I am trying to print the results of a json object from a php query into javascript.
So basically the query results looks like:
{"points":
[{"lat":40.766696929932,"long":-73.990615844727},
{"lat":40.688514709473,"long":-73.96475982666},
{"lat":40.714504241943,"long":-74.005630493164},
{"lat":40.704719543457,"long":-74.009262084961},
{"lat":40.693260192871,"long":-73.968894958496},
{"lat":40.760955810547,"long":-73.967247009277},
]}
When i try to get the php variable (using AJAX) containing the json object i get:
VM62:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
I tried googling to see how the error relates to my code but i still don't get it.
Can someone explain to me how to get the json in javascript?
<?php
$connect = pg_connect("host=127.0.0.1 dbname=datab user=thomas password=iamtom") or die("Could not connect: ");
$result = pg_query($connect,"SELECT geometry FROM table");
if (!$result){
echo '{"error":"no results"}';
}
$points= array();
while($row = pg_fetch_array($result)){
$coordinate = json_decode($row['geometry'])->coordinates;
$p = new stdClass;
$p->lat = $c_2[0];
$p->long = $c_1[1];
array_push($points, $p);
}
$output = new stdClass;
$output->points = $points;
echo json_encode($output);
pg_close($connect);
?>
Here is my HTML/JS:
<html>
<head>
<title>Simple Map</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$.ajax({
type: "GET",
dataType: "JSON",
url: "dab.php",
data: {
sataVariable: "here is some data send with GET method"
},
success: function(data) {
var j = JSON.parse(data);
document.writeln(data); // attempting to take the coordinates and store it in a variable
},
error: function(data) {
console.log(data);
}
});
</script>
</head>
<body>
</body>
</html>
Because you're feeding dataType: "JSON" into your call to jQuery.ajax() the data retrieved from the AJAX call is automatically being parsed from JSON to a JavaScript object (though I'd switch "JSON" to "json" to match the documentation):
"json": Evaluates the response as JSON and returns a JavaScript object.
Don't manually parse the response again using JSON.parse() in your success handler; just work directly with data.
Now that you have your data in a JavaScript object called data you can interact with it, e.g.
for (var i = 0; i < data.points.length; i++) {
console.log(data.points[i].lat, data.points[i].long);
}
Related
I'm trying to extract the information with a XHR request (AJAX) to a php file (this php file gets the information throught json file with Get request too) so when I try to do console.log(Checker) on the console, it returns Undefined and if I put alert(Checker) it returns [object Object]. How can I solve it?
PHP:
<?php
headers('Content-Type', 'application/json')
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents
?>
JS:
function start() {
$.ajax({
type: 'GET',
url: 'api/domain/showall.php',
dataType: 'json',
success: function(data) {
alert(data)
displayTheData(data)
}
});
}
function displayTheData(data) {
Checker = data;
JSON.stringify(Checker)
console.log(Checker)
window.Checker = Checker;
}
JSON:
[{"name":"Google","url":"google.es","id":1}]
Here you are strigify data but not store value i any var.
function displayTheData(data) {
Checker = data;
var displayChecker = JSON.stringify(Checker) /// add displayChecker
console.log(displayChecker ) // print it
window.Checker = Checker;
}
There is not displayTheData() function so first call it and pass response params.
You need to echo the JSON Response ! Change return $jsonContents; to echo $jsonContents; it will work !!!
You must parse data into body (not returning it which has no meaning outside a function) and, optionnaly but much better, fill some headers. A very minimalistic approach could be :
<?php
headers('Content-Type', 'application/json');
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents // echo JSON string
?>
I'm trying to make a simple ajax call:
When the user selects and option, some info about that option will be
echoed into a div (this is dynamic)
Here's my code for the ajax call
ajax.js
$(document).ready(function()
{
//Add Event
//Currently Broadcasting #Zone
$('#beacon0').on('change', function ()
{
var Selected = $(this).find("option:selected");
var SelectedText = Selected.text();
var SelectedEncoded = encodeURIComponent(SelectedText);
$.ajax
({
url: 'ajax-addevent.php',
data: 'n_beacon='+ SelectedEncoded,
dataType: 'JSON',
success: function(returnClass)
{
var resultajax = jQuery.parseJSON(returnClass)
console.log(resultajax);
},
error: function(xhr, status, error)
{
var errors = JSON.parse(xhr.responseText);
console.log("failed");
console.log (errors);
}
});
});
});
SO the ajax call should give the name of the zone in the URL, so I can $_GET the parameter in my php script. This is the php I run just to test the ajax call.
ajax-addevent.php
<?php
include("classes/event.class.php");
$event = new Event();
$GetZoneName = $_GET['n_beacon'];
$ZoneName = urldecode($GetZoneName);
$arrayDetails = $event->getBeaconEvent($ZoneName);
while($row = mysqli_fetch_array($arrayDetails))
{
$EventTitle = $row["n_title"];
$EventLink = $row["n_link"];
$EventDate = $row["n_date"];
}
$arr = array( "EventTitle" => $EventTitle,
"EventLink" => $EventLink,
"EventDate" => $EventDate );
header("content-type:application/json");
$json_arr = json_encode($arr);
return $json_arr;
?>
My problem is that the ajax call fails and gives me this as result:
What's wrong why my ajax call? Can you help?
EDIT Update Code:
You're trying to get an XML response when the returned datatype is JSON - xhr.responseXML will always be undefined unless the response is valid XML.
Try using xhr.responseText instead. You can use JSON.parse(xhr.responseText) to get a javascript object out of it.
Another good technique is to use the dev tools of your current browser to inspect the network response directly (F12 in Firefox or Chrome, then open the Network tab).
I am using a jquery ajax get method to fetch information from the server however I am having trouble parsing the information so that I may use it. My website has a gallery of products that will filter its items based on category.
Here is the jQuery ajax function:
$('.category').click(function() {
var category;
if ($(this).hasClass('Shirts')) {
category = 'shirts';
}
if ($(this).hasClass('Hats')) {
category = 'hats';
}
if ($(this).hasClass('Acc')) {
category = 'acc';
}
$.ajax({
type: 'GET',
url: 'galleryfetch.php',
data: { 'category' : category },
dataType: 'json',
success: function(data) {
arr = $.parseJSON(data);
alert(arr);
}
});
});
This is the php script that the information is posted to:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$category = $_GET['category'];
$conn = mysqli_connect('localhost', '*****', '*****', 'clothing');
$rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");
while ($row = mysqli_fetch_array($rows)) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
}
I using the alert in the success function to see if the information is passed succesfully but at the moment there is no alert and i get an:
Unexpected token o error.
I'm not sure if I'm parsing the information correctly or if Im not correctly using JSON
tl;dr: $.parseJSON(data); should be removed.
Your server is returning JSON (but claiming it is sending HTML, you should have header("Content-Type: application/json")).
You have told jQuery to ignore the claim that it is HTML and parse it as JSON. (This would be redundant if you fixed the above problem)
dataType: 'json',
The parsed data is passed to your success function.
You then pass that data to JSON.parse so it gets converted to a string (which will look something like [ [Object object], ... and is not valid JSON) and then errors.
Remove:
arr = $.parseJSON(data);
And just work with data.
I am working on parsing a json script queried through ajax from my database. I want to use what I queried (in a json format) in my javascript function "addComp()" that adds a geometric component for each building on a map. Here is the jQuery/ajax code:
$.ajax({
type: "GET",
url: "ajax_processor.php",
dataType : "json",
success:function(data){
console.log(data); //here I got what i want
var geometryElement = $.parseJSON(data);
for (var i=0; i<geometryElement.length; i++) {
addComp( geometryElement[i].bldg,
geometryElement[i].iZ,
geometryElement[i].iType,
geometryElement[i].x0,
geometryElement[i].y0,
geometryElement[i].p, ...); //parameters p1, p2, p3, p4, p5
}
}
});
The JSON script I got, queried through PHP is :
{"ID_geometryElement":"1","bldg":"1","iZ":"1","iType":"1","x0":"23","y0":"5","p1":"5","p2":"2","p3":"3","p4":"0","p5":"0"},
{"ID_geometryElement":"2","bldg":"1","iZ":"1","iType":"1","x0":"24","y0":"7","p1":"2.5","p2":"4","p3":"3.5","p4":"0","p5":"0"},
...
But that doesn't display anything on the map, and I got the following errors:
Uncaught SyntaxError: Unexpected token o jquery.js:550
jQuery.extend.parseJSON jquery.js:550
$.ajax.success index_LF.php:3725
fire jquery.js:3074
self.fireWith jquery.js:3186
done jquery.js:8253
callback jquery.js:8796
handleStateChange firebug-lite.js:18917
Does anyone know where it comes from and how to fix it ?
EDIT: on the PHP side, I got :
<?php
$host = 'localhost';
$databaseName = 'localdb';
$tableName = 'building_geometry';
$user = 'admin';
$password = 'password';
$connexion = mysql_connect($host,$user,$password);
$dbs = mysql_select_db($databaseName, $connexion);
$sql = mysql_query('SELECT * from building_geometry');
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
echo json_encode($rows);
?>
but the problem is not in the php, I was parsing twice what was already in json (dataType is json).
That is not valid JSON. It looks like an array literal but it's missing the outer square brackets.
That is,
{"foo": 0, ... },
{"bar": 1, ... },
is invalid, but it would be valid if it were
[{"foo": 0, ... },
{"bar": 1, ... }]
Anyway, if you're telling jQuery that the data type is JSON, and it really is JSON, then you don't have to parse it. The "data" parameter will be the parsed object, not the unparsed string.
I have a session array $_SESSION['Cartquantity'] . In php file on line no 200 I am storing this array in a variable $QtyArray
$QtyArray = $_SESSION['Cartquantity'] ;
then I am encoding the array in json to use it on js file
echo "var cartQty = " . json_encode($QtyArray) . ";" ; (on line 201)
Now via the AJAX I am updating the session array on line no 120 in the same way
$QtyArray = $_SESSION['Cartquantity'] ; (on line 120)
echo "var cartQty = " . json_encode($QtyArray) . ";" ; (on line 121)
This is my javascript code to call file
$.ajax({
url:'index.php',
cache:false,
datatype:'json',
data:{ q: "add_card", item_id: id, item_qty: qty,stop:'1' },
success:function(data){
$("#cart_quanity").html(parseFloat($("#cart_quanity").html()))
}
});
return false ;
array is clearly updating because I can see this on console of firebug. But when I am getting this value on js file value is not changing. While if I reload the page where I update this value via ajax and then go to view quantity it is changing. Why is that happening ?
Please help!!!
Your server-side handler for the ajax request should just return the data literal itself.
On the client parse that data and then handle it there - not as a "complete" javascript snippet but just as an data object. JQuery supports you with the parsing part. Just let it auto-guess the type of the response or define it when calling $.ajax or $.post.
$.post(url, data, function(response) {
// you cann assume response to be an object
// containing the data from the json-response of the server
}, "json");
self-contained example (doing nothing useful):
<?php
if ( isset($_POST['foo']) ) {
// the client requests a new item
$rv = array(
'status'=>'ok',
'value'=>rand(1,10)
);
header('Content-type: application/json');
echo json_encode($rv);
die;
}
?>
<html>
<head>
<title>...</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var total = 0;
$(".foo").on("click", function() {
$.post("?", { foo: true }, function(data) {
if ( data.status && "ok"==data.status ) {
var newValue = data.value;
total += newValue;
$("#output").append("+ "+newValue+" = "+total+"<br />");
}
}, "json");
});
});
</script>
</head>
<body>
<button class="foo">click</button>
<div id="output">0<br /></div>
</body>
</html>