slugspeed
slugspeed

Reputation: 17

Accessing an array in PHP from Javascript/jQuery

I have all my html, php and javascript/jquery code in a single file. I have an array $arr in php (json_encode($arr)) which when printed shows the data in php. How do I access it in javascript. The array contains all the rows from the resultset of a query execution. I have looked up jsonParse and var json_obj = but have not got any results. I am newbie so any help is appreciated. My code so far in php :

$result_again = $conn->query($sql_again);
if ($result_again->num_rows > 0) 
{
    $resultarray = array();
    while($row_again = $result_again->fetch_assoc()) 
    {
        $resultarray[] = $row_again;
    }
}
echo json_encode($resultarray);

My code in the .js file :

 $( document ).ready(function() {
 $.ajax({
      type: "GET",
      dataType: "json",
      url: "secondform.php",
      success: function(data) {
        alert("Result: " + data);
      }
    });
});

Upvotes: 1

Views: 279

Answers (1)

Sharn White
Sharn White

Reputation: 624

Step 1:

Render json_encode($arr) into javascript string variable.

var json = '<?= json_encode($arr) ?>';

Step 2:

Parse JSON string into javascript object.

var obj = JSON.parse(json);

Or if you're using jQuery:

var obj = jQuery.parseJSON(json);

You now have a javascript object which you can access properties of like below :)

alert(obj.title); // show object title
alert(obj[0].id); // grab first row of array and show 'id' column

Edit -- in reply to slugspeeds update

Ok, so looks like you're doing this the AJAX way using jQuery. Since your PHP script is using json_encode() the jQuery $.ajax() should return an javascript array object.

$( document ).ready(function() {
    $.ajax({
      type: "GET",
      dataType: "json",
      url: "secondform.php",
      success: function(arr) {
        console.log(arr); // show array in console (to view right-click inspect element somewhere on screen, then click console tab)

        $.each(arr, function( index, row ) { // loop through our array with jQuery
            console.log('array row #'+index, row); // show the array row we are up to
            // you can do what you want with 'row' here
        });

      }
    });
});

For reference: https://developer.chrome.com/devtools/docs/console

Upvotes: 2

Related Questions