I want to read the contents of a local file using JavaScript/jQuery. I understand this is often discussed, but my example is a little different because I want to return the contents after the fetch is done rather than manipulate HTML.
I don't want to talk about security issues and local files because this code is meant to run within my own browser (Chrome, which I start with the --allow-file-access-from-files flag).
I have the following function to get the data...
function readData() {
$.ajax({
type: "GET",
url: "data.xml",
async: false, // this does not change the outcome
dataType: "xml",
success: function(xml) {
// Got the data, find entries and return them.
console.log("Returning data");
var doc = $(xml).find('entry');
// This is where most examples manipulate dom, I want to
// return the data instead
return doc;
}
});
}
Now I want to do...
var xmlDoc = readData();
// undefined, why?
and have the document in the variable. Instead I get undefined. It seems that the function returns before the file is fetched. Or maybe I have a problem with variable scope?
Does anyone know how to accomplish this? Yes, I am sure I want to use JavaScript even though I am doing this locally.
The stackoverflow answer regarding handling of $.ajax calls has a good example of a nice way this can be used. This example can be slightly modified to give you something close to what you are looking for.
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'xml',
beforeSend: showLoadingImgFn
})
.always(function() {
// remove loading image maybe
})
.fail(function() {
// handle request failures
});
}
The examples of implantation of the above method is:
xhr_get('/index').done(function(data) {
// do stuff with index data
});
xhr_get('/id').done(function(data) {
// do stuff with id data
});
You might want to something like:
function readData() {
var returnData;
xhr_get('data.xml').done(function(data) {
returnData = data;
});
return returnData;
}
Hope that helps.
Related
I've an array of items in javascript, and for each item, I've to make an ajax post to a URL to get corresponding info and display the info in a container. The code broadly looks like this:
var data = some_data;
array.forEach(item, idx)=> {
callAjaxAndUpdate(data, item, $('div#container'+i);
});
and the Ajax method is simply
var standardUrl = 'https://example.com/post.php';
function callAjaxAndUpdate(data, item, container) {
$.ajax({
url: standardUrl
data: data,
type: 'POST',
}).done(function(res) {
container.append(res.data);
}).fail(function(res) {
container.append(res.responseText);
}).always(function() {
container.append('DONE!');
});
}
However, this thing whole thing seems to have become blocking. I did server-side logging of timestamps, and I could see that ajax request for each item is getting triggered only after that for the previous one has completed (always section executed).
Could someone help me out with why this setup is synchronous, and how to make it async? Please note that this script is executing in the browser, and not on nodeJS.
EDIT: Turns out, it's the PHP backend which is processing the requests in a blocking way. Perhaps the session is the culprit here. I would close the question now. Thanks for your help and suggestions.
Try default Ajax async
var standardUrl = 'https://example.com/post.php';
function callAjaxAndUpdate(data, item, container) {
$.ajax({
url: standardUrl,
async: true,
data: data,
type: 'POST',
}).done(function(res) {
container.append(res.data);
}).fail(function(res) {
container.append(res.responseText);
}).always(function() {
container.append('DONE!');
});
}
Or you can call the method on .done method
I'm trying to store ajax result into variable. When I use console.log it gives my html tag that I wanted, But when I trying set into global variable it said undifined.
How I can store ajax result into global variable
var result;
$.ajax({
url: "person.html",
success: function(data){
//result=data;
console.log(data);
}
});
//console.log(result);
Ajax is asynchronous, meaning that the code to find out what result IS is running at the same time that the console log of result, which is why you're getting undefined, because result hasn't been set by the time the value is being console logged.
The only way I know of to console log the result would be to either do it within the ajax success function or to have the ajax success function call a subsequent function that contains the console log. It's the only way to be sure that a value has been returned before you console log it.
Examples:
EXAMPLE 1:
var result;
$.ajax({
url: "person.html",
success: function(data){
result=data;
console.log(result);
//Note that in this instance using the variable 'result' is redundant, as you could simply console.log data like you're already doing.
}
});
EXAMPLE 2:
var result;
$.ajax({
url: "person.html",
success: function(data){
result=data;
subsequentFunction(result);
}
});
function subsequentFunction(result){
console.log(result)
}
// Note that if you're doing something simple with result that this could be a bit long winded and unnecessary.
It all depends on how much you're wanting to do with the result as to which option would be better.
Note: There is also a property of an ajax call called 'async' that you can set to false which forces it to be synchronous, but this is generally considered a bad idea as it will prevent any other code from running until the result is returned and locking the browser.
$.ajax returns a promise, meaning that your code KNOWS it's going to receive a response, but because it's dependent on an external source, it doesn't know when this response will come in.
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
See above link for more information on the subject.
ajax requests are async so your console.log(result) is running before getting response of your request. you should do something like this
var result;
$.ajax({
url: "person.html",
success: callback(data)
});
function callback (data){
result=data;
console.log(result);
}
You will not see anything beacuse the data is not populated yet. In your specific case you actually need to wait for the response. You can achieve it by using the following snippet.
$(document).ready(function(){
var data = $.parseJSON($.ajax({
url: 'person.html',
dataType: "json",
async: false
}).responseText);
var myProp = data.property; // Here you can access your data items
});
Another approach should be like you can push your data in an array and can access it in another function like this:
var result =[];
$(document).ready(function()
{
$.ajax({
url: 'person.html',
async:true,
dataType: "json",
success: function(data)
{
result.push(data);
}
});
});
NewFunction()
{
console.log(result);
}
How can I take count of element in my database with ajax/json in asp.net? With GET method? So far I've got this:
// GET: /People/
public JsonResult Index()
{
var count = db.People.ToList().Count;
return Json(count);
}
in javascript:
function check_count() {
var how_many=$.ajax(
{
type:'GET',
url:'/People/',
success: function(data){
alert('successful');
}
});
}
What you have looks OK, except for one little thing:
var how_many = $.ajax({
// ...
});
The AJAX call returns a "promise", it lets you chain things together, handle errors etc.
The reason for this is that AJAX calls are async, you start them and they (hopefully) will finish some time in the future. The line with your alert('successful'); is the code that will be run once the call is finished.
Change that code to handle your data, perhaps try the following:
$.ajax({
type: 'GET',
url: '/People/',
success: function(data) {
console.log(data);
// this is like a break point, so you can inspect things
debugger;
}
});
As long as you have debugging enabled in your browser you'll be able to check what data was returned and work out what code you want from there.
$(document).ready(function() {
$.getJSON('https://jira.atlassian.com/rest/api/latest/project?callback=?', function(data) {
console.log("success");
});
});
Why this code is not working? Its not giving error also in browser. But a project file is being downloaded as script in Chrome as shown by Inspect Element tool. How can I get data from the file?
It looks like Atlassian use jsonp-callback instead of callback as the parameter in a query string for JSONP callbacks.
See here.
I would suggest you configure your JSONP-call with the jQuery.ajax API like:
$(function() {
$.ajax({
type: "GET",
url: "https://jira.atlassian.com/rest/api/latest/project",
dataType: "jsonp",
jsonp: "jsonp-callback",
data: { /* additional parameters go here */ }
}).done(function(data) {
console.log("success");
});
});
The option jsonp renames the JSONP-callback parameter as #mccannf suggested from the API.
Also, for future reference, you might consider using the jqXHR object to add error-handling functionality, so you can tell if the JSON request is failing. See jQuery's reference (http://api.jquery.com/jQuery.getJSON/)
$(document).ready(function() {
var jq = $.getJSON('https://jira.atlassian.com/rest/api/latest/project?callback=?',
function(data) {
console.log("success");
})
.error(function() { console.log("error occurred"); });
});
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.