Reputation: 37
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.
Upvotes: 3
Views: 305
Reputation: 37
I found the Problem with our Help: The JSON-String was not correct
Explained step by step:
$str_json = file_get_contents('php://input');
echo $str_json;//json%3D%5B%7B%22name%22%3A%22Max%22%2C%22value%22%3A%22testvalue%22%7D%5D
$str_json = urldecode($str_json);
echo $str_json;//json=[{"name":"Max","value":"testvalue"}]
$str_json = str_replace('json=', '', $str_json);
echo $str_json;//[{"name":"Max","value":"testvalue"}]
//now it is a json-string which can be json_decoded
$arr_json = json_decode($str_json, true);
$name = $arr_json['name'];
echo $name;//Max
Thanks a lot guys!
Upvotes: 0
Reputation: 4337
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'];
Upvotes: 5