user5493899
user5493899

Reputation:

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

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.

Upvotes: 1

Views: 61

Answers (4)

RiggsFolly
RiggsFolly

Reputation: 94672

It seems to be you are making life rather more complicated that you need to.

With a simple change to your query, to return just what you want and to rename the column names at the same time (not sure why thats necessary but) you could do this. Then with the use of mysql_fetch_assoc() you get all you want without all that complex result jiggling.

$result = mysql_query("SELECT StateC as state, Comment as comment,
                              Date1 as date1, Date2 as date2 
                       FROM Cstate 
                       WHERE cod = $id ORDER BY Cod2 ASC");

$arr2 = array();
while($row = mysql_fetch_assoc($result))
{
      $arr2[] = $row;
}
echo json_encode($arr2);

This will create an arr2 containing multiple rows which are also arrays.

I personally would go for sending an array of objects as objects are a breeze to use when the data gets to the javascript.

$result = mysql_query("SELECT StateC as state, Comment as comment,
                              Date1 as date1, Date2 as date2 
                       FROM Cstate 
                       WHERE cod = $id ORDER BY Cod2 ASC");

$arr2 = array();
while($row = mysql_fetch_object($result))
{
      $arr2[] = $row;
}
echo json_encode($arr2);

Now using the mysql_fetch_object() approach, your javascript for the success processing could also be simplified to :-

success: function(data) {
    var temp = '';
    for (i=0; i<data.length; i++) {
        temp += "<b> state: </b> " + data[i].state + "<br>"
             + "<b> comment: </b> " + data[i].comment + " <br>"
             + "<b> date1: </b> " + data[i].date1 + " <br>"
             + "<b> date2: </b> " + data[i].date2 + " <br>";
    }
    $('.comments').html(temp);
 },

NOTE: This also fixes the overwriting of the $('.comments').html in your original javascript code, which would have only shown the data from the last array occurance.

Upvotes: 2

jeroen
jeroen

Reputation: 91742

You are overwriting your results in the loop:

  $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");));

Now you will generate a new array with 1 key - value pair each time so you will end up with information from only the last row that was found.

What you want, is something like (I also removed some syntax errors in the array itself...):

$arr2 = array();
while($i < $num)
{
  // or $arr2["$i"] depending if you want numerical or string keys
  $arr2[$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"));

And you should use PDO or mysqli in combination with prepared statements to avoid potential sql injection problems.

Upvotes: 1

Parth Chavda
Parth Chavda

Reputation: 1829

     $i=1; use this because on  `json_encode($arr2);` throw a error sometime 

 $arr2[$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, "Date");

Upvotes: 0

GordonM
GordonM

Reputation: 31750

For associative arrays or arrays with missing indicies JSON always encodes them as a javascript object. When decoded by json_decode they will be converted to PHP objects.

If you want them to be decoded as arrays you need to call json_decode with the correct parameters.

json_decode ( $json, TRUE );

All of this is in the PHP manual for json_decode.

Upvotes: 0

Related Questions