Logan 96
Logan 96

Reputation: 83

Ajax post data through name

If I add caption to image it's working, if I add one more caption without refreshing the page the 1st value is posting to the second one...

$(document).ready(function () {
    $(".cap_btn").click(function(){
        var li = $(this).closest("li");
        var cap = $('input[name="cap"]').val();
        $.ajax({
            type: "POST",
            url: "addcap.php",
            data: { id: li.data("imageId"), "cap": cap},
            success: function(data){
                alert("Caption Added");
            },
            error: function(){
                alert("failure");
            }
        });
    });
    });

php code:

if(isset($_POST['id'])){
    $ids = $_POST['id'];
    $cap = $_POST['cap'];
    try
    {

        $query = "UPDATE image SET caption='$cap' WHERE id='$ids'";
        $sql=$con->prepare($query);
        $sql->execute();
    }
    catch(PDOException $e)
    {
        echo $sql . "<br>" . $e->getMessage();
    }
}

Upvotes: 0

Views: 79

Answers (1)

IRONALEKS
IRONALEKS

Reputation: 50

You can do it like this

$(document).ready(function () {
$(".cap_btn").click(
    function()
    {
        var xmlhttp = new XMLHttpRequest();

        xmlhttp.onreadystatechange = function()
        {
            if (this.readyState == 4 && this.status == 200)
            {
                alert("Caption Added");
            }
            else
            {
                alert("failure");
            }
        };

        xmlhttp.open("POST", "addcap.php", true);

        var formdata = new FormData();

        var li = $(this).closest("li");
        var cap = $('input[name="cap"]').val();

        formdata.append("id",li.data("imageId"));
        formdata.append("cap",li.data("cap"));

        xmlhttp.send(formdata);
    });
});

Hope it helps :)

Upvotes: 1

Related Questions