Display Flask JSON datas with Jquery - javascript

I'm trying to display json data coming from my flask function.
I can use getJson method to get those datas but getJSon work with action like click or change.
getJSon return data but i can't use use them out of the function.
For example
$.getJSON('../admin/graphe_1', {
}, function(data) {
chart.data = data
console.log(data)
});
console.log(chart.data)
The first console log display data but the second one display nothing.
How can I do to get this data out of the function ?

Reason is getJSON function is asynchronous. So your second console.log prints the data before actually loaded into your app. So it prints null probably. The first console.log is in the function which executed right after completing loading data successfully. So it should print correct data. If you want to do stuff after loading data successfully do it in the done function which contains your first console.log. if you want synchronous execution use,
$.ajax({
dataType: "json",
url: url,
async: false,
data: data,
success: function (data){
chart.data=data;
}
});
console.log(chart.data); // data should be loaded
This is not recommend since it blocks UI thread.

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

Extract object from JS script loaded with synchronous jQuery ajax call

I am trying to get use an object from a script loaded synchronously using Ajax via jQuery.
From this script I am trying to load an object which looks like this from a script called map_dropdowns.js which returns the object options:
{curr_cat: "RELATIONSHIP"
curr_subcat: " Population in households"
curr_total: "Total"}
My code for the script with the ajax is here:
<script>
$.ajax({
type: "GET",
url: "../scripts/map_dropdowns.js",
dataType: "script",
async: false,
success: function(data){
console.log(data);
}
});
console.log(options); //returns `Object{}` in the console, and only shows values when expanded
options["curr_cat"]; //returns undefined
console.log(Object.keys(options)); //returns an empty array []
</script>
In the original script, the keys and values within options can be accessed perfectly fine. console.log in Chrome shows its contents fully without needing to be expanded (Object {curr_cat: "RELATIONSHIP", curr_subcat: " Population in households", curr_total: "Total"}), and Object.keys() works just fine.
After it is loaded onto the page with the Ajax function, however, trying to access the values using the keys comes up undefined, Object.keys turns up an empty array [], and the key:value pairs are only shown in the console when I click on the object, with it otherwise showing only Object {}.
I am pretty sure that I need to do something in the success function of the Ajax, but I am not sure what after a lot of trial and error.
Thanks!
Loading JS code via AJAX is always a little hit and miss. It's usually a much better idea to load the data either as HTML, XML or JSON, and then deal with it as required once the AJAX request completes.
In your case, as you're attempting to load an object, JSON would be the most appropriate. If you change your map_dropdowns.js file to return data in this format:
'{"curr_cat":"RELATIONSHIP","curr_subcat":"Population in households","curr_total":"Total"}'
You can then make your async request to get this information from this file:
$.ajax({
type: "GET",
url: "../scripts/map_dropdowns.js",
dataType: "json",
success: function(data){
console.log(data.curr_cat); // = 'RELATIONSHIP'
console.log(data.curr_subcat); // = 'Population in households'
console.log(data.curr_total); // = 'Total'
}
});

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.

how to access input data submitted to ajax request (NOT return data) via jQuery

I'm trying to retrieve the data I submitted to an asynchronous ajax request should the back-end fail in some way. The data in 'myJSONData' is actually pulled off a queue (array) in memory and I need to put it back into the queue if any kind of error occurs.
e.g.
var myJSONData = {"parm1":"value1","parm2":"value"};
$.ajax({
type: "POST",
url: "/postData.ajax",
dataType: "json",
data: myJSONData,
success: function(jsonReply) {
// I need to refer to the posted data here (i.e. myJSONData)
},
error: function(xhr,ajaxOptions,thrownError) {
// I need to refer to the posted data here (i.e. myJSONData)
}
});
My code fires off a number of calls at various times, the trouble is that if I refer to myJSONData within the success or error blocks it contains the most recent value of that variable in memory, and not what was in the variable at the time of the ajax call.
Is there some other way to access the data associated with the particular instance of ajax call - something like $.ajax.data ?
You should be able to access it in your success and error functions :
success: function(jsonReply) {
var p1 = myJSONData.param1;
}

Iterate on array, calling $.ajax for each element. Return array with all ajax results

I've just started working with JavaScript for non-trivial things, so this is probably straightforward...
What I'm trying to accomplish: iterate on an array of product references, fetch the JSON for each reference, and return an array of all the product information (with a hash-like structure indexed by reference).
What I've tried:
function fetchProductData(references){
var product_data = new Object();
references.forEach(function(ref){
$.ajax({
url: "http://localhost:3000/products/find.js?reference=" + ref,
dataType: "jsonp",
type: "GET",
processData: false,
contentType: "application/json",
success: function(data) {
product_data[ref] = data;
}
});
});
alert('before return: ' + product_data);
return product_data;
};
$(document).ready(function(){
var products = fetchProductData(references);
alert('products : ' + products);
});
Here's what I don't understand: the first time I call alert to display the array contents, the array is empty. However, on the second call, the array is populated with the data I want.
In other words, the "products :" alert displays the data I want in the code above. But if I comment the "before return: " alert, it no longer does. Why is this?
So my question is: how can I have jQuery make several $.ajax call to fetch product information, collect that information in an array, and return that array so I can use it elsewhere in my code?
Also, why is the data in the variable magically accessible after it is referenced in an alert?
The "A" in "AJAX" stands for "asynchronous" :). Your program doesn't wait for the call to complete before going on to the next iteration, meaning you'll probably not get all of your data. Also the alert has the same problem. Operation to concat 'before return:' to the string add just enough time to get some data in the variable. On a faster machine you might find you never get data.
I think you really need to rethink your approach. It's not a good idea to have multiple AJAX requests in a loop. It will greatly increase latency of the page. Pass all your parameters once using JSON, then have your server side script loop through that and return a single response in JSON.
function fetchProductData(references){
// make sure your "references" is a JSON object
$.getJSON('http://server/side/url', {'json':references}, function(product_data) {
// do something with product_data (alert them, put them in an array, etc)
});
}
function fetchProductData(references, cb){
var length = 0;
var product_data = new Object();
references.forEach(function(ref){
length++;
$.ajax({
url: "http://localhost:3000/products/find.js?reference=" + ref,
dataType: "jsonp",
type: "GET",
processData: false,
contentType: "application/json",
success: function(data) {
product_data[ref] = data;
if (++count === length) {
cb(product_data);
}
}
});
});
};
$(document).ready(function(){
var products = fetchProductData(references, function(products) {
alert('products : ' + products);
});
});
Use a callback on your asynchronous operation.
The reason it appears to work with the alert call is because alerting a message gives ajax enough time to populate your array. The return statement is only triggered after you click OK on the alert box giving your code a window of 250ms to populate the array with data.
You are executing you ajax query in async mode. And you want a sync result. Try to add:
async: false
Hope this helps.
your $.ajax call is asynchronous, so what is happening is that the first time you make the call, your javascript makes the call, moves on to the next line (alert) and then loops. You're data hasn't returned at that point yet. What you can do to remedy this is to set the async: false option in your $.ajax call.
This is an asynchronous operation. The only sure way to know when the data is ready is in the callback function: success: function () {...}, which gets called when the data has finally returned. Put your alert in there.

Categories