Cannot populate JSON request with correctly formatted data - php

I am trying to populate JSON request with the data coming back from my phpsearch.php file (shown here)
<?php
include "base.php";
$name = $_GET["name"];
$query = "SELECT lat, lng FROM markers WHERE name = '".$name."'";
$result = mysql_query($query);
$json = array();
while($row = mysql_fetch_array ($result))
{
$bus = array(
'lat' => $row['lat'],
'lng' => $row['lng']
);
array_push($json, $bus);
}
$jsonstring = json_encode($json);
echo $jsonstring;
?>
The data shows in the console in this format:
[{"lat":"37.730267","lng":"-122.498589"}]
The route calculation function is at the bottom of the question, I previously had used an asynchronous JSON rewquest but this was causing the code to execjte before the origin value was set, now it is being set but it looks incorrect
How can I make sure my latitude and longitude results are in the correct JSON format? currently the JSON request looks like this:
Request URL:https://maps.googleapis.com/maps/api/js/DirectionsService.Route?4b0&5m4&1m3&1m2&1dNaN&2dNaN&5m4&1m3&1m2&1d37.738029&2d-122.499481&6e1&8b1&12sen-GB&100b0&102b0&callback=_xdc_._1rqnjk&token=80599
Route calculation code:
function calcRoute() {
var startname = document.getElementById('start').value;
var endname = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
$.ajax({
url:'phpsearch2.php',
dataType:'html',
data:{name:startname},
async:false,
success:function (result)
{
console.log(result)
origin = new google.maps.LatLng(result[0].lat, result[0].lng);
}});
var end = new google.maps.LatLng('37.738029', '-122.499481');
var request = {
origin: origin,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
document.write('<b>'+ origin +'</b>');
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Time for a Walkabout </b><br>';
summaryPanel.innerHTML += '<b>From ' + startname + ' </b>';
summaryPanel.innerHTML += '<b>to ' + endname + '('+ route.legs[i].distance.text +')</b><br>';
}
}
});
}

The LatLng constructor takes two numbers as arguments, you're passing it a JSON object. Get the latitude and longitude properties out and pass the numbers directly, like this:
function (result){
origin = new google.maps.LatLng(result[0].latitude, result[0].longitude);
}
I'm guessing on the specific properties, you may want to console.log(result) to see the exact object structure.

Related

Ajax never initiating success: when using xhrFields

I am having trouble getting the success call to fire in my ajax request. I know the communication is working fine, but the last call in my PHP script, which is a return json_encode($array); will fire as if it is a part of the onprogress object. I would like to "break" the onprogress call and run the success function on the last data sent via return json_encode when the PHP script has terminated...
Here is my AJAX call:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
dataType: "json",
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = data;
}
});
e.preventDefault();
});
});
And here is the basic PHP server script:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count < 100){
progress_message($count, "working....");
$count += 10;
sleep(2);
}
return json_encode($array);
?>
I made your code work, there were 2 errors. First, in your while loop, your function name is incorrect, try this:
progress_msg($count, "working... ." . $count . "%");
Secondly, the very last line outputs nothing, so technically you don't get a "successful" json return. Change the last line of your server script from:
return json_encode($array);
to:
echo json_encode($array);
UPDATE: Full working code with hacky solution:
Ajax:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
dataObjects = data.split("{");
finalResult = "{" + dataObjects[dataObjects.length - 1];
jsonResponse = JSON.parse(finalResult);
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = jsonResponse.msg;
}
});
e.preventDefault();
});
Search.php:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count <= 100){
progress_msg($count, "working... " . $count . "%");
$count += 10;
sleep(1);
}
ob_flush();
flush();
ob_end_clean();
echo json_encode($array);
?>
The problem with the "success" method of the ajax call was that it couldn't interpret the returning data as JSON, since the full return was:
{"progress":0,"msg":"working... 0%"}{"progress":10,"msg":"working... 10%"}{"progress":20,"msg":"working... 20%"}{"progress":30,"msg":"working... 30%"}{"progress":40,"msg":"working... 40%"}{"progress":50,"msg":"working... 50%"}{"progress":60,"msg":"working... 60%"}{"progress":70,"msg":"working... 70%"}{"progress":80,"msg":"working... 80%"}{"progress":90,"msg":"working... 90%"}{"progress":100,"msg":"working... 100%"}{"msg":"hello world"}
Which is not a valid JSON object, but multipje JSON objects one after another.
I tried removing all previous output with ob_end_clean(); , but for some reason I can't figure out, it didn't work on my setup. So instead, the hacky solution I came up with was to not treat the return as JSON (by removing the dataType parameter from the AJAX call), and simply split out the final Json element with string operations...
There has got to be a simpler solution to this, but without the use of a third party jQuery library for XHR and Ajax, I couldn't find any.

