The JS
Serializing data from a FORM, stringify it and POST it as JSON with AJAX to update.php
jQuery.fn.serializeObject = function () {
var formData = {};
var formArray = this.serializeArray();
for(var i = 0, n = formArray.length; i < n; ++i)
formData[formArray[i].name] = formArray[i].value;
return formData;
};
$(function() {
$('form').submit(function() {
data = $('form').serializeObject();
alert(JSON.stringify(data));
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'inc/update.php',
data: {json: JSON.stringify(data)},
dataType: 'json'
});
});
});
The update.php file where it should be decoded to an array
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$name = $response['name'];
$update = $pdo->prepare("UPDATE user SET name='".$name."' WHERE id='3';");
$update->execute();//the SQL works fine with String for $name
With Tamper Data addon in Firefox i checked the POSTDATA, here it is:
json=%7B%22name%22%3A%22fff%22%7D
This is like:
json={"name":"fff"}
I'm new at JS/AJAX/JSON and I cant find my mistake. So please help me.
I've searched for many hours without success.
Don't know what's the point of writing serializeObject function, when you can just use serializeArray.
Javascript:
$(function() {
$('form').submit(function(e) {
e.preventDefault(); // Stop normal submission, which is probably why your PHP code isn't working
data = $('form').serializeArray();
alert(JSON.stringify(data));
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'inc/update.php',
data: {
json: JSON.stringify(data)
},
dataType: 'json'
});
});
return false;
});
PHP:
$str_json = _$_POST['json'];
$response = json_decode($str_json, true); // decoding received JSON to array
$name = $response['name'];
If you use true as 2nd argument in json_decode it returns an array not object.
So you need to do
$name = $response['name'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With