I want to take an external json file (locations.json) and load the contents into a variable. I would then like to use this variable using the information provided here: http://www.json.org/js.html
I've had a lot of trouble trying to load the external json to a variable. I've looked at this ( load json into variable ) page quite a bit, and none of that actually populates the variable. When displaying the variable's contents later, it appears to be empty.
$("#testContain").html("<p>" + json + "</p>");
Using methods listed in the last link, this dispays "undefined".
The json file that I am using looks like this:
[{"id":"1","locname":"Dunstable Downs","lat":"51.8646","lng":"-0.536957","address":"Chiltern Gateway Centre","address2":"","city":"","state":"England","postal":"","phone":"","web":"http:\/\/www.nationaltrust.org.uk\/main\/w-dunstabledownscountrysidecentrewhipsnadeestate","hours1":"","hours2":"","hours3":""},
{"id":"2","locname":"West Delta Park","lat":"45.5974","lng":"-122.688","address":"N Broadacre St and N Expo Rd, Portland","address2":"","city":"","state":"OR","postal":"","phone":"","web":"http:\/\/en.wikipedia.org\/wiki\/Delta_Park","hours1":"","hours2":"","hours3":""}]
Anyone have any suggestions?
The problem is that the request is asynchronous. You could make a synchronous call as suggested by the accepted answer to the question that you linked to, but that is generally not a good idea as it will freeze the browser completely while it is waiting for the response.
The variable is assigned just fine, but when you use it after requesting it, you have to make sure that it's after getting the response, not just after sending the request. Using the value in the callback for the getJSON method is the easiest way to make sure that you have the value:
var my_json;
$.getJSON(my_url, function(json) {
my_json = json;
// here you have the value
});
// here you don't have the value, as this happens before the response arrives
Related
I send a http GET request which returns JSON data in the following form. I am finding it impossible to access this data despite having no problems with example json that I create. I want to ideally take the array under wifi, and use this data to create a html table, but I think I can work out how to create the table if I could just access the actual elements of the data.
I have tried multiple methods to try and reach the first timestamp. I have tried:
var element = result.undefined.clients.wifi[0].timestamp;
but this returns an error that 'clients' can't be found.
I also tried:
var element = result.clients.wifi[0].timestamp; //and
var element = result.wifi[0].timestamp;
The JSON data returned to a variable is shown below:
result = undefined
{"sourceId":"idid","sourceType":"CLOUD_source","searchMeta":{"maxResults":4,"metricType":["clients"],"family":["wifi"],"Interval":"M1"},
"clients":{"wifi":
[{"timestamp":1424716920,"avg":3,"min":1,"max":4,"Count":8,"sCount":3,"sources":["x1","x2","x3","x4","x5","x6","x7","x8"]},{"timestamp":1424716980,"avg":2,"min":1,"max":3,"Count":4,"sCount":2,"sources":["x3","x4","x8","x4"]},{"timestamp":1424717160,"avg":2,"min":1,"max":3,"Count":9,"sCount":4,"sources":["x3","x4"]}]}}
The JSON data is invalid. If it is returned from a server, you need to go there and correct the data source, (if you have access to that).
Otherwise, perhaps notify the backend guy(s) about it.
If it is from a REST API, and you are "sure" that the server code should be error free, then check that you have supplied all the required parameters in the API request you are making.
I think your JSON is messed up. I ran it through JSONLint, and having the undefined at the beginning causes things to break.
What are some arguments as to when to use JSON external file such as with jQuery's
$.getJSON('external.json',function(data){});
(ajax retrieving) versus defining it in javascript with
var myJson = { "someVar": { "1": ["test1","test2"], "2": ["test3","test4"]} }
What is the "proper" way of doing it? Does it depend on JSON length or are there any other factors that can tell you what approach to use?
The way I see it: choose between loading another file which is supposed to be slow as you are loading data via ajax call or adding plenty of lines into already packed javascript file which is not a good thing either. Surely there must be some distinction as to where you should use one or another ... ?
I am not interested only in speed difference (getting file from ajax is of course slower) but also in other aspects such as what is generally used when and what should be used in some case ...
The first one is a shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
This is an Ajax request which will take more time than having a simple JSON object into the file.
I would prefer the second one IF it's possible. Also if you attend to have good performances the first one is longer.
time( Loading+parsing 2 files ) >> time( Read a Javascript object )
If your data is known at page creation time you're probably best to use an object literal like:
var myJson = {...}
However, as Kursion mentions,
$.getJSON(...)
is a shorthand method for retrieving json data asynchronously via ajax. You'd use it if you want to retrieve data from the server that wasn't known at the time of page load...
For example, if a user enters a search term in an input control, you might want to retrieve JSON in response to that without performing a whole page update. You couldn't simply define a javascript object up-front because you wouldn't know what the search term was in advance.
I searched around, and couldn't find an answer to my question. I'm very new at coding, and at work, we have an application that current names that are logged in, and what they are doing.
Recently, they have changed from jquery 1.4.1 to jquery 1.8.3. Ever since then, I cannot get the results to process correctly, because of the following error;
"Unable to get value of the property 'split': Object is null or undefined"
I have the code setup to grab the results and split them;
function processAgents(xData, status) {
var avail = xData.responseText.split("|")[0];
var acw = xData.responseText.split("|")[1];
var total = xData.responseText.split("|")[2];
var breaks = xData.responseText.split("|")[3];
var pending = xData.responseText.split("|")[4];
The application is setup to open as an HTA file which opens up the PHP script.
Any help would be appreciated, please let me know if I left anything out!
Thanks!
EDIT 1
I did some more investigating, and it looks like I'm not getting data from my process request. This is how it is currently setup
function updateAgents() {
var ts1 = new Date().getTime();
$.ajax({
url: "http://SERVER/AgentSrc.php?x=" + ts1,
complete: processAgents
I'm not sure if this is processing correctly since they went to jquery 1.8.3.
EDIT 2
So after looking into it more, it doesn't appear that the script is getting the data from the server, even though I have access. If I make a local file and put the information in it, it will pull the information and split it, but if I point to the path of the file on the server, it won't get the information. But the strange thing is, if I run it using jquery 1.4.1, it pulls the data fine, but can't display it. But with 1.8.3, it doesn't allow me to pull it from the server.
thanks again!
This will give some clarity
xData.responseText.toString().split("|")[0];
(split is part of string not jQuery)
Here is a possible explanation: in earlier versions of jQuery, ajax calls returned an xmlHttpRequest (XHR) object. Recent versions return a promise (jqXHR) instead.
See this page for more details.
I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});
I'm quite a beginner in JS and even more in jQuery UI. I don't understand if my problem has a very simple synchronous solution, or if I need to write callback functions to cope with something that cannot be anything else than asynchronous...
I had this in a script associated with an HTML document:
var json = "[{ ... some object ... }]"
As the JSON object must be changed, I've created a text file and moved the value into it. Now I've to read the value from the file to assign it to the variable.
I see that when in production, the HTML page will be served by an HTTP server, and the file must be remotely retrieved using HTTP on the server. But also that if I want to test the page on my development machine, with no server, this is just reading a local file.
Is there a single piece of code that can read the JSON value in both situation, in a synchronous mode, so that something like this would be possible:
var json = ... piece of code...
I initially thought using:
$.getJSON("file.json", function(obj) { json = obj; });
expecting a read error would lead to json variable being the empty or null, but it seems the call is asynchronous and requires more code in callback functions.
Any guidance appreciated.
First of all, the call definitely should be synchronous. Just move the rest of your code into the callback, it's not that hard - and it will make your browser responsive while the file is downloaded.
If this is really a big problem, you can use the async option in $.ajax:
$.ajax({
async: false,
url: 'file.json',
dataType: 'json',
success: function (value) { json = value; }
});
Note: This will only work if the file you're requesting is from the same domain, and may or may not fail for local files, depending on the browser.