Extract object from JS script loaded with synchronous jQuery ajax call - javascript

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'
}
});

Related

How to call a Javascript function inside a Jade/Pug file

I have a node.js project with frontend written in Pug. On the pug side I have written a Javascript function that is making an Ajax call and returning a string, I am trying to call this function inside that same pug file but it gives me a function not defined error. Can anyone please help with this?
header(class="global-header")
p Current Status: #{getCurrentAvail()}
script.
function getCurrentAvail(){
$.ajax({
url: "/admin/account/accountAvailability",
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
success: function(data){
console.log("===1")
currentAvail = data.message
console.log(currentAvail)
return data.message
},
error: function(data){
console.log("Error function avail");
}
});
}```
It appears you have some piece of external data and you want that data to show in a rendered web page. You have two basic choices here:
1. Server-side fetching and rendering of the data. You can have your server get the data before rendering the page and pass that data to your template engine so your template engine can insert the data into the page at the appropriate place.
2. Client-side fetching and insertion of the data. You can call the getCurrentAvail() function from within a <script> tag in the web page. This will send the rendered web page to the browser. As it loads, the browser will then execute your script, fetch the data from your server and then you would use DOM APIs in the browser to insert the result of that ajax call into the web page to make it visible to the user in the page.
Also, please note that your function getCurrentAvail() has no return value at all. You aren't returning anything from the outer function. Your return data.message is inside the asynchronous success callback so that just go back to nowhere. If you're going to go with the client-side option #2, then you can just put the DOM manipulation code right into the success callback function.
Your current code is attempting to do 1/2 server and 1/2 client and that is not something that will work.
At all times, have total clarity on what is in the server and what is in the client. Ajax methods run in the browser. A #{variable} construct exists only in Pug, and the substitution occurs on the server.
I think this is what you need:
header(class="global-header")
p Current Status:
span#status
script.
function getCurrentAvail(){
$.ajax({
url: "/admin/account/accountAvailability",
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
success: function(data) {
document.getElementById("status").innerText = data.message
},
error: function(data){
console.log("Error function avail");
}
});
}
getCurrentAvail();

Display Flask JSON datas with Jquery

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.

Ajax response and Jquery parse.JSON error

I'm consuming a Rest API. Post call for a login. Got a 200 and a lot of things said API returns. I want to console.log that data (just to confirm things, and see what info I will want to preserve). So I tried:
$.ajax({
url: 'http://www.mensagemassinada.com.br/QSWebAPI/API/Login',
type: 'POST',
data: JSON.stringify(tudo),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
complete: function(data) {
var cap = data.responseJSON
console.log(cap);
console.log(data);
},
});
event.preventDefault();
})
I can get the info I want (in data.responseJSON). In the plain "data" console.log I get all other info from the server. I want to acess individual itens inside said responseJSON (in the log I can see that responseJSON is a array). How can I acess individual values inside this array? I believe I would use parseJson, but got a error, regarding JSON structure. This is the array content printscreen (with private data edited):
From what I could find the Json format should be different. But I just want to confirm if the error is my fault, or if I need to ask for some modifications from the back end guy.
thanks in advance.
You can access the data by targeting the array with the id 0
console.log(cap[0].Empr_Nome);

Jquery ajax success response is string not javascript object

I'm making a jQuery AJAX call to my Rails app (all run on localhost) which is responding with Javascript. The javascript is running because I'm getting the alert. But, I would like to read the my_var variable in the js.erb file. However, when I try to look at the data parameter of the success function it sees the data as a string. So doing data.my_var is undefined.
js.erb file
var my_var = "hi";
alert('this ran');
javascript
$.ajax({
url: "/a/validate?a_id=" + "<%= params[:id] %>",
context: this,
dataType: "script",
data:
{
json_a: JSON.stringify(this.a),
model_to_validate: model,
target_class: target_class,
current_class: current_class
},
success: function (data, textStatus, jqXHR) {
if(!this.orderFormViewed) {
this.orderFormViewed = data.order_block_opened;
}
},
error: function (data) {
console.log("error in ajax validate call");
debugger;
}
})
That's because that's exactly what you told it to do with dataType: "script" - look at the dataType options below. The script is run in it's own context and so you won't see that variable (I believe). You're going to need to communicate differently if you want that set. Or if you just need data send json.
https://api.jquery.com/jQuery.ajax/
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
try to change your dataType to json if you only need to get an object and be sure your server return a json.

How to download a text file and store as a string in jQuery

I have a set of text files representing a table of data from a third party that I'd like to download using a JavaScript application. They look something like this:
col1 col2 .. coln
vala valb .. valz
valA valB .. valZ
etc..
I've been trying to use jQuery to do this. I've been able to use $.load, but I don't want to store the data in the DOM, instead I'd like to parse it out into an object. Whenever I try to use an of the ajaxy methods I'm getting an error I don't understand. For example:
var myData;
$.ajax({
type: 'GET',
url: $(this).attr('source'),
dataType: 'html',
success: function(data) {
myData = data;
}
});
alert(myData);
Gives me an undefined value for myData. Any suggestions would be appreciated.
For that code to work the event needs to be syncrounus, in other word, set async: false in the $.ajax-call. The problem comes because ajax is normally async, meaning that when you do the alert, the request might, or might not have finished. Normally though, it won't cause it takes longer time to fetch a page than to do a function-call. So, by setting async: false, you tell jquery (and the ajax-handler) to wait till the page is finished loaded before you try to alert the data. Another method to achieve the same effect is to do something like this:
var myData;
function fin(data) {
myData = data;
alert(myData);
}
$.ajax({
type: 'GET',
url: $(this).attr('source'),
dataType: 'html',
success: fin
});
This approach is probably better than to set async to false, because it won't make the browser hang while waiting for the page your loading. However, asynchronous programming is not something that is easy to learn, therefore many will find it easier to use async: false.

Categories