YSuraj
YSuraj

Reputation: 417

Get php array in jQuery?

Trying to retrieve the values of name and city in jquery. It seems PHP result is returned as an array in jQuery.

<?php 
$val = array(
    name => $_POST["name"],
    city => $_POST["city"]
);

foreach($val as $res) {
    echo $res;
}
?>

$(document).ready(function(){
    $.post("get.php",
        {
            name : "fakename",
            city : "fakecity" 
        },
        function(data){
            // returns name and city as a single array
            alert(data);
            // how to get it as an associative array
            // desired result :
            //* alert(data.name); 
            //* alert(data.city);
        }
    );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Views: 1252

Answers (3)

RiggsFolly
RiggsFolly

Reputation: 94682

Send the data as a JSON String, then in javascript it is recieved as a javascript object.

Use the 4th param on the jQuery.post( url [, data ] [, success ] [, dataType ] ) call to specifiy to the js that data will be returned as json.

<?php

    $val=array(
             name => $_POST["name"],
             city => $_POST["city"]
            );
    echo json_encode($val);
?>

Then in the js

$(document).ready(function(){
      $.post("get.php", {name : "fakename",city : "fakecity"},
             function(data){
                //alert(data);
                alert(data.name); 
                alert(data.city);
       },'json');                    // extra param specifying returned data will be json
  });

Upvotes: 0

Stuart
Stuart

Reputation: 6780

In your PHP, just return a json encoded array:

<?php
$val=array(
    name => $_POST["name"],
    city => $_POST["city"]
);
echo json_encode($val);
?>

and then in your JS you can pretty much do as you were:

$(document).ready(function(){
    $.post("get.php",
    {
        name : "fakename",
        city : "fakecity" 
    },
    function(data){
        // returns name and city as a single array
        alert(data);
        // how to get it as an associative array
        // desired result :
        //* alert(data.name); 
        //* alert(data.city);
    });
});

Upvotes: 0

HeavyNounours
HeavyNounours

Reputation: 418

Use JSON :

<?php

$val = [
    'name' => $_POST["name"],
    'city' => $_POST["city"]
];
echo json_encode($val);
die(); 

?>

In your JS :

$.ajax({
    url: 'get.php',
    type: 'POST',
    data: {
        name: 'fakename',
        city: 'fakecity'
    },
    dataType: 'json'
}).done(function(ret){
    console.log(ret.name, ret.city);
});

Upvotes: 3

Related Questions