Website not reading the correct local json - javascript

I have made a HTML site that reads a .json with javascript/jQuery and writes to it with PHP.
I then have a c++ backend that writes and reads to the same .json.
I want to be able to send what button is selected by the players to the c++.
The .json that javascript reads isn't always the .json that I have modified with PHP or C++.
It won't always have the updated data, the time to get the updated data can be instant, a few seconds or e few minutes.
I have tried to remove caching and I have checked that the file gets updated
To load the .json on the website I use:
var $JSONList = $('#JSONList');
$.getJSON("json/playerMode.json", function(json) {
console.log(json); // this will show the info it in firebug console
var stringed = JSON.stringify(json);
var response = JSON.parse(stringed);
console.log(response); // this will show the info it in firebug console
$.each(response, function(i, itt){
$JSONList.append( "</br>" + itt.Name + " has pressed: " + itt.Button + " :(())");
})
});
This is called by a <button>
Since this sometimes won't load the updated .json, is there some way that I can force javascript to load the local .json again?

First, let's make the assumption this url works - except the caching issue and address that and other things as noted.
Change from the shortcut "json/playerMode.json" to $ajax
Force to NOT cache the results
Added a fail just in case
fixed syntax for "<br />"
removed unneeded code as the JSON would be parsed already as long as it is valid. IF it is not valid JSON and it only returns "a string, that looks like JSON", you should use dataType: "text json" to force jQuery conversion/parse
or consider using a converter (see below)
MIGHT need header('Content-Type: application/json') for PHP
if you are NOT returning a true JSON string, use a converter to make it into one, see Using Converters here: https://api.jquery.com/jQuery.ajax/
This from https://api.jquery.com/jquery.ajax/
Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET
parameters.
$.ajax({
type: "GET",
url: "json/playerMode.json",
cache: false,
data: "",
dataType: "json" // force automatic parse of the JSON string returned
}).done(function(json) {
console.log(json); // this will show the info it in firebug console
// should not need
// var stringed = JSON.stringify(json);
// not needed, see above
// var response = JSON.parse(json);
//console.log(response); // this will show the info it in firebug console
//$JSONList - what is this? it should be in here somewhere...so I did that
let $JSONList = $('#JSONList');
// should be parsed already, so changed to that
$.each(json, function(i, itt) {
$JSONList.append("<br />" + itt.Name + " has pressed: " + itt.Button + " :(())");
}).fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="JSONList"></div>

Related

Get JSON data from WFS/Geoserver

I am struggling with getting data from WFS in my GeoServer. I want to get specific properties from the JSON returned by WFS and use it in my html page filling a table. I have read lots of posts and documentation but I can't seem to make it work. I have:
(a) changed the web.inf file in my geoserver folder to enable jsonp
(b) tried combinations of outputFormat (json or text/javascript)
(c) tried different ways to parse the JSON (use . or [], JSON.parse or parseJSON etc),
(d) used JSON.stringify to test whether the ajax call works correctly (it does!!)
but, in the end, it always returns undefined!!
function wfs(longitude, latitude){
function getJson(data) {
var myVar1=data['avgtemp1'];
document.getElementById("v1").innerHTML = myVar;
}
var JsonUrl = "http://88.99.13.199:8080/geoserver/agristats/wfs?service=wfs&version=2.0.0&request=GetFeature&typeNames=agristats:beekeeping&cql_filter=INTERSECTS(geom,POINT(" + longitude + " " + latitude + "))&outputFormat=text/javascript&format_options=callback:getJson";
$.ajax({
type: 'GET',
url: JsonUrl,
dataType: 'jsonp',
jsonpCallback:'getJson',
success: getJson
});
}
wfs(38, 23);
Could you please help me?
You are close to it. First, you have a typo in the variable name you are writing (myVar1 vs myVar). Secondly, your function is receiving a Json object, so you must dive into its structure. First you get the features, then the 1st one, then the property array, then the property of your choice.
I suggest you read a tutorial on Json Objects, as you will surely want to loop through properties/items, validate they are not null etc.
function getJson(data) {
var myVar1=data.features[0].properties['avgtemp1'];
document.getElementById("v1").innerHTML = myVar1;
}
At last, don't forget to use the debugger in your favorite browser. put a breakpoint in your function and check the structure and content of data.

How to parse JSON in PHP and pass it to Javascript?

This is my goal: Use twitter api to populate some slides with recent tweets without reloading the page.
The way I have it right now is this: I'm making an ajax call every few seconds from a javascript on my page to a php page. The php page sets up and authenticates a connection to Twitter and gets a responce in JSON format. Now here is my problem, the JSON responces I get are all mix and match some are arrays some are stdClass objects. Ideally I would like to pass this JSON directly to Javascript as an object, so inside Javascript I can do something like this, jsonresponce->statuses->text.
Keeping that in mind here is the same structure I described but in code:
Front End->
// JavaScript Document
function AJAXToTwitter(){
console.log("making ajax call");
$.ajax({
url: '../php/twiter-stream.php',
type: 'GET',
success: function(responce) {
$.each(responce, function(i, obj){
$(".LiveSlide1 .text").html(obj.text);
});
console.log("ajax call successful");
},
error: function(errors) {
console.log("ajax call failed");
}
})
}
$(document).ready(AJAXToTwitter);
Back End ->
//PHP Document
<?php
require "../vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumerKey = "iNol________________n5uVZcAB";
$consumerSecret = "o_______________________l1_J";
$accessToken = "142480736-jlOVy___________________________________tm5b7ZN";
$accessTokenSecret = "K___________________________________________wF__V";
function getToken( $apiKey, $apiKeySecret, $axToken, $axTokenSecret ) {
$connection = new TwitterOAuth( $apiKey, $apiKeySecret, $axToken, $axTokenSecret );
return $connection;
}
$connection = getToken($consumerKey, $consumerSecret, $accessToken,
$accessTokenSecret);
$urlQuery = "#WebDesign";
$search = $connection->get("search/tweets", ["q" => $urlQuery]);
echo (json_encode($search));
?>
The problem here is that I think that the responce in the case of search/tweets query is a class so json_encode produces a string and I'm unable to use $.each function. The exact error in Chrome Dev Tools Console says
Uncaught TypeError: Cannot use 'in' operator to search for '70806' in
{"statuses":[{"created_at":"Sun Jun 11 17:15:40 +0000 .......
and it goes on to spit out the whole json string that I encoded.
My question is what is the proper way to handle JSON in general when dealing with an API like this, should I just avoid using PHP and do a direct call from JavaScript? Should I manually extract every responce and encode it in a smaller, handmade json? Or is there a way to just pass the response unmodified back to javascript?
So after some trial and error I got it to work. The PHP file is the same, in the JavaScript I had to do this:
$.ajax({
url: '../php/twiter-stream.php',
type: 'GET',
success: function(responce) {
//added this line to parse the json string into JS object
var parsedJSON = JSON.parse(responce);
//now just iterating over the object to extract the info
$.each(parsedJSON.statuses, function(i, obj) {
var slideIndex = (i + 1) % 7;
$(".LiveSlide" + slideIndex+ " .text").html(obj.text);
$(".LiveSlide" + slideIndex+ " .Date").html(obj.created_at);
});
console.log("ajax call successful");
},
error: function(errors) {
console.log("ajax call failed");
}
})
This is the way I think it works, inside the PHP the TwitterOAuth::get() function retrieves a JSON string from the Twitter server, encodes it into a class. In order to pass it to javascript I needed to convert that class back to a string, that's done with json_encode(). Then inside the javascript we convert it back into an object using either JSON.parse() like I did here or you can also probably specify " dataType: 'json' " in the jQuery ajax call as #Joe Black suggested.

AJAX and JSON error handling

I have a form which submits data via AJAX to an external server.
The data which gets sent is then validated and if correct the user can then advance onto the next step of the form.
If the data is not valid, then the server returns an error which is outputted as a JSON object.
I can see the JSON object in FIDDLER.
My aim is to grab that JSON data and output it on the page and notify the user.
Ideally, i would do this as part of an error handler on the AJAX request(found below).
Is this achievable?
PS:
Unfortunately, I can't set up a demo because the link that the data is posted to is only available on my network.
It is also worth pointing out that the error that the back-end script outputs is actually stored in the link that the data is posted to.
AJAX REQUEST:
var setUpVrmData = function() {
$("#getvrmdata").click(function () {
var p_vrm = $('#p_vrm').val();
$.ajax({
dataType: "JSON",
type: "POST",
url: "http://217.35.33.226:8888/l4_site/public/api/v1/BC8F9D383321AACD64C4BD638897A/vdata",
data: {
vrm: p_vrm,
},
success: function(data) {
//Empty the dropdown box first.
$("#p_model").empty();
appendString = "<option value='none'>-- Select your model --</option>";
$.each(data['vehiclemodel'], function (k, v) {
// += concatenate the string
appendString += "<option value='" + k + "'>" + v + "</option>";
});
$("#p_model, #ent_mileage").show();
$('.js-find-my-car').hide();
$('.js-get-price').show();
$("#p_model").append(appendString);
$("#p_model").prop("disabled", false);
$('#skey').val(data['skey']);
},
error: function() {
console.log("We return error!");
}
});
});
The Error function will return an XHR object that you may be able to parse to get the message you want. I don't know what is serving the data so depending on how that's setup your mileage may vary. I've done this using PHP as well as C# and writing to Console, but in both cases I was able to control the returned data.
I used this article : http://encosia.com/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/ as a starting point.
You'll need to update:
error: function() {
console.log("We return error!");
}
to
error: function(xhr, status, error) {
console.log("We return error!");
}
Set a break point there in Firebug to check if an XHR object is passed, if not you'll need to find a way to get it.. You mention you can see the JSON in fiddler, it should be available to you. If it is, just use the eval posed in the article and you should be okay. If not you'll have to go and figure out how to get it, depending on your platform difficulty will vary.
A few things to note, eval is messy and can get you into trouble. In the cases I've done this, I removed the eval in production.
Also as of jQuery 1.8 success error and complete are deprecated. Use done fail and always if you plan on updating jQuery in the future.
jQuery API reference, for reference.
http://api.jquery.com/jquery.ajax/

JSON returned from ASP.NET not usable in JS

I'm returning a DataSet converted to JSON via a jQuery AJAX call, all is well! The request I receive back is:
{"Table":[[2,"BlackBerry Tour","2013-09-10","2013-09-13","Project"],null]}
Looks valid to me, also ran it through JSLint validator, again, all is well! Now, whenever I try to access any of this data, I simply receive undefined from the following:
var dataObject = data.d //data.d is the response from the server and what is logged above
console.log(dataObject.Table) //undefined
console.log(dataObject["Table"]) //undefined
Now, if I run JSON.parse(dataObject), I can then access it alright. This is a problem right now however, since the site this will reside on sticks IE into IE7 mode, and JSON is always undefined according to IE (I know, IE7, it's out of my hands tho).
So my question is why can I not use the returned JSON as is? why must I run it through JSON.parse before using it? More info is available on request (AJAX call, DataSet converter, etc)
AJAX Call, per request:
$.ajax({
type: "POST",
url: "DBManager.asmx/GetAdminList",
contentType: 'application/json',
data: '{"strEmail": "' + strFilter + '" }',
dataType: "json",
success: function (data) {
console.log(data.d); //valid JSON response.
}
});
If you returning back a string you have to somehow parse it into an object. E.g.
var data = '{"Table":[[2,"BlackBerry Tour","2013-09-10","2013-09-13","Project"],null]}';
var dataJ
eval('dataJ = ' + data )
alert(dataJ.Table)
http://jsfiddle.net/uvvAm/
If you're using jQuery you can use
var dataJ = $.parseJSON(data);
This is preferable, since eval is open to all kinds of attacks.
var dataObject = eval('(' + data + ')');
alert(dataObject.Table);
Try this thing may help you.

JQuery parse JSON

I'm fairly new to JQuery. The code below works and I can see the correct JSON response in Firebug. But I couldn't find a way how to get and parse it in the code. Alert window only shows
"[object Object]" but not any json text.
<script>
$.ajaxSetup({ cache: false });
var _token;
function make_token_auth(user, token) {
var tok = user + ':' + token;
return "Token " + tok;
}
$.ajax
({
type: "GET",
url: "url",
dataType: 'json',
beforeSend: function (xhr){
xhr.setRequestHeader('Auth', make_token_auth('userid', 'token'));
},
success: function (data){
alert(data);
}
});
</script>
The fact you precised
dataType: 'json',
tells jQuery to parse the received answer and give it as a javascript object to your success callback.
So what you have here is fine and what is alerted is correct (this is an object, so
alert simply prints the result of data.toString()).
Use console.log to see what it is exactly :
success: function (data){
console.log(data);
}
and open the developer tools in Chrome or the console in Firebug to browse the properties of the object.
don't use alert() for debugging -- it's often unhelpful (as in this case), and also has serious issues when used with asyncronous code (ie anything Ajax) because it interrupts the program flow.
You would be much better off using the browser's console.log() or console.dir() functions, and seeing the object displayed in the console. It is much more functional, and doesn't interrupt the flow of the program.
So instead of alert(myjsonvar) use console.log(myjsonvar).
You can get the json string by using JSON.stringify
var jsonstr = JSON.stringify(data);
alert(jsonstr);
The alert function expects you to pass in a string or number.
Try doing something like this:
for(x in data) {
alert(x + ': ' + data[x]);
}
Update in response to comments: You can use alert in development or production to see string and number values in the object returned by the server-side code.
However, carefully rereading your question, it looks like what you really want to see is the actual JSON text. Looking at #dystroy's answer above, I think that if you remove the dataType: 'json' from your $.ajax invokation, jQuery will treat the response as plain text instead of automatically converting it to an Object. In this case, you can see the text by passing it to the alert function.
Try using
data = JSON.parse(data)
Then do whatever you want with the data.
Source: JSON.parse() (MDN)

Categories

Resources