Mj1992
Mj1992

Reputation: 3504

$.ajax values not returning correctly

I am trying to get returned values from database from a PHP array to a JavaScript array. So far what I've done is returning the values as a string and I want each value as an array index.

This is my jQuery AJAX Call:

    $.ajax({
          type: 'GET',
          url: "Profile_Control.php",
          data:"ajaxRequest=yes&id="+document.getElementById("compid").value,
          success:function(data)
          {       
              document.getElementById("asd").innerHTML=data;
          }
        });

and this is my PHP script so far, which is returning the values like a string and I want each value in the array index.

   $branches=Profile_Model::getCompanyBranches($_GET['id']);

    while($row=mysql_fetch_array($branches))
    {
        echo $row[3];
    }

Now I am only echoing column 3 of the values returned from database and the output is like this:

        67.030867.020467.031167.020667.0357

and the result I want should be like this.

   arr[0]=67.0308
   arr[1]=67.0204
   arr[2]=67.0311
   arr[3]=67.0206
   arr[4]=67.0357

I also tried encoding the data in JSON by using json_encode($row[3]); but it returns me the following result.

  "67.0308""67.0204""67.0311""67.0206""67.0357"

Upvotes: 1

Views: 72

Answers (2)

aabreu
aabreu

Reputation: 335

Create a new array with each element being $row[3], send the new array via json_encode.

Right now you're just json_encoding each $row[3] individually.

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318488

Create an array with the elements you eventually want in your JS array and then json_encode that array:

$rows = array();
while($row=mysql_fetch_array($branches)) {
    $rows[] = $row[3];
}
echo json_encode($rows);

However, data will be an array in your success callback so you cannot simply assign it to the innerHTML property of an element. But since that seems to be debug output simply replace it with console.log(data);.

Upvotes: 2

Related Questions