I'm having trouble getting my information into an array in an ajax call, if I alert the information right after I insert it into the array it works fine, but if I do it at the end it alerts unidentified. I made sure that books is declared outside so it doesn't interfere.
var books = [];
$.ajax({
url: 'getFolderContents.php',
dataType: 'json',
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
},
error: function()
{
alert("error");
}
});
alert(books[0]);
Your
alert(books[0]);
will be executed while the Ajax call is running and therefore will not have any elements at this point of execution yet. Ajax is asynchronous - while you are doing a request to your PHP script your script continues execution.
Put all actions with books in your success function.
Another hint: As of jQuery version 1.8 you cannot longer use the parameter async: false to create a synchronous "A"jax call. You have to use the callback functions. Have a look at the docs for $.ajax
Your array hasn't lost any data; the data hasn't been put in there yet. The 'A' stands for "asynchronous", meaning your success callback hasn't run yet at the time you call the alert.
Put the alert inside your callback instead:
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
alert(books[0]);
},
Your alert is executing before the success function is called. Perhaps seeing the same code using a promise will make things clearer.
$.ajax( url: 'getFolderContents.php', dataType: "json" )
//the then function's first argument is the success handler
.then(function( data ) {
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
alert(books[0]
});
});
I always feel this syntax makes async stuff make more sense. Otherwise this code functions exactly like Blazemonger's correct answer.
Your AJAX call is asynchronous, that's why it is undefined.
The alert at the end happens before the ajax success callback, because ajax is asynchronous.
Related
I have following code, where for each Image it makes ajax call. but my problem is like when it make ajax call for first image,at that time without waiting for respose it invokes for the second.so it hasn't get effect of first call,means I missed the first call effect. similary without waiting for second it is inovking for third,...
so how to wait in above each function until response come?
jQuery('.xxx img[src*="mainimage"]').each(function () {
vobj = $(this);
var inmainurl = 'https://xxx.kki/api/oembed.json?url=' + $(this).attr('src');
$.ajax({
url: inmainurl,
dataType: 'json',
success: function (result) {
$(vobj).attr('src',result.thumbnail_url);
}
});
});
You should use a recursive function for these purposes. Basic example (jsFiddle):
var myMethod = function(index){
var total_images = $('img').length;
if( index == total_images ) return; // job finished
var current_image = index || 0;
$.ajax({
/*...*/
success: function(/*...*/){
/*...*/
myMethod(current_image + 1);
}
});
};
myMethod();
You could make it synchronous by adding async: false to the ajax parameters. Then you can call them one after the other.
Or, if you want a bit more flexibility, put the ajax call into a function, passing in the image to load. Then in the "success" method of the ajax call, call the function again, passing in the next image name. You'll need some sort of list of image names so that the recursive calls can work out the next image to pass in, in each case.
After every ajax success callback, set some data-* attribute to loaded element and call the same function again.
Try this:
function loadOnlyOneImage() {
var vobj = $('.xxx img[src*="mainimage"][data-loaded!="true"]:first');
if (vobj.length) {
var inmainurl = 'https://xxx.kki/api/oembed.json?url=' + vobj.attr('src');
$.ajax({
url: inmainurl,
dataType: 'json',
success: function(result) {
vobj.attr('src', result.thumbnail_url);
vobj.attr('data-loaded', true);
loadOnlyOneImage();
}
});
}
}
loadOnlyOneImage();
I tried to use this loop to read some urls to read their modified time:
var arr = [];
//... fill arr with push
for (var e in arr) {
nodename=arr[e].hostname;
node_json="/nodes/"+nodename;
html +='data';
xhr = $.ajax({
url: node_json,
success: (function(nn) {
$('#host_'+nn).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
})(nodename)
});
This already works a bit i I comment out the success line: I get calls to all node-files, and in Firebug, I can see the different modified times in the header of the calls.
At first I had a closure, (see How to generate event handlers with loop in Javascript?) And I only got the last line modified with all results. that's why I try to put the action in a separate function.
But that gives:
ReferenceError: xhr is not defined
$('#host_'+nn).append("last modified: " + xhr.getResponseHeader("Last-Modified")...
How do I get xhr into that function?
I aslo tried:
...
xhr[e] = $.ajax({
url: node_json,
success: add_result_to_info(nodename, e)
});
}
}
// outside loop
function add_result_to_info(nn, e) {
$('#host_'+nn).append("last modified: " + xhr[e].getResponseHeader("Last-Modified"));
}
source of the AJAX call: Get the modified timestamp of a file with javascript
If arr is truly an array, just use .forEach or even better .map (with a shim on older browsers) to encapsulate each iteration's scope without the need for additional closures:
var xhrs = arr.map(function(e) {
var nodename = e.hostname;
var node_json = "/nodes/" + nodename;
html +='data';
return $.ajax({
url: node_json
}).done(function(data, status, xhr) {
$('#host_'+nodename).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
});
});
The reason to use var xhrs = arr.map() instead of .forEach is that you then (for free) get the ability to call yet another callback once every AJAX request has completed:
$.when.apply($, xhrs).then(function() {
// woot! They all finished
...
});
your are directly executing the method and passing its result as the callback for the success callback.
the xhr is already passed as the 3rd argument so try
success: function(nn,status, xhr) {
$('#host_'+nn).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
}
if you have to pass the nodename as well, the you need to use a function that returns a function
success: (function(nn){
return function(data ,status, xhr) {
// you can use nodename here...
$('#host_'+nn).append("last modified: " + xhr.getResponseHeader("Last-Modified"));
};
})(nodename)
I have created a for loop that loops the number of times that an element appears in a container. The for loop grabs some data from the HTML and creates a JSON url which will then return a value. That value should then be added to the HTML in the appropriate place.
The problem seems that the for loop completes before all of the Ajax calls are made, so only the last value is being added to the HTML. I thought that I could make sure that the readystate is equal to 4, but that solution did not work. I also tried using complete, rather than success as an Ajax Event. Any insights? Here is my the code.
for(var index = 0; index < $('#wizSteps #step6 label').length; index++){
var priceCount;
console.log(index);
var currentSelect = $('#wizSteps #step6 label[data-pricepos="'+index+'"]');
url = 'http://www.thesite.com/api/search.json?taxonomy=cat3435' + currentSelect.find('input').attr('name');
jQuery.ajax({
url: url,
dataType: "JSON",
success: function( data ){
var totalResult = data.totalNumberOfResults;
console.log(currentSelect);
currentSelect.find('.itemCount').text(totalResult);
}
});
}
It looks like you don't necessarily need the requests to finish in order, you just need to keep track of currentSelect in a way that works. For that, you can use the context ajax option:
for (var index = 0; index < $('#wizSteps #step6 label').length; index++) {
var currentSelect = $('#wizSteps #step6 label[data-pricepos="' + index + '"]');
url = 'http://www.thesite.com/api/search.json?taxonomy=cat3435' + currentSelect.find('input').attr('name');
jQuery.ajax({
url: url,
dataType: "JSON",
context: currentSelect,
success: function (data) {
var totalResult = data.totalNumberOfResults;
this.find('.itemCount').text(totalResult);
}
});
}
That is ok, the calls are not supposed to be done this way. They are only initiated in the loop.
Ajax is asynchronous. The queries are completed later, may be in different order.
If you want to be sure that every call is completed before you do the next one,
you must integrate the next call into the callback function of the previous.
In your case the variable may be overwritten in the call back function.
You can learn more on this here:
Asynchronous Javascript Variable Overwrite
Another interesting question/discussion related to the topic:
What are the differences between Deferred, Promise and Future in JavaScript?
It does not directly answer your question, but helps to understand the problem deeper.
The point is that you probable don't need the loop at all (or you do but in a completely different form).
You should try creating a recursive function, that you will call again in the success of the ajax call, this way you will be sure that the next ajax call will be called only once the previous call is done.
If you want the requests in a sequence, you can work with a queue.
First build the queue:
var queue = [],
index,
stepLength = $('#wizSteps #step6 label').length;
for(index = 0; index < length; index++){
var priceCount;
console.log(index);
var currentSelect = $('#wizSteps #step6 label[data-pricepos="'+index+'"]');
url = 'http://www.thesite.com/api/search.json?taxonomy=cat3435' + currentSelect.find('input').attr('name');
queue.push([url, currentSelect]);
}
And after that do the serial ajax requests:
function serialAjax() {
if(queue.length === 0) {
return;
}
var queueData = queue.shift(),
url = queueData[0],
currentSelect = queueData[1];
jQuery.ajax({
url: url,
dataType: "JSON",
success: function( data ){
var totalResult = data.totalNumberOfResults;
console.log(currentSelect);
currentSelect.find('.itemCount').text(totalResult);
serialAjax();
}
});
};
// call the function
serialAjax();
I'm trying to iterate through elements of .ball class and check if their associated url exists:
$(".ball").each(function(i){
var url;
var c_day = $(this).data('day');
var c_mon = $(this).data('mon');
var c_year = $(this).data('year');
url = c_year + "/" + c_mon + "/" + c_day + ".html";
$.ajax({
url: url,
error: function()
{
alert('file: ' + url + ' does not exist');
},
success: function()
{
alert('file: ' + url + 'EXXXXXXISTS!!!!!');
blogA[ blog_count ] = url;
blog_count++;
$(this).css("color", "red" );
}
});
});
I've done some research and read that using .ajax in .each causes a lot of problems but I couldn't wrap my head around on how to fix it.
The problem is that I get really weird results (has to do with asynchronous?). If I alert url outside of ajax, it correctly iterates through the elements. If I alert url in ajax, it spits out urls that belong to the last element of the class.
Something like this, in order to simplify your code
function successHandler(url, ball) {
return function(ret) {
alert('file: ' + url + 'EXXXXXXISTS!!!!!');
ball.css('color','red')
}
}
var balls = $('.ball'), requests = []
balls.each(function(index, ball) {
var url = ...
requests.push($.ajax({ url : url , success : successHandler(url, ball) })
})
$.when.apply($, requests).done(function() {
alert('all balls are checked')
})
Or with ES6:
const success = (url,ball)=>(ret)=>ball.css('color','red')
const balls = $('.balls')
, reqs = balls.map( (b, i) => {
const url = ...
return $.ajax({url, success:success(url,ball)})
})
$.when.apply($, reqs).done( (resps) => alert('all done'))
A Little explanation: You are blindly using this in your callback, not knowing in which context it is going to be executed. In order to work around it and has your URL into callback we are creating function that returns a function, so it will have URL of current .ball DOM object in the context.
You'll probably also need to execute code after all ajax requests are done, so using $.when is the simplest way of doing it. And we are storing all promises just for this reason.
If you aren't concerned about the order of execution of each ajax call and just want to know when they are all done and the array is fully populated, then you can get this to work by fixing your reference to this and by adding a callback function that is called when all items are done:
// this function called when the ajax calls for all balls have finished
// at this point, blogA and blog_count will be populated
function ballsDone() {
// put your code here
}
var balls = $(".ball");
var cnt = balls.length;
balls.each(function(i){
var url;
var self = $(this);
var c_day = self.data('day');
var c_mon = self.data('mon');
var c_year = self.data('year');
url = c_year + "/" + c_mon + "/" + c_day + ".html";
$.ajax({
url: url,
error: function()
{
alert('file: ' + url + ' does not exist');
if (--cnt <= 0) {
ballsDone();
}
},
success: function()
{
blogA[ blog_count ] = url;
blog_count++;
self.css("color", "red" );
if (--cnt <= 0) {
ballsDone();
}
}
});
});
Keep in mind that the ajax calls are asynchronous so the ONLY place you can use the results from the ajax call is in the success handler. You can't use the results of the ajax calls right after the .each() call in a synchronous fashion because the ajax calls have not yet finished. You must wait for the success handler to be called and when cnt success handlers have been called, then they are all done and you can then process the results.
I'm possibly missing something that is very obvious, but I'm not getting nowhere with this problem.
I'm simple trying to set a value of a variable after getting the value from a json feed.
I'm using jquery to get a jsonp feed and then store the value in a variable that I can use later, but its not working and the value doesn't get stored. If I console.log the value it returns it.
jQuery(document).ready(function($){
serverip = "<?php echo $_SERVER['SERVER_ADDR']; ?>";
stream_domain = "";
$.ajax({url: 'http://load.cache.is/inspired.php?ip=' + serverip, dataType:'jsonp',
success: function(data){
$.each(data, function(key, val) {
if (key == serverip){
stream_domain = val;
console.log("val: " + val);
}
});
}
});
console.log(stream_domain);
});
Here is the same code on jsfiddle.net
You are making an asynchronous request. So your code which appends the HTML execute before the success does which assigns the variable.
The code following the ajax request executes immidiatly after the request is made.
So if you require the response data then you should move your append code to be executed from the success method similar to this:
if (key == serverip){
stream_domain = val;
console.log("val: " + val);
$("<span>" + val + "</span>").appendTo(".json");
$("<span>" + stream_domain + "</span>").appendTo(".variable");
}
DEMO
The ajax call is asynchronous, so the timeline of the events is :
make ajax call
console.log
ajax call success, variable assign
Wait for the success event before using the variable. Here is your updated jsFiddle where I've added a function called in the success callback function:
function continueWorking(){
console.log(stream_domain);
$("<span>" + stream_domain + "</span>").appendTo(".variable");
}