I am trying to decode JSON in php I sended using an ajax call in javascript (jquery).
The javascript code:
var editSchedule_data = {
'action' : 'editSchedule',
'eventid' : $('#eventid').val(),
'pixels_per_minute' :$('#pixels_per_minute').val(),
artists: {
artist: []
}
}
$('.artist').each(function(index) {
var id=$(this).attr('id');
id=id.split('_');
editSchedule_data.artists.artist.push({
'artistid' : id[0],
'stageid' : id[1],
'left' : $(this).offset().left-$('.artists').offset().left,
'width' : $(this).width()
});
});
$.ajax({
type : "POST",
url : "callback.php",
data : editSchedule_data,
dataType : "json",
async : true,
success : function(json) {
if(json.success) {
showSucces(json.message);
}
else{
showError(json.message);
}
},
error: function(error){
alert("An error occurred: "+error.message);
}
});
The php-code:
$clean = sanitize($_POST);
echo(json_encode($clean['artists']),
json_last_error());
echo(json_decode($clean['artists']),
json_last_error());
My output:
encode:
{"artist":[{"artistid":"4","stageid":"3","left":"360","width":"240"},{"artistid":"3","stageid":"4","left":"120","width":"240"},{"artistid":"1","stageid":"5","left":"120","width":"180"},{"artistid":"2","stageid":"5","left":"300","width":"120"},{"artistid":"5","stageid":"6","left":"480","width":"120"}]}
0
decode:
0
Can someone tell me how to get the decode function to work?
Why are you trying to use json_decode there? You already have the data as array in $_POST.That’s why json_decode fails and retuns NULL…it expects a properly formated string and you are passing it an array.
If the dataType : “json” parameter confuses you, it specifies the type of the data you are expecting back from the server not the type of the data you are sending.
You shoud simply process the data from $_POST, create your response , apply json_encode on it and echo the resulted string.