Will multiple AJAX requests execute in the order they were created? - javascript

In short the question is:
jQuery.ajax({
url: some_url,
success: function(){
alert('success1');
},
error: function(){
alert('error1');
}
});
jQuery.ajax({
url: some_url,
success: function(){
alert('success2');
},
error: function(){
alert('error2');
}
});
jQuery.ajax({
url: some_url,
success: function(){
alert('success3');
},
error: function(){
alert('error3');
}
});
Will these always result in:
alert('success1');
alert('success2');
alert('success3');
Or can the output be like:
alert('success2');
alert('success3');
alert('success1');
Shouldn't I run abort() on previous AJAX requests if I want the last one's output to be displayed to the user only? I mean I don't mind them seeing success1 and success2 messages as long as success3 will be always the last one.

Try to read about JavaScript Promises/A+ (i.e. here http://www.html5rocks.com/en/tutorials/es6/promises/)
This could be helpful.
It allows to do smth. like
doSmthAsync().then(doSmthAsyncElse()).then(...) and so on
Also, jQuery deffered could help you. http://api.jquery.com/jquery.deferred/

Related

is that possible to make ajax call to external web page?

is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}

Reload variables every 10 seconds

Okay here's the problem.
I want to have 6 realtime variables in php (now they are like Divs). The method I use works fine but it's awful (I know). I need better solution.
Now I load 6 diffrent files like this:
<script>
function loadText() {
$.ajax({
url: ("variable1.php"),
cache: false,
success: function(data) {
$("#variable1").html(data);
}
});
} setInterval(loadText, 60000);
</script>
<div id="variable1"></div>
What should I do? Thanks.
Are you going to want to do a setInterval()?
setInterval(function(){loadText();}, 10000);
Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:
function loadText(){
var text = $.ajax({
type: "POST",
url: "variable1.php",
async: false
}).success(function(){
setTimeout(function(){loadText();}, 10000);
}).responseText;
$('#variable1').html(text);
}
Or use .ajax().complete() if you want it to run regardless of result:
function loadText(){
var text = $.ajax({
type: "POST",
url: "variable1.php",
async: false
}).complete(function(){
setTimeout(function(){loadText();}, 10000);
}).responseText;
$('#variable1').html(text);
}
Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.
http://jsfiddle.net/YXMPn/
You can always have a function you set to run however often you want that has this... It's a much shorter way... If this is what you mean...
$("#variable1").load("variable1.php");

Unable to apply jquery

i have a page searchKB.jsp and it has some code like this :
$.ajax({
type: "GET",
data: {app:app,env:env,ptitle:ptitle,kbaseId:kbaseId},
url : 'jsp/knowledgeBase/kbResults.jsp',
success: function(res){
getResponse(res);
},
error: function(){
document.getElementById("message").style.display="";
$('#message').html("<b><font color=red face=Arial size=2>An Error encountered while processing your Request.Please try again after sometime.</font></b>");
}
});
function getResponse(response){
document.getElementById("message").style.display="none";
document.getElementById("KBInfo").innerHTML = response;
}
searchKB.jspis calling kbResults.jsp through the above code and now i want to apply jquery on elements of kbResults.jsp ..how will i do this ?
i tried everything but it is failing
<input type="button" id="expand3" value="Hide"/> <div id="result3">hide this</div>
and corresponding jquery code
$("#expand3").click(function(){
$("#result3").hide();
});
Try using something like this.
$(document.body).on("click", "#expand3", function(){
$("#result3").hide();
});
Assuming that elements with IDs expand3 and result3 are coming from that AJAX call, you can do something like this:
$.ajax({
type: "GET",
data: {app:app,env:env,ptitle:ptitle,kbaseId:kbaseId},
url : 'jsp/knowledgeBase/kbResults.jsp',
success: function(res){
getResponse(res);
} // removed the error callback for clarity
});
function getResponse(response){
$("#message").hide();
$("#KBInfo").html(response);
// only then attach the listener
// because #expand3 needs to be in the DOM
$("#expand3").click(function(){
$("#result3").hide();
});
}
Or, you can use #ashokd's solution with delegated listener.

"this.source is not a function" error while implementing autocomplete

$(document).ready(function(){
var var_name=null;
$('#id1').click(function(){
$.ajax({
type:"GET",
url:" ggs.erm.servlet.setup5.Page",
success:function(response){
var_name=response;
console.log(response);
}
})
});
$("#id").autocomplete({source:var_name});
});
This is the Code I am messing with,It says TypeError:this.source is not a function. Where I am wrong,Correct me???
jQuery Ajax methods are non-blocking, so it looks like you're trying to set an auto-complete source before the previous method resolves. You probably want to move the autocomplete assignment into the success method of your .ajax() call.
So, instead of what you have, use:
$.ajax({
type: "GET",
url: "ggs.erm.servlet.setup5.Page",
success: function(response) {
$("#id").autocomplete({ source: response });
}
});

$.ajax URL inquiry

Will toDistance.php ran after calling this function? It seems like toDistance.php is not called. Thanks
function myAjax(volunteerDist, jid){
$.ajax({
type:'POST',
url: 'toDistance.php',
data : ({
distance:volunteerDist,
id:jid
}),
success: function(){
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});
Did you tried out by taking arguments on your success function? Try this code.
function myAjax(volunteerDist, jid){
$.ajax({
type:'POST',
url: 'toDistance.php',
success: function( data ){
///CHECK UR UPCOMING DATA
alert(data.jid);
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});
Will toDistance.php ran after calling this function?
If the data parameter is what the server expecting to get, Yes.
Use firebug, check what is going on with your request and stop guessing...
It seems OK. Try to track web traffic with FIddler and check if the script is called and the arguments.
If you're debbuging with Safari, Chrome or Firefox you can record the traffic.
Check for POST variables, script location etc.

Categories