Reputation:
i need to seperate two variables which i got from the server and i m using $.post method. but when i m doing it i m getting the combined mixed value from this method. here is the code
$(".spot_me").click(function()
{
var idea = $(this).attr("id");
var idea1 = $(this).attr("data");
alert(idea);
alert(idea1);
$.post('spot_me.php', 'val=' + idea + '&tim=' + idea1, function (data)
{
alert(data);
});
});
here var id is a userid. i wish to get the coordinates which this user had stored in the database. my php code for abc.php is
<?php
session_start();
$value = $_POST['val'];
$value1 = $_POST['tim'];
$con=mysqli_connect("localhost","root","******","anurag");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result2 = mysqli_query($con,"SELECT latitude,longitude FROM notifications WHERE uid='$value' AND time='$value1' ");
if(!$result2)
{
echo "Error in query";
}
else
{
$row = mysqli_fetch_array($result2);
$lat = $row['latitude'];
$lon = $row['longitude'];
echo $lat;
echo $lon;
}
?>
now i want to get this lat and lon value separately in my jquery $.post method in the parameter data. how can i get these values separately and "I WANT TO STORE THEM IN TWO DIFFERENT VARIABLES IN $.POST METHOD" how can i do this
Upvotes: 0
Views: 123
Reputation: 129
//From the server
$row = mysqli_fetch_array($result2);
return json_encode($row);
//and on the client
var dataasjson = $.parseJSON(data);
$.each(dataasjson, function(index, element) {
element.name //this is your label i.e databse field name as key
dataasjson[element.name] //this is your long/lat value
});
Upvotes: 0
Reputation: 3682
you can do it by returning you output as JSon and then parse that JSON in Javascript.
In PHP file do like this: (instead of returning two variables)
echo json_encode(array('latitude' => $row['latitude'],'longitude'=> $row['longitude']));
Response will be like this (test values use)
{"latitude":123,"longitude":456}
in you Jquery Ajax code where you return response use JSON parse method
var obj = $.parseJSON(data );
alert( obj.latitude)
alert( obj.longitude)
Upvotes: 0
Reputation: 56982
At PHP
$row = mysqli_fetch_array($result2);
echo json_encode($row);
At jQuery
$.post('spot_me.php', 'val=' + idea + '&tim=' + idea1, function (data)
{
var response = jQuery.parseJSON(data);
alert(response.latitude);
alert(response.longitude);
});
This is just an indicator oh how to do it, and not tested.
Upvotes: 0
Reputation: 2800
You'll use JSON to communicate between the languages.
Your PHP will transform the array into JSON:
else
{
$row = mysqli_fetch_array($result2);
echo json_encode($row);
}
And your javascript will treat the data
as an object, because you've told the .post()
function to expect json
var post_str = 'val=' + idea + '&tim=' + idea1;
$.post('spot_me.php', post_str, function (data)
{
alert(data.latitude);
alert(data.longitude);
}, 'json');
Upvotes: 1
Reputation: 817
Upvotes: 0