Unable to return latitude/longitude result to Javascript JSON from PHP MySQL query

I am trying to return database values for latitude and longitude from a PHP/MySQL query to my Javascript function in order to populate a google maps JSON request.
My PHP/MySQL query script, phpsearch2.php is:
<?php
include "base.php";
$name = $_GET["name"];
$query = "SELECT lat, lng FROM markers WHERE name = '".$name."'";
$result = mysql_query($query);
while($row = mysql_fetch_array ($result))
{
echo '{';
echo '"latitude":"'.$row['lat'].'",';
echo '"longitude":"'.$row['lng'].'",';
echo '}';
}
?>
It returns a value in this format:
{"latitude":"37.730267","longitude":"-122.498589",}
Here is my calculate root function, when I run the program I get an error saying 'origin is not defined' even though I think I am setting it to have the same value as the return result from the JSON request to phpsearch, I just don't know where the mistake lies.
function calcRoute() {
var startname = document.getElementById('start').value;
var endname = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
$.getJSON("phpsearch2.php", {name : startname}, function (result) {
origin = google.maps.LatLng('result');
});
var end = new google.maps.LatLng('37.738029', '-122.499481');
var request = {
origin: origin,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
//document.write('<b>'+ start + end + '</b>');
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Time for a Walkabout </b><br>';
summaryPanel.innerHTML += '<b>From ' + startname + ' </b>';
summaryPanel.innerHTML += '<b>to ' + endname + '('+ route.legs[i].distance.text +')</b><br>';
}
}
});
}
You are passing 'result' in as a string. You need to pass the result object, without the quotes:
var origin = google.maps.LatLng(result);
Keep in mind that $.getJSON is asynchronous. You probably need to wrap the rest of your gmaps code in a function declaration, and call that function in the $.getJSON callback after origin is set. Otherwise you're still trying to use origin before it has been fetched from the server.
Something like:
$.getJSON("phpsearch2.php", {name : startname}, function (result) {
var origin = google.maps.LatLng(result);
// Now that we have our origin, we can initialize the rest
init(origin);
});
function init(origin) {
var end = new google.maps.LatLng('37.738029', '-122.499481');
var request = {
origin: origin,
<snip>
}

JQuery Post Not Passing Data Values to Php File

I am using the jQuery function $.post to pass some values to a php file, which then uses those values to refer to a mySQL database and parse out the resulting value in the post success function. However for some reason when I try and grab the data in the php file using the $_POST tag I am getting the notice that the indexes are undefined. Here is my js code:
var curX = 2;
var curY = 6;
function move(moveX, moveY) {
var position = {
x: curX + moveX,
y: curY + moveY
}
$.post('php/tilecheck.php', position, function(data) {
//console.log(data);
curX += moveX;
curY += moveY;
var n = data.split("\"");
boundary(n[3], n[1]);
boundary(n[7], n[5]);
boundary(n[11], n[9]);
boundary(n[15], n[13]);
/*boundary(data.left,'left');
boundary(data.right, 'right');
boundary(data.top, 'top');
boundary(data.bottom, 'bottom');*/
})
}
function boundary(value, pos) {
if(value == 1){
$("#a" + pos).css('display', 'none');
}
else {
$("#a" + pos).css('display', '');
}
}
And the php file it refers to:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include('db-info.php');
$x = $_POST['x'];
$y = $_POST['y'];
if(!empty($_POST)) {
$q = "SELECT * FROM tiles WHERE xpos = ".($x - 1)." AND ypos = $y LIMIT 1";
$lefttile = mysql_fetch_assoc(mysql_query($q));
$q = "SELECT * FROM tiles WHERE xpos = ".($x + 1)." AND ypos = $y LIMIT 1";
$righttile = mysql_fetch_assoc(mysql_query($q));
$q = "SELECT * FROM tiles WHERE xpos = $x AND ypos = ".($y - 1)." LIMIT 1";
$toptile = mysql_fetch_assoc(mysql_query($q));
$q = "SELECT * FROM tiles WHERE xpos = $x AND ypos = ".($y + 1)." LIMIT 1";
$bottomtile = mysql_fetch_assoc(mysql_query($q));
$json = array(
"left" => $lefttile['bound'], "right" => $righttile['bound'],
"top" => $toptile['bound'], "bottom" => $bottomtile['bound']
);
$output = json_encode($json);
echo $output;
}
else
echo "No value";
?>
Whats weird is even though the values are undefined in the php, it still outputs the correct data in an array, which is confirmed by the console log. However, to access those values in the array I have to use the fixed call to the function boundary(), while the commented out code doesn't work. Please let me know if you have any ideas or questions. Thank you.
One try from me .. You have JSON responde.. so you can use it.
!! There is need to be added one check before the LOOP, to see if the responde is successfull or not how ever this is my idea ..
$.ajax({
url: 'php/tilecheck.php',
data: position,
type: 'POST',
dataType: 'json',
success: function(data) {
$.each(data, function(key,value){
if(value == 1){
$("#a" + key).css('display', 'none');
}
else {
$("#a" + key).css('display', '');
}
});
}
});
Check what you get from jQuery in PHP :
print_r($_POST);
and check the proper naming of 'x' and 'y'

Retrieving JSON formated results using php post request in ajax via jquery, to be used in adding google map Marker closed

Just doing a small project relating to google maps.
Basically I have coordinates in a database that I want to retrieve using ajax, and update the map without the need to refresh the page.
php part:-
$deviceID = $_POST['deviceID'];
$sqlLocation = "SELECT * FROM Location WHERE DeviceID = '".$deviceID."' AND Type ='network'";
$sqlResult = mysql_query($sqlLocation);
while($row = mysql_fetch_assoc($sqlResult))
{
$response["uid"] = $row["DeviceID"];
$response["deviceInfo"]["Longitude"] = $row["Longitude"];
$response["deviceInfo"]["Latitude"] = $row["Latitude"];
$response["deviceInfo"]["Type"] = $row["Type"];
$response["deviceInfo"]["latlontime"] = $row["latlontime"];
echo json_encode($response);
}
the format of the multiple json result :-
{"uid":"*deviceID here*","deviceInfo":
{"Longitude":"x.xxxxxxx","Latitude":"x.xxxxxxx","Type":"network","latlontime":"2012-05-05 18:55:12"}
}
{"uid":"*deviceID here*","deviceInfo":
{"Longitude":"y.yyyyyyyyy","Latitude":"y.yyyyyyyyy","Type":"network","latlontime":"2012-05-05 18:55:56"}
}
javaScript part with some pseudo code sorry !
var map;
var count =0;
function initialize(DeviceID)
{
if(DeviceID!=null)
{
$.ajax({
type:"POST",
dataType:"json",
data:{deviceID: DeviceID},
url: "json_coords.php",
contentType: "application/json; charset=utf-8",
success: function(data)
{
*****problem used be here******
var len = data.length;
for( var i = 0; i<len; i++)
{
var json_row = data[i];
var latitude = json_row.deviceInfo.Latitude;
var longitude = json_row.deviceInfo.Longitude;
var title = "pos: "+i+json_row.deviceInfo.Type + " "
+json_row.deviceInfo.latlontime ;
//alert_test(latitude,student.Longitude);
setMarker(latitude,longitude,title);
*********************************************************************************
}
}
});
}
else
{
// do nothing
}
var latloncenter = new google.maps.LatLng(51,-1.4469157);
var myOptions =
{
zoom: 4,
center: latloncenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function setMarker(lat,lon,titletxt)
{
var latlongMarker = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker
(
{
position: latlongMarker,
map: map,
title:titletxt
}
);
}
the initialize function will be called after pressing a certain divs on the website:-
$('#leftcolumn>a').click(function()
{
var deviceID = $(this).attr("name");
//alert(deviceID);
initialize(deviceID)
});
I would really appreciated if you can help me out
Thank you :)
* the original problem was around how to retrieve data from a php page with json results**
the Ajax function of jQuery (in JSON mode) expected a unique json object, you ara sending 2, the format is invalid.
You can do:
$response = array();
while($row = mysql_fetch_assoc($sqlResult))
{
$response[] = (object) array(
'uid' => $row["DeviceID"],
'deviceInfo' => (object) array (
'Longitude' => $row["Longitude"],
'Latitude' => $row["Latitude"],
'Type' => $row["Type"],
'latlontime' => $row["latlontime"]
)
);
}
echo json_encode($response);
And onsuccess callback:
success: function(data) {
$.each(data, function (device) {
var title = device.Type + ' ' + device.latlontime;
setmarker( device.Longitude ,device.Latitude , title);
});
}
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&region=GB"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body onload="initialize();">
<div id="map_canvas" style="height:300px;width:500px"></div>
Load markers
<script type="text/javascript">
var map;
var count =0;
function initialize()
{
var latloncenter = new google.maps.LatLng(51,-1.4469157);
var myOptions =
{
zoom: 4,
center: latloncenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function loaddata(DeviceID)
{
if(DeviceID!=null)
{
$.ajax({
type: "POST",
dataType: "json",
data:{deviceID: DeviceID },
url: 'mapdata.php',
success: function(data)
{
$.each(data,function(index,value) {
console.log(value);
/// I know there is no such thing as data.jsonGetvalueByID just trying to explain what I want to do
var longitude = value.deviceInfo.Longitude;
var latitude = value.deviceInfo.Latitude;
var type = value.deviceInfo.Type;
var time = value.deviceInfo.latlontime;
var title = type + " " +time;
//calling function to add map marker
createmarker(longitude, latitude, title);
});
}
});
}
}
function createmarker(lat,lon,titletxt)
{
var latlongMarker = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker
(
{
position: latlongMarker,
map: map,
title:titletxt
}
);
return marker;
}
</script>
</body>
</html>
// my ajax file that just fakes the data needed, so replace with your database code.
<?php
$response = array();
$rows = array();
$rows[] = array("DeviceID"=>1,"Type"=>"Network","Longitude"=>"51.4343","Latitude"=>"-2.344","latlontime"=>date("Y-m-d H:i:s"));
$rows[] = array("DeviceID"=>2,"Type"=>"Network","Longitude"=>"55.4343","Latitude"=>"-2.644","latlontime"=>date("Y-m-d H:i:s"));
foreach ($rows as $row)
{
$data["uid"] = $row["DeviceID"];
$data["deviceInfo"]["Longitude"] = $row["Longitude"];
$data["deviceInfo"]["Latitude"] = $row["Latitude"];
$data["deviceInfo"]["Type"] = $row["Type"];
$data["deviceInfo"]["latlontime"] = $row["latlontime"];
$response[] = $data;
}
echo json_encode($response);
?>

How to put my JSON info into a jQuery Array

I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.

Categories