Search code examples
phpjqueryajaxajaxform

Sending data via Ajax from form


I need to update row in database by id using Ajax.

My Form:

<form id="update_ajax">
     <input type="text" name="name" class="test_hide">
     <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
     <input type="submit" value="<?php echo $row['id']; ?>" class="pure-button">
</form>

My Ajax function:

$("#update_ajax").on("submit", function () {
        var id = $(this).attr('id');
        var name = $(this).attr('name');
        var dataall={'id' : id, 'name' : name};
        $.ajax({
            type: "post",
            url: "update.php",
            data: dataall,
            success: function (data) {
                alert(data);
            }
        });
    });

And my php file is:

if ((isset($_GET['id'])) && (isset($_GET['name']))) {
    $id = $_GET['id'];
    $name = $_GET['name'];
}else{
    die("Not set");
}
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "8169x5it");
$query = $pdo->prepare("UPDATE test SET name=:name WHERE id=:id");
$query->bindParam(':name', $name);
$query->bindParam(':id', $id);
$query->execute();

And I have the error that my name value is not set in $_GET['name']. And I can't understand why it's not set. Because I send it in data.


Solution

  • This is wrong:

    var id = $(this).attr('id');
    var name = $(this).attr('name');
    

    $(this) is the form, so $(this).attr('id') is "update_ajax", not the value of the hidden input. And $(this).attr('name') is undefined because the form doesn't have a name=something attribute. What you really want is:

    var id = $(this).find("input[name=id]").val();
    var name = $(this).find("input[name=name]").val();
    

    But you can simplify it all to:

    var dataall = $(this).serialize();
    

    serialize() will find all the inputs in the form and return a URL-encoded string containing all their values.

    Finally, you either have to change the jQuery to use type: 'GET', or change the PHP to use $_POST instead of $_GET.