0

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>

2
  • 4
    Why not use JSON? Commented Dec 14, 2016 at 14:48
  • I have tried using JSON.parse(), but it didn't worked out. Commented Dec 14, 2016 at 14:49

3 Answers 3

3

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);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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);
    });
});

Comments

0

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
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.