Get json data from server - javascript

I am trying to get a json array of ints from a server by sending the server a get request. When I run the code below the server receives the request. How can I print the data the server sends back? The second alert() doesn't show.
$(document).ready(function(){
alert("READyS");
$("button").click(function(){
$.getJSON("http://localhost:8080/Data/", function (data) {
alert("data recieved");
});
});
});

Since you are using jQuery you can use this:
$("button").click(function(){
$.get( "http://localhost:8080/Data/" )
.done(function( data ) {
alert( "Data Loaded: " + data );
});
});
Obs.: Please be more specific about what button is.
If still don't work, paste your html here

You can use a callback function passed to success state of the AJAX request. This way you're using the async nature of the request, which doesn't block the browser call stack while it's waiting for requested data and You're getting the result printed to the page. This is just a single p element that has all the request's information inside of it, so it will work if it's just a string. If it's an array of objects or something like that then you can create a map function with printData function inside it to loop through all of the downloaded objects.
function printData(passedData) {
jQuery('<p/>', {
id: 'foo',
text: passedData
}).appendTo('body');
}
function testAjax(handleData) {
$.ajax({
url:"http://localhost:8080/Data/",
success:function(data) {
handleData(data);
}
});
}
testAjax(printData);

Related

Aborting / canceling running AJAX calls before execute new AJAX in JS

I've never done this type of manipulation of AJAX calls (to stop/abort/cancel or ignore? already running AJAX calls before the execution of a new one) before so I really don't understand how to do that and would appreciate some direction.
I have a page in my app where I make a number of AJAX calls to fill dynamically the data in my table (Object Name, Object Fit, Object Progress) when the page loads. For example, there are 5 rows in the table. So I call
$.post("/getFit", {objectId: objectId}, function (result) { manipulation with result }
and
$.post("/getProgress", {objectId: objectId}, function (result) { manipulation with result }
5 times each in the loop -- one for each of the objects.
The first column of my table has links to more detail on the object, and clicking on them I call another AJAX:
$(document).off('click', '.js_object').on('click', '.js_object', function (e) {
var objectId = $(this).attr("id")
$.post("/viewObject", {objectId: objectId}, function (result) {document.getElementById("main_window_content").innerHTML = result; });
})
The problem is that the browser will not render the results of the last AJAX call (/viewObject) until it has received the results of all of the previous calls (/getFit x5 and /getProgress x5).
As a result, a user that wants to drill into the detail on an object needs to wait until the AJAX calls for the other objects are complete before they see anything.
So I struggle with how to stop/abort/cancel (or ignore?) "/getProgress" and "/getFit" so we can fully execute "/viewObject" and view the results of it.
I would very much appreciate your help.
Use xhr.abort() to kill the xhr requests as shown in the below code in JS. I believe there is ajax.abort(); in JQuery
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
If you want execute one ajax after another, and you need all requests to work to show the final result, you can use .done():
$.ajax({
url:'/getFit',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /getProgress
$.ajax({
url:'/getProgress',
data:{objectId:objectId}
})
.done(function(data){
//do something with the results then call /viewObject
$.post("/viewObject"....
})
});
That way you only show /viewObject if the others calls were successfull

Using JSONP and I have 'ReferenceError: data not defined'

I've got a problem with displaying JSON data called via JSONP. I've got a complex JSON file delivered cross domain via a URL and I'm quite the novice at JSON and ajax. I followed a JSONP article here at https://learn.jquery.com/ajax/working-with-jsonp/ and that worked a treat. Now I am trying to iterate through the JSON object and display data in the HTML page after following this question How do I iterate through this JSON object in jQuery? and I'm not going anywhere. The data is not defined and I'm not sure what I am doing wrong:
// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell LibCal what we want and that we want JSON
data: {
q: "select Room name,booked timeslots,booking name from LibCal room bookings",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
I hope it's an obvious fix to a more advanced user our there :)
Thats because your data object doesn't exist. The data key you're referring to is a on the object you're passing to the $.ajax method.
You need to execute your function inside the success callback in order for it make any sense.
$.ajax({
...
// keep all your original stuff
...
success: function( response ) {
var data = response;
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
}
});
I did the request like this. You need to go one level more to access the array to loop.
var json_url = "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41"
$.ajax({
url: json_url,
crossDomain:true,
dataType:"jsonp"
}).done(function(response) {
// at the end of request
//Yours --->response.bookings
//Mine --->response.bookings.timeslots
//access the array to loop
var rooms = response.bookings.timeslots;
$.each(rooms, function(index, element) {
create_elem(element.room_name, index);
});
});
Here is a working version in jsFiddle - https://jsfiddle.net/9e746pkh/
Hope this helps.

Error when storing JSON after an ajax request (jQuery)

I'm quite new to JavaScript/jQuery so please bear with. I have been trying to store the resulting JSON after an ajax request so I can use the login info from it later in my program. I get an error stating that "Data" is undefined. Here is the problematic code:
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(){
var SessionData = Data();
(FunctionThatParsesJSON);
}
})
}
I have checked the URL manually and it works fine (including) being wrapped in the "Data" function. From what I have found online, this may be something to do with ajax been asynchronous. Can anyone suggest a way of storing the JSON so that I can use it later?
Try something like the following;
function LOGIN(){
$.ajax({
url: 'https://.......&JSONP=Data&.........',
success: function Success(data){
functionToProcessData(data)
})
}
When making your ajax call, you can handle the response given by assigning a parameter to the function. In the case above, I have passed the 'data' parameter to the success function allowing me to then use it in further functions (as demonstrated by 'functionToProcessData(data)'.
The response from ajax call is captured in success handler, in this case 'data'.
Check below code:
success: function(data){
var SessionData = data.VariableName;
// Here goes the remaining code.
}
})
Since people ask about explanation, thus putting few words:
When we do $.ajax, javascript does the async ajax call to the URL to fetch the data from server. We can provide callback function to the "success" property of the $.ajax. When your ajax request completed successfully, it will invoke registered success callback function. The first parameter to this function will be data came from server as response to your request.
success: function ( data ) {
console.log( data );
},
Hope this helps.
Internally everything uses promises. You can explore more on promises:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Apparently you are using JSONP, so your code should look like this:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp",
success: function (data){
(no need to parse data);
}
});
Another option:
$.ajax({
url: 'https://.......&JSONP=Data&.........',
dataType:"jsonp"
})
.done(function (data){
(no need to parse data);
});
See the documentation and examples for more details.
success: function (data, textStatus, jqXHR){
these are the arguments which get passed to the success function. data would be the json returned.

Restrictions of Multiple AJAX Calls?

Context:
I have a javascript file, within i have an AJAX function calling a php file returning the data and performing a function with it(an sql query returning records for a set date, then plotting it on a map using the google maps API). Lets call this Data A
Question:
What i need is to be able to get the next days data and storing it in an array (Lets call it Data B) and comparing it with the first set of data(Data A).
From my understanding i need another ajax call within this one, iv tried it but it seems i cannot get the data, i may have a misunderstanding of the core workings of ajax. For example:
var data_a;
var data_b;
$.ajax({
type: "POST",
url: scriptday,
data: $("#dayForm").serialize(),
error: function( data ) {
console.log("Error: "+ data );
},
success: function( json ) {
data_a = json
//start of inner ajax call
$.ajax({
type: "POST",
url: scriptday2,
data: $("#dayForm").serialize(),
error: function( data ) {
console.log("Error: "+ data );
},
success: function( json ) {
data_b = json
// access data_a here
}
}
});
//end of inner ajax call
}
});
EDIT:
Correct way of doing this was to store inner ajax call in a function that takes data_a inside.
function innerAjax(data_a){
$.ajax({
.....
//data_a can now be used here
})
}
and to call it inside the first ajax as
innerAjax(data_a);
this way using AJAX in a synchronous way :)
thanks to those who contributed!
No, restrictions of multiple AJAX calls do not exist, if you use async ajax (and looks like you do).
For you problem - perhaps you need to wait correctly for result of both ajax calls, to store the results and then process them.

Accessing values of a JSON-encoded object

I am sending a JSON encoded array from my controller to my view page. I am doing this on my view page to get the data:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data[0].message);
});
}
The data is like this
{"message":"hello!"}
I am alerting the value of message but my alert giving me undefined. My question is how can I access values of JSON array?
I am new to JSON so I don't know much about JSON.
Try changing your function to:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data.message);
}, 'json');
}
This is because jQuery probably doesn't know that the response data is JSON, so it's assuming that it's plaintext. You can explicitly specify it in $.get as the last parameter as in the revised code, or configure your server to send the response with the HTTP Content-Type header of application/json.
I'm assuming this because message is not a property of a String and that's why you're getting undefined.
Alternatively, you may use $.getJSON:
function () {
$.getJSON('http://localhost/Location/loc', function(data){
alert(data.message);
});
}
Also note that I have changed the alert to data.message. See Knaģis' answer for explanation.
You data contains a single object, not an array.
In your case use alert(data.message); instead.
An array is defined using [] brackets, for example [{message:"hello"}, {message:"world"}] is an array with two objects in it.
OK, if this does not work:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data.message);
});
}
try this:
function () {
$.get('http://localhost/Location/loc', function(data){
alert(data.message);
}, 'json');
}

Categories