I am trying to load multiple .js files through the GetScript method.
I need them to be loaded in series, meaning the first .js files needs to be fully loaded before going to the next one.
Question 1: I was using the code below, but found that this becomes quite messy when the amount of js files increase. Is there a more clear way of loading multiple .js files?
Also, I've found that function( data, textStatus, jqxhr ) is a callback function that is executed when the getScript request succeeds. The parameters (data, textStatus, jqxhr) can be used in the funtion, where: data is the data from the .js file, textStatus is the status of the request and jqxhr is a XMLHttpRequest object.
Question 2: Why is the parameter textStatus used as a callback? Using it in this function will always set it to Success, right?
Question 3: When I only want to execute the next getScript, i could just leave out the parameters and write: jQuery.getScript("url.min.js", function() { Correct?
jQuery.getScript("//url1.com/file1.js", function(data, textStatus, jqxhr) {
jQuery.getScript("//url2.com/file2.js", function(data, textStatus, jqxhr) {
jQuery.getScript("//url3.com/file3.js", function(data, textStatus, jqxhr) {
jQuery.getScript("//url4.com/file4.js", function(data, textStatus, jqxhr) {
});
});
});
});
Thank you.
I was using the code below, but found that this becomes quite messy when the amount of js files increase. Is there a more clear way of loading multiple .js files?
You could DRY it up a little by recursively iterating through an array of URLs, assuming that no further processing is required in the callback. Something like this:
function getScript(arr, i) {
i = i || 0;
jQuery.getScript(arr[i], function() {
i++;
arr.length > i && getScript(arr, i);
});
}
getScript(['//url1.com/file1.js', '//url2.com/file2.js', '//url3.com/file3.js', '//url4.com/file4.js']);
Why is the parameter textStatus used as a callback? Using it in this function will always set it to Success, right?
It follows the same pattern as other jQuery AJAX methods, you're right that in this case it will always be a successful response.
When I only want to execute the next getScript, i could just leave out the parameters and write: jQuery.getScript("url.min.js", function() { Correct?
Yes
Related
This is somewhat related to other similar questions:
jquery ajax returns error but is success
jquery .ajax always returns error - data being added to database
Jquery Ajax Call always returns error
However, my problem doesn't seem to be the data:"json" issue.
My code is a simple POST request to a server and, for testing purposes, it is always returning 200 OK.
If I run the jquery code directly after document ready, it works just fine and calls the success function.
But if I attach it to a on("click") button event, it always return the error function. Nothing has changed on the server and I can see on the console that the right resource is being called.
My main code is located on a js file:
var myObj = function(){
var url = "myURL";
this.functionINeed = function(data, cb) {
ajaxPost(url, data, cb);
};
function ajaxPost(url, data, cb){
$.ajax({
"url" : url,
"contentType" : "application/json; charset=UTF-8",
"data" : data,
"type" : "POST",
"success" : function(serverData, textStatus, jqXHR){
cb(null, {
"serverData" : serverData,
"textStatus" : textStatus,
"jqXHR" : jqXHR
});
},
"error": function (jqXHR, textStatus, errorThrown) {
cb({
"jqXHR" : jqXHR,
"textStatus" : textStatus,
"errorThrown" : errorThrown
});
}
});
};
}
//I initialize the object directly on the js file
MyObj = new myObj();
Then, the first scenario: call the function directly on page load:
var data = {
"action" : "someaction",
"code" : "somecode"
}
MyObj.functionINeed(JSON.stringify(data), function(err, response){
if(err){
alert(err.errorThrown);
return err;
}else{
alert(response.textStatus);
return response;
}
});
This works fine: the server is called, the content is returned and JQuery calls the success function.
However, if I attach this code to a button event, it always returns the error function. I am monitoring the server and I am sure it is returning the correct data.
$("#myButton").on("click", function(){
var data = {
"action" : "someaction",
"code" : "somecode"
}
MyObj.functionINeed(JSON.stringify(data), function(err, response){
if(err){
alert(err.errorThrown);
return err;
}else{
alert(response.textStatus);
return response;
}
});
});
For the records, my server is Node.js with Sails.js, but this doesn't seem to matter.
The many similar questions are somehow related to the data:"json" issue, but I've removed it and the most weird is that the behavior only happens when you attach the code to an event.
I would suspect there is some kind of scoping issue involved (object being instantiated on the file, for ex.), but the server is being correctly called every time. I just can't understand why JQuery interprets all responses as errors (and empty server data).
What am I doing wrong here?
After an insane afternoon trying all kinds of combinations, a light bulb went off and I figured out the problem is that my button html was inside a form.
<form>
<button></button>
</form>
After changing to a regular div, it worked.
<div>
<button></button>
</div>
Which is -- to me -- absolutely insane. It seems JQuery captures more information than meets the eye when sending the ajax query, and this was messing the response parsing by expecting some form encoded behavior. Does it mean I cannot have special purpose buttons inside my forms? Since I am using Bootstrap, that's "OK" because I can use the a tags for this (tested and worked). But this seems a JQuery bug (version: 1.11.2)
I would like to give a high level explanation of what's my issue because I can't put up complete code which is too complex.
I have a button. when I click on the button, it pulls data from fb parses it and adds it to the page. Now after it is loaded to then page.. I want to run a script on the loaded content. I am running the script after the data is parsed but somehow it shows that element is not loaded by the time script started running. can some one throw some light.
$("somebutton").on("click",function(){
LoadAndParseFbData();
});
function LoadAndParseFbData(){
//loaded the json, parsed it and added to the page.
anotherScript();
}
function anotherScript(){
// this has some script related to data which is loaded dynamically by parsing json.
}
This is what i am trying on high level. please help thanks :)
$("somebutton").on("click",function()
LoadAndParseFbData();
});
function LoadAndParseFbData(){
FB.api(path, method, params, function(){
//loaded the json, parsed it and added to the page.
anotherScript();
});
}
function anotherScript(){
// this has some script related to data which is loaded dynamically by parsing json.
}
Run anotherScript() from within the ajax success callback:
$J.ajax({
url: url2,
type: "post",
data: { data: "yourdata", },
success: function (data, textStatus, jqXHR) {
anotherScript();
},
error: function(jqXHR, textStatus, errorThrown) {
/*error handling code here*/
}
});
I have a select box(list box) where it has 3 values drop down like Pending,Approve,NotApproved and when I select any one of them I want to fire a query so that I get data from database
like select * from table where status="Pending" without reloading page.
can any one help me how can I get data from database without page refresh in a php file.
Thanks in Advance
You can use a get or post AJAX request like so:
jQuery.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'xml/html/script/json/jsonp', // I guess html will be do or JSON if you are returning in a JSON format
data: {param1: 'value1'}, // Here you can send any additional parameters like status ( pending etc.)
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
// in the data variable you will receive the data from your PHP file if the request was succesfull
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
Reference: https://api.jquery.com/jQuery.post/
You should use AJAX for this (as is said in comments). You have can use :
XmlHttpRequest,
jQuery : Less code than an ordinary XmlHttpRequest and easier to implement. Perfect for beginner but heavy if you are looking for performance (to my mind),
And some libraries that I don't know.
I have created a loading screen plugin. The scenario is that i am doing page navigation using ajax loading. So before loading a page using ajax, i would show an loading screen using the code $('body).loadingMask('show') and once the page is loaded completely loaded, i would remove the loading screen using the code $('body').loadingMask('hide).
The problem is that, there is some delay in retrieving the target dom element inside the plugin.
This is the general structure of the code
$('body').loadingMask('show');
$.ajax({
url : 'views/next.html',
async : false,
success : function(content, textStatus, jqXHR) {
$('body').append(content);
},
error : function(content, textStatus, jqXHR) {
throw "Unable to load template. Please check the path and name of the template"
}
});
$('body').loadingMask('hide');
The problem is that , inside the show function of the loadingMask plugin, There is a delay in retrieving the target dom element(i.e body) . So pratically, the code $('body).loadingMask('show') runs only after the ajax page is finished loading.
In order to make it work , i have added a time delay. Which seems to work fine.
This is the modified code
$('body').loadingMask('show');
setTimeout(function(){
$.ajax({
url : 'views/next.html',
async : false,
success : function(content, textStatus, jqXHR) {
$('body').append(content);
},
error : function(content, textStatus, jqXHR) {
throw "Unable to load template. Please check the path and name of the template"
}
});
},500);
$('body').loadingMask('hide');
Now i can see the loading screen, while the page loads.
If you remove async:false you can call your plugin withing the ajax success, right after the content gets added.
async:false is deprecated and often leads to unforeseen problems
$('body').loadingMask('show');
$.ajax({
url: 'views/next.html',
success: function(content, textStatus, jqXHR) {
$('body').append(content).loadingMask('hide');
},
error: function(content, textStatus, jqXHR) {
/* likely need to remove maske here and add something to content to advise user*/
throw "Unable to load template. Please check the path and name of the template"
}
});
I'm using jQuery 1.2.6 (I know it's old, but I don't have a choice) I need to check the status of my ajax calls. I either want to use:
statusCode, or I could even use error(jqXHR, textStatus, errorThrown), except that textStatus, errorThrown and statusCode, aren't in my jQuery version.
Basically what I have to do, is know if the ajax call was aborted, or had an error for another reason. Any ideas how I can do this?
you could get the status text from the error callback:
$.ajax({
url: "/foo",
dataType: "text",
error: function(obj){
alert(obj.status + "\n" + obj.statusText);
}
});
http://jsfiddle.net/jnXQ4/
you can also get it from the complete callback if the request resulted in an error.
Edit: the ajax request also returns the XMLHttpRequest which you can then bind events to, though I'm not sure how cross-browser it is.
var request = $.ajax(options);
request.onabort = function(){
alert('aborted');
}