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>
RPichioli
3,3553 gold badges27 silver badges31 bronze badges
-
4Why not use JSON?Machavity– Machavity ♦2016年12月14日 14:48:11 +00:00Commented Dec 14, 2016 at 14:48
-
I have tried using JSON.parse(), but it didn't worked out.YSuraj– YSuraj2016年12月14日 14:49:29 +00:00Commented Dec 14, 2016 at 14:49
3 Answers 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);
});
answered Dec 14, 2016 at 14:52
HeavyNounours
4183 silver badges17 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
});
});
answered Dec 14, 2016 at 14:53
Stuart
6,7692 gold badges29 silver badges42 bronze badges
Comments
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
});
answered Dec 14, 2016 at 14:54
RiggsFolly
94.7k22 gold badges108 silver badges152 bronze badges
Comments
default