Ajax url call with multiple pages - javascript

I a trying to make an ajax call with the URL http://exampleurl.com/site/api/v1/brand/page/1/size/100. I need the page number to change (page/1 in example) based on the response I get from this ajax call. Here is what I currently have
$.when(
$.get("http://exampleurl.com/site/api/v1/brand/page/1/size/100", function(result) {
brands.total = result.totalElements;
brands.pages = result.totalPages;
brands.page = result.pageNumber;
brands.first = result.firstPage;
brands.last = result.lastPage;
})
).then(function() { ... other data });
I would like to $.get("http://exampleurl.com/site/api/v1/brand/page/"+ i +"/size/100"... but I need the loop to be based off of the brands.pages. I have tried putting another ajax call in this get function, however I am unable to set a variable such as brands.data in the second call and retrieve it in the then function. Any help??

Here's an idea:
function fetch(page) {
var url = "http://exampleurl.com/site/api/v1/brand/page/" + page + "/size/100"
$.get(url, function(result) {
// do something
if (page < result.pages) {
fetch(page + 1)
}
}
}
What we're doing is fetching the data, processing, then checking if we're done, if not, we call the same function recursively.

Related

I can't seem to break out of A $.each() loop

I can't seem to manage to break out of my each loop if the ajax returns an error. I've tried
return false;
and other similar thing but the $.each still continues to run.
I need to be able to do this so that I can display error messages from my back end after posting it via ajax(I know this is bad practice however a client needed to be able to be able to send multiple forms off at once.).
Can anyone explain what I've done wrong?
var postAll = function(button_clicked)
{
e.preventDefault();
var form_response = [];
var formsCollection = document.getElementsByTagName("form");
$.each(formsCollection, function (key, value)
{
console.log(value.action);
console.log(value.id);
var url = value.action;
var id = value.id;
var data = ($('#' + id + '').serialize());
if (id == 'additionalInfo')
{
data = {'Add_info': $('#Add_info').val(),};
}
if (id != 'DONE')
{
$.ajax({
type: "POST",
dataType: 'json',
url: url,
beforeSend: function (xhr)
{
xhr.setRequestHeader('X-CSRF-TOKEN',$("#token").attr('content'));
},
data: data,
success: function (data)
{
console.log('success'); // show response from the php script.
form_response.push(data); // show response from the php script.
},
error: function (data)
{
console.log('fail'); // show response from the php script.
display_errors(data, id); // show response from the php script.
return true;
}
});
}
});
}
AJAX is asynchronous, when executing your $.each function it will execute the AJAX call and "Not wait" for the others to finish
To solve your problem you'll have to write a function that will execute the first ajax call and in the success it will execute itself again with the second ajax call.
Example:
var data = [form1,form2...etc];
function letsLoop(data,index = 0){
$.ajax({
url:....
success: function(){
letsLoop(data,index+1);
},
error: function(){
}
});
}
and here you call your function:
letsLoop(data,0);
If by breaking out of the loop you mean the return in your error handler, then it won't work as you think it would.
Your loop creates asynchronous requests 'at once'. Then each of these requests is handled by the browser (more or less simultaneously), then come responses. So by the time your error handler runs the loop has long finished.
BTW, the return in your case relates to the error handler, not the function inside the loop.
So, to achieve what you want you should 'queue' your AJAX requests and perform them one by one.
One possible solution is to create an array of forms then take (and remove it from the array) the first one, perform a request, on a response repeat the whole thing, and keep repeating until the array is empty.

how to wait check ajax request has completed before other element?

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();

Send Ajax request to many server?

I have problem with my code:
Now I want to send request Ajax to 2 page, is it ok ? if ok, can show me how to do. Thanks.
Example:
function change_select_employee(){
var p="";
p="&month="+document.getElementById('F02S').value;
document.getElementById('select_employee').innerHTML = "";
new Ajax.Request('a.php', { method:'get', onSuccess:onLoad_select ,parameters:p});
}
I want send this ajax to 2 file, a.php, b.php, how do I do it ?
As both comments suggest you can go both ways about this, either run the Ajax.Request twice or use an array to hold your target urls.
function change_select_employee(){
var p = "&month="+document.getElementById('F02S').value;
document.getElementById('select_employee').innerHTML = "";
new Ajax.Request('a.php', { method:'get', onSuccess:onLoad_select ,parameters:p});
new Ajax.Request('b.php', { method:'get', onSuccess:onLoad_select ,parameters:p});
}
or
function change_select_employee(){
destinations = ["a.php","b.php"];
var p = "&month="+document.getElementById('F02S').value;
destinations.forEach(function(dest) {
new Ajax.Request(dest, { method:'get', onSuccess:onLoad_select ,parameters:p});
});
document.getElementById('select_employee').innerHTML = "";
}
You can even define the target url array outside the main function and pass it as an argument to change_select_employee($destinations)
Create a function ( makeAjaxRequestTo(page) ) that sends an AJAX request to a given page, and then simply call it with a few pages, like this:
var pages = [ "/page1/somewhere.php", "/page2/somewhere.php" ];
var page;
for (var i in pages){
page = pages[i];
makeAjaxRequestTo(page); // Your own code goes here to send an AJAX request to page x
}

multiple calls to ajax simultaneously

I'm trying to make multiple calls to Ajax, i have fields like time intervals and no of calls to ajax under that time period. Now the problem is, while making multiple calls to same Ajax, there may be chances of merging of data with the other data that were send to Ajax earlier. I am not sure that it will happen.
Here my Ajax call.
callAjax = function () {
var dataIn = inObj.data || {};
var successFunc = inObj.success || function () {};
var passOn = inObj.passOn || {};
var myParams = {drape:1,type:'GET'};
myParams.url = this.homeComingUrl;
$.extend(myParams,params);
var data = this.fillAction(action,dataIn);
if (myParams.drape) { vidteq.utils.drapeSheer(action); }
var that = this;
var magicCall = $.ajax({
url:myParams.url,
type:myParams.type,
data:data,
success: function (response) {
// TBD we need better error handling
if (myParams.drape) { vidteq.utils.undrapeCurtain(action); }
successFunc(response,passOn);
},
error:function(response) {
if (myParams.drape) { vidteq.utils.undrapeCurtain(action); }
that.gui.io.handleError(response);
}
});
}
saveEvents = function () {
this.commitEditingEvent();
var dataEvents = this.collectEventsToSave();
//$('#calendar').fullCalendar('removeEvents');
var that = this;
if (vidteq.eTrainer==1) {
dataEvents = arguments[0];
}
if (!dataEvents.length) { alert("Nothing to save");return; }
this.callAjax('updateEvents',{
data : { events : JSON.stringify(dataEvents) },
success : function (response,passOn) {
that.handleGetEvent(response,passOn);
}
},{type:'POST'});
}
This may not be required for understanding the problem.
If any body can explain how Ajax handles multiple calls, then it'll really helpful.
First line, your anonymous function isn't saved and isn't ran. Then. In each function, what does this refer to ? What is this context ? Is this window or do you call your function like saveEvents.apply( jQuery ) ?
JavaScript is powerful, when your want to run XMLHttpRequest (Ajax uses it), scripts are called when an event happen, like "server is found", "request is send", "file is reading", "file loaded"... for each state of your request. Ajax by jQuery help you to request asynchronous. You can request as many Ajax request as you would like in the same time. The important is to create a function happen in success case.
In this success function, you receive data, you compute it, then this function may call another Ajax request, and so on. When you chain requests like this to get the same file, we call it Ressource.
Ressource uses Ajax which uses XMLHttpRequest.
you need to do asynic :false in your ajax method
function isLoggedIn() {
var isLoggedIn;
$.ajax({
async: false,
// ...
success: function(jsonData) {
isLoggedIn = jsonData.LoggedIn
}
});
return isLoggedIn
}

Javascript Array loses data

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.

Categories

Resources