Multiple AJAX requests in jQuery - javascript

I have a function that pulls data from two locations and places the returned content on a modal dialog that is displayed to the user.
Both requests are asynchronous because they're cross-domain. The problem lies in that I don't want to display the modal until both requests have finished loading. How can I check to make sure both requests have finished before loading the modal?
I have tried placing the openModal functions in the success handler of the second request and that works when the first requests finishes loading before the second request, but sometimes this isn't the case.
Here's a copy of my code:
function loadData(id) {
$.ajax({
type: 'GET',
url: 'https://someurl.com/v1.0/controller1/' + id,
dataType: 'jsonp',
success: function(data) {
// Do some stuff to the data
}
});
$.ajax({
type: 'GET',
url: 'https://someurl.com/v1.0/controller2/' + id,
dataType: 'jsonp',
success: function(data) {
// Do some stuff to the data
openModal();
}
});
}
function openModal() {
// Open the modal
}

Check out the new version of jQuery -- 1.5. It has support for exactly your problem, you can check out this blog post for the solution of your problem: http://www.erichynds.com/jquery/using-deferreds-in-jquery/

You could put the one of the ajax requests inside the success callback of the other request, but that wouldn't be as efficient as having them both request at the same time. Then you'd just have to put the openModal call inside the success callback of the inner ajax request. Not optimal, it would be a quick and easy fix if this solution would work for you until a better option is found.
I'm going to keep thinking on this one...

$.when(
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "moon",
tagmode: "any",
format: "json"
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})).then(function (res1, res2) {
});

Related

Taking data out of the Ajax Jsonp

I want to taking data out of the Ajax Jsonp.
Why doesn't work this app?
Please Help.
var res;
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
}
});
$("div").html(res);
https://jsfiddle.net/q6vfgemp/
The data is retrieved correctly but since the request is async you cannot set the html outside of the success callback, put it inside the success callback and it will work.
Also it's a good practice to console.log the data when you're not sure where the problem is to make sure it is retrieved successfully.
Edit: Here is why the async: false option is not working, check the accepted answer for the details.
In JSONP you should add a callback parameter to the request.
The response would be a script calling your callback with the requested data.
So, you should call a URL like this:
http://domain.ext/?callback=xxx
And you should have a function with name "xxx":
function xxx(data) {
// Here you can manage the received data
}
Also, the requested resource should support JSONP, if it doesn't you will not receive anything in your callback.
Since the request is asynchronous, your code sets the "div" before the result is actually retrieved. In order to make sure you retrieve the result, and then set the div, do this:
$.ajax({
url: 'https://api-metrica.yandex.com/analytics/v3/data/ga?end-date=today&ids=ga%3A35416355&dimensions=ga:pagePath&metrics=ga:users&filters=ga:pagePath==/p/etkinlikler.html&start-date=2015-10-25&oauth_token=AQAAAAAVs-uLAASpEAf-MmJK_kHgpU9Fwv8WArM',
dataType: 'jsonp',
async: false,
success: function(result) {
res = result.totalsForAllResults["ga:users"];
$("div").html(res);
}
});

How to make an ajax call to a page and wait for the ajax calls on that page to finish

I am doing a simple ajax call.but in the page i'm calling there's an ajax call to a pdf file. Is there a way to make the page wait until all the ajax calls on the requested page are loaded? I am getting as well the following error :"Can't create DocumentThreadableLoader"
$.ajax({
type: "POST",
dataType: "text",
url: '/test/test.pdf',
success: function (data) {
$('body').html(data);
},
data: body
});
Not recommended since ajax is meant for async calls
$.ajax({
type: "POST",
dataType: "text",
async: false, // ADD THIS LINE
url: '/test/test.pdf',
success: function (data) {
$('body').html(data);
},
data: body
});
Best Solution
Use callback structure and or jQuery built in promises (success, done, always, complete, etc).
load pdf data into html body
$( "body" ).load( "test/test.pdf" );

Link to anchor not yet loaded (ajax)

I'm loading comments with ajax in my website, and I'm sending to users notification with an anchor to the specific comment.
The anchor is not working, that piece of DOM isn't loaded yet.
How can I handle this? Maybe something "on ajax complete" ? I can do a script that launch "on ajax complete", but I don't know how to manage the anchor in the url.
$.ajax has a complete() callback that you can put code into. you can run location.hash = yourAnchorHash.
You could use jQuery's complete or success callback depending on whether you only want your code to fire when the call is successful or always when the call is complete.
$.ajax({
type: "POST",
url: "yourURL",
contentType: "application/json; charset=utf-8",
data: yourData,
async: true,
success: function (msg) {
//get stuff done when ajax call is successful
},
complete: function()
{
//get stuff done when ajax call is complete
}
});

Add cache to ajax json request

I have a basic ajax call to parse a json file. I need to make sure I am not hitting the feed every time someone visits the page. How would I go about adding some sort of cache so the feed only get's requested say every say 2 hours?
$(function () {
$.ajax({
type: "GET",
dataType: "json",
url: "my.json",
success: function (data) {
// do something with the data
}
});
May be you can use cookie store your time and check every time to know 2 hours time gap then you can call your function get the latest feed.
By default, is should get cached. You can set the option explicitly as shown below.
$(function () {
$.ajax({
type: "GET",
cache: true,
dataType: "json",
url: "my.json",
success: function (data) {
// do something with the data
}
});
You can also use the below statement for all ajax calls on the page.
$.ajaxSetup({cache: true});

Jquery Ajax Problem

Hi all;
var v_name = null;
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
$.data(document.body, 'v_name', mydata);
}
});
v_name = $.data(document.body, 'OutputGrid');
alert(v_name);
first alert undefined before alert work why ?
In addition to the other answers, also keep in mind that by default .ajax GET requests are cached, so depending on your browser, it may look like all of your requests are returning the same response. Workarounds include (but are not limited to): using POST instead of GET, adding a random querystring to your url for each request, or adding 'cache: false' to either your ajax call or to the global ajaxSetup.
To make it work, you have to place the alert() in the success function:
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});
AJAX calls are asynchronous, and therefore JavaScript would evaluate alert(v_name); before the server responds to the AJAX call, and therefore before the success function is called.
Your AJAX applications must be designed in such a way to be driven by the AJAX response. Therefore anything you plan to do with mydata should be invoked from the success function. As a rule of the thumb, imagine that the server will take very long (such as 1 minute) to respond to the AJAX request. Your program logic should work around this concept of asynchrony.
$.ajax({
type: "GET",
url: "Testpage.aspx",
data: "name=test",
dataType: "html",
success: function(mydata) {
alert(mydata);
}
});

Categories

Resources