Reputation: 273
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.
Upvotes: 0
Views: 517
Reputation: 780974
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
.
Upvotes: 2
Reputation: 1291
What you have, http://api.jquery.com/attr/
What you wanted http://api.jquery.com/val/
Give that a shot, it should work doesn't look like any other errors in your source. If not let us know.
EDIT:
Also you change:
$(this).attr('id');
$(this).attr('name');
To
$("input[name=id]").val();
$("input[name=name]").val();
Or
$(this).serialize();
See https://api.jquery.com/serialize/ for the later
Upvotes: 0