Reputation: 5270
I have this AJAX:
$.ajax({
url : get_base_url() + 'update',
type : 'POST',
async : false,
data : json_positions,
dataType : 'html',
success : function(data) {
console.log(data);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log('error:');
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown)
}
});
data sent is:
json_positions
which is a string like this:
{"new_positions" : [{ "id": "2", "position": "0"},{ "id": "5", "position": "1"},{ "id": "4", "position": "2"}]}
I want to decode json_positions using json_decode() in a PHP page but it seem that tdata is not sent to the php page because when i try to:
print_r($_POST);
it returns an empty array using console.log(data).
Upvotes: 0
Views: 869
Reputation: 6530
$_POST
only contains key value pair stuff. Your POSTed JSON is in $_HTTP_RAW_POST_DATA
.
Upvotes: 0
Reputation: 193301
Well your code is okay, no need to change anything. But it's how you pass your data.
data sent is:
json_positions
which is a string like this: ...
You should not pass it like string. It should be an object like you defimed it:
{"new_positions" : [{ "id": "2", "position": "0"},{ "id": "5", "position": "1"},{ "id": "4", "position": "2"}]}
Make you sure you pass an object, not string, e.g. don't add any quotes around it etc. Then it's going to work fine.
As per jQuery documentation for $.ajax data parameter:
dataObject, String Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So your data should be a query string or an object.
In your case I recommend to use object. Like with this code:
var json_positions = {
new_positions: []
};
$.each(result, function(key, value) {
var value_splitted = value.split('-');
json_positions.new_positions.push({
id: value_splitted[1],
position: key
});
});
Upvotes: 2
Reputation: 104196
Since you are sending json data, you need to define the appropriate content type:
contentType: 'application/json'
Also, change the dataType to json if you are expecting json data back:
dataType : 'json'
Upvotes: 1