Mason White
Mason White

Reputation: 155

PHP array to JavaScript array using json_encode()

How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.

JavaScript code:

$.ajax({
         method:"POST",
         url:'php.php',
         data:"",
         dataType:'json',
         success:function(data){
             var y1=data;
             console.log(data.name);
         }
      });

PHP code:

<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //assign vars after formatting to avoid a wrong login with correct 
    //username and password
    $username = trim($_POST["user"]);


   $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer_array[] = $customer1;

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer_array[] = $customer2;

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    echo json_encode($customer_array);
}

Upvotes: 0

Views: 77

Answers (3)

Tom Udding
Tom Udding

Reputation: 2294

You where almost there. Your AJAX requests accepts JSON but your PHP does not output JSON (it does but not in the correct way), you'll have to set the appropriate Content-Type header:

header('Content-Type: application/json');
echo json_encode($customer_array);

Your AJAX request should now be able to use the properly formatted JSON as the data variable (and console.log it).

Upvotes: 0

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

As has been mentioned, there are multiple options for passing the data from PHP:

  • add the Content-Type header with value application/json before sending the return from json_encode() to echo():

    header('Content-Type: application/json');
    echo json_encode($customer_array);
    
  • Parse the return from the PHP using JSON.parse()

    success:function(data){
        var y1=data;
        var data = JSON.parse(data);
    

So pick one of those approaches. One might argue that the first is more semantically correct, since JSON data is being sent.

Additionally, the success callback of the AJAX request is attempting to access the property name of the data returned. However, the data returned should be an array of objects, each which has a property name. One approach to logging the name of each property is to use Array.forEach() and send the name of each element in the array to console.log().

data.forEach(function(dataItem) {
    console.log(dataItem.name);
});

See a demonstration of this in this phpfiddle.

Upvotes: 0

Rasclatt
Rasclatt

Reputation: 12505

I am just going to summarize my comments into an answer, first I would just turn off the json return for trouble shooting. You can parse the json after fact anyway:

$.ajax({
    // Do "type" here
    type:"POST",
    url:'php.php',
    // Send something to check in the script
    // This is optional, but I like to do it...
    data: {
        "action":"get_name_city"
    },
    success:function(data){
        // Do a try, just incase your parse fails
        try {
            // Parse the json here
            var getJson = JSON.parse(data);
            console.log(getJson);
            console.log(data);
        }
        catch(Exception) {
            // Show any errors that might get thrown
            console.log(Exception.message);
        }
    }
});

PHP:

# Check the action is set and is named
if(isset($_POST["action"]) && $_POST["action"] == "get_name_city") {
    $username = trim($_POST["user"]);
    $customer_array = array();

    $customer1 = array(
        'name' => '3',
        'city' => 'Houston'
    );

    $customer2 = array(
        'name' => '2',
        'city' => 'Boston'
    );

    $customer3 = array(
        'name' => "1",
        'city' => "Bossier City"
    );

    $customer_array[] = $customer1;
    $customer_array[] = $customer2;
    $customer_array[] = $customer3;

    # Just die here
    die(json_encode($customer_array));
}
# Die with error so there is some feedback to your ajax
die(json_encode(array('error'=>'No data was sent.')));

Upvotes: 1

Related Questions