I'm trying to use JSON data format together with jQuery and, well, it would be surprising if it worked.
In my remoteServiceEngine.php, I have something like this:
$jResponse[0] = json_encode(array("jAction" => "add", "jObject" => "listCountries", "jBody" => "test"));
$json_data = json_encode(array("jRequestState" => $jRequestState, "jMessage" => $jMessage, "jResponse" => $jResponse));
echo $json_data;
And this is how it is handled in JS:
success: function(remoteResponse){
switch(remoteResponse.jRequestState) {
case 0:
$("#removeServiceMessage").fadeIn(2000).html('<div class="remoteError">'+remoteResponse.jMessage+'</div>').fadeOut(2000);
break;
case 1:
$("#removeServiceMessage").fadeIn(2000).html('<div class="remoteSuccess"><B>Success:</B> '+remoteResponse.jMessage+'</div>').fadeOut(2000);
for (i = 0; i < remoteResponse.jResponse.length; i++) {
switch(remoteResponse.jResponse[i].jAction) {
case "add":
$("#"+remoteResponse.jResponse[i].jObject).fadeIn(1000).append(remoteResponse.jResponse[i].jBody);
break;
case "remove":
$("#"+remoteResponse.jResponse[i].jObject).fadeOut(1000);
break;
case "update":
$("#"+remoteResponse.jResponse[i].jObject).fadeIn(1000).html(remoteResponse.jResponse[i].jBody);
break;
default:
alert(remoteResponse.jResponse[i]);
break;
}
}
break;
}
}
The whole problem is that I cannot access successful content. With $jRequestState = 1 and the forementioned $jResponse[0], switch goes directly onto default and this is the output I get:
{"jAction":"add","jObject":"listCountries","jBody":"test"}
but I cannot figure out how to access these elements. I tried it with:
alert(remoteResponse.jResponse[i]['jAction']);
and
alert(remoteResponse.jResponse[i][0]); //yeah, that's kinda stupid solution, but well...
Since I've never used JSON with jQuery, I can't figure out how to deal with that. Help, anybody?
Like adeneo said in the comment you jsonencode twice. Your php code should look like:
$jResponse[0] = array("jAction" => "add", "jObject" => "listCountries", "jBody" => "test");
$json_data = json_encode(array("jRequestState" => $jRequestState, "jMessage" => $jMessage, "jResponse" => $jResponse));
echo $json_data;