How to properly write code in order to send a php muliple array to JSON?

Wednesday, November 4, 2015

I need to perform a task which consists in sending a php multiple array to JSON, but it doesn't work and i don't know if i am missing something!



Since it is 2 days that i am having this trouble i decided asking here, because i haven't found nothing much on how properly write the code, especially for the php part.



How can i improve this code in order to make it work? Is the php part done correctly? What function should i use, if there are, to make everything going right?



AJAX call:



    function ajaxcall(ID)
{
$.ajax({
type: 'POST',
url: 'visualize.php',
data: {id: ID},
dataType: 'json',
success: function(data) {
for (i=0; i<data.length; i++)
{
var state = data.i.state;
var comment = data.i.comment;
var date1 = data.i.date1;
var date2 = data.i.date2;
$('.comments').append("<b> state: </b> " + state + "<br>"
+ "<b> comment: </b> " + comment + " <br>"
+ "<b> date1: </b> " + date1 + " <br>"
+ "<b> date2: </b> " + date2 + " <br>");
}
},
error : function(err, req) {
alert("SOMEWHING WENT BAD");
}
});
}


visualize.php



    $id = $_POST['id'];
$result = mysql_query("SELECT * FROM Cstate WHERE cod = $id ORDER BY Cod2 ASC");
$num = mysql_num_rows($result);
$i=0;
while($i < $num)
{
$arr2 = array("$i" => array('state' => mysql_result($result, $i, "StateC"),
'comment' => mysql_result($result, $i, "Comment"),
'date1' => mysql_result($result, $i, "Date1");,
'date2' => mysql_result($result, $i, "Date2");));
$i++;
}
echo json_encode($arr2);


EDIT: if i print the "arr2" in my browser it works as a proper JSON string.

0 comments:

Post a Comment