I get some scripts asynchronously on my login page:
$.when(
$.getScript("/Scripts/View/scroll-sneak.js"),
$.getScript("/Scripts/kendo/kendo.custom.min.js"),
$.Deferred(function (deferred) {
$(deferred.resolve);
})
).done(function (res1, res2) {
if (res1[1] == "success") {
}
if (res2[1] == "success") {
}
alert('all script loaded...');
});
I have two queries here:
How can I leverage browser cache here, as getScript always take fresh script.
How can I have promise that this script will be available to all pages on same domain.
Alternate solutions are welcome.
Answer to your first question is set cache true. Jquery documentation page also mentions a way
jQuery.cachedScript = function( url, options ) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
For your second question: Please clarify more, what you want to achive?
Related
I have an app that needs three different post requests to sync data, I only want one thing to happen when all three are completed but the jquery when is not working. All posts use the success function to process data that the server sent back. Here is my code:
var picUploads = $.post("http://www.epcmapp.co.za/php2/uploadPic.php", {Images: jsonPics}, function (res) {
alert("Ajax Images return");
if(res != "" && res != "53554343455353")
alert(res);
});
var pdfUploads = $.post("http://www.epcmapp.co.za/php2/uploadPDF.php", {PDFs: jsonPDF}, function (res) {
alert("Ajax PDF return");
if(res != "" && res != "53554343455353")
alert(res);
});
var sync = $.post("http://www.epcmapp.co.za/php2/sync.php", {data: json}, function (res) {
alert("Ajax return");
var result = JSON.parse(res);
dropSyncTables();
checkDB();
for (var i in result) {
populateDB(result[i].toString());
}
readDB();
loadProjects();
loadAdditional();
loadProcessRows();
loadAttachments();
});
$.when(picUploads, pdfUploads, sync).then(function() {
$("#loadIcn").attr("src", "images/check3.png");
});
The alerts in the posts do not pop up and the code inside the jquery then never runs. How am I supposed to do this then?
If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.
Instead of this:
$.post("/post/url.php", parameters, successFunction);
you would use this:
$.ajax({
url: "/post/url.php",
type: "POST",
data: parameters,
success: successFunction,
error: errorFunction
});
There are lots of other options available too. The documentation lists all the options available.
ref This answer
First check your console.log. You would probably find the issue there. But even if you find it you would always want some kind of errorhandling and this is possible with the deffered objects:
$.when(picUploads, pdfUploads, sync)
.then(function() {
$("#loadIcn").attr("src", "images/check3.png");
})
.fail(function(ts) {
alert('something failed');
console.log(ts.responseText); //Check in console what went wrong here
})
It is also possible to use done() and fail() with $.post (as of jQuery 1.5)
var picUploads = $.post("http://www.epcmapp.co.za/php2/uploadPic.php", {Images: jsonPics}, function (res) {
alert("Ajax Images return");
if(res != "" && res != "53554343455353")
alert(res);
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
});
Answer is simular to Adding a general parameter to all ajax calls made with jQuery, but I need to add additional param only for ajax calls with method post:
$.ajax({
url: url,
type: "POST",
data: data,
success: success,
dataType: dataType
});
May I achieve this without adding param into all ajax calls directly (editing inplace), i.e. via setup param via some sort of common config?
Thanks for comments.
I've also found this post usefull: jQuery's ajaxSetup - I would like to add default data for GET requests only
Solution is (not fully tested yet):
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (originalOptions.type == 'POST') {
originalOptions.data = $.extend(
originalOptions.data,
{
some_dummy_data: 'lksflkdflksdlkf'
}
);
}
});
P.S. My final solution:
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.type.toLowerCase() == 'post') {
options.data += '&some_dummy_data=lksflkdflksdlkf';
if (options.data.charAt(0) == '&') {
options.data = options.data.substr(1);
}
}
});
Changes:
options.type contains post in lowercase (just in case I've added
toLowerCase)
options.data is string, not object, so I've rewrited query change via plain string manipulation
originalOptions didn't worked, but with options it workes.
I have a quiz type application. Each question has two answers with a value of 1 or 2. When the quiz is complete, if they have a score lower than 10, they get redirected to a page.
This is my code for this part.
while (n < numResults) {
increment = minScore + (interval * n);
if (totalScore <= increment) {
if(totalScore <= 10) {
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
})
.done(function( msg ) {
window.location.href("www.page2.html");
});
}
return;
} else {
n++;
}
}
I have a few things I am trying to solve. Firstly, before the redirect, some data (answers and url) is posted to PHP so I can process it. One thing I pass is the current window url. The reason I do this is because the
url has a format like
www.page1.com?a=1&b=2&c=3
In PHP, I parse this url and grab the values.
My first problem is that although the data is successfuly sent to PHP and handled, and returns a response of Success, the done function never seems to fire, therefore no redirect occurs (I put an alert in this function
to ensure it is not firing). In PHP, after I process the data, I do this
var_dump($response); //Outputs Success
return json_encode($response);
The second thing I am trying to work out is the redirect url (page2.html). Within this page, I have a button. This button has a standard link, and then I need to give it some params from the initial url.
So this pages button might be something like
www.externallink.com?a=1&c=2
How can I get the original URLs params into a button on the redirected url?
Thanks
USE below function insted of done:
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
success:function(data){
window.location.href("www.page2.html");
});
})
For your 1st part:
Try putting the error function of jQuery ajax call. Sometimes when the return type of result does not match with the expected datatype of ajax call, then result comes in the response of error.
error: function (data, status, e) {
}
For your 2nd part:
Attach click event for the button in the handler and read the current URL query string using window.location.search and then redirect using
window.location = newURL + "extra query params";
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function(data, textStatus, jqXHR) {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) {
alert( "complete" );
});
If you .done() callback never invoked, try to set debuggers or alerts inside .fail() or .complete() callback functions. Check if you have an error during ajax call and at all if the call has complete statement.
Here more information: http://api.jquery.com/jquery.ajax/
I have an autocomplete feature in my application which makes an ajax request to server.
However, once I get data from server, I want to use the look up feature instead of using the service url(to minimize calls to server).
Here is what my js looks like
$('#country').autocomplete({
serviceUrl : './countryCache?',
paramName : 'countryName',
transformResult : function(response) {
return {
// must convert json to javascript object before process
suggestions : $.map($.parseJSON(response), function(item) {
return {
data : item.name
};
})
};
},
showNoSuggestionNotice:true,
onSelect: function (value, data) {
$('#countryId').val(value.data);
}
});
Here is a sample from my ajax call to countryCache - "India, Iceland, Indonesia".
If the user has typed I, the server returns back the result as above.
Now when the user types in n after I, I dont want to make a call to server again.
Can someone help me achieve it.
There is a simple solution for this in the jQuery UI Autocomplete documentation. There you'll find a section titled Remote with caching that shows how to implement what you are looking for.
I adapted the code from that site to this question, and added some comments for clarification:
var cache = {};
$( "#country" ).autocomplete({
source: function( request, response ) {
// If the term is in the cache, use the already existing values (no server call)
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
// Add countryName with the same value as the term (particular to this question)
// If the service reads the parameter "term" instead, this line can be deleted.
request.countryName = request.term;
// Call the server only if the value was not in the cache
$.getJSON( "./countryCache", request, function( data, status, xhr ) {
cache[ term ] = data;
response( data );
});
},
select: function (event, data) {
$('#countryId').val(data.item.value);
}
});
As I didn't know exaclty the format of the JSON, I just used a basic one that for the text "In" returned: ["India","Indonesia","Spain"] (without ids, just a plain array).
If what you are using is the Ajax AutoComplete plugin for jQuery (the code above looks like it, although the question was tagged with jquery-ui-autocomplete), then you don't have to worry about caching, because the plugin does it automatically for you.
From the plugin's documentation:
noCache: Boolean value indicating whether to cache suggestion results. Default false.
As you didn't specify any value for nocache, then it will take the default value that is false, and it will perform caching directly.
I ended up not using this method at all and going with fast, quick searches with a limit of 100. But since I asked, here is how I sent requests using only the first character:
// global variables: models [], result {}
lookup: function(query, done) {
var mdl = $("#autocomplete").val();
if (mdl.length == 0) {
names = [];
result.suggestions = models;
done(result);
return;
} else if (mdl.length != 1) {
result.suggestions = names;
console.log(result);
done(result);
return;
}
var jqHXR = $.ajax({url: "search.php",
data: {"q": mdl},
dataType: "json",
method: "GET" }
)
.done(function(data, status, jqXHR){
models = [];
$.each( data, function( key, val) {
names.push({ value: val.u, data: { category: genders[val.g] } });
});
result.suggestions = names;
done(result);
})
.fail(function (data, status, errorThrown) {
console.log("failed: "+status+"| error: "+errorThrown);
console.log(data);
});
},
A colleague of mine used devbridge and my research seems to verify that there's an attribute for the devbridgeAutocomplete object for minChars and lookupLimit. Maybe there are different instances of devbridgeAutocomplete, but I thought it was worth posting just in case they're similar, though I should assume you would have seen them already :).
Here's the code:
var a = $('#<%= txtFindName.ClientID %>').devbridgeAutocomplete({
minChars: 3,
lookupLimit: 20,
serviceUrl: 'AutoComplete/ADUsers.aspx',
onSelect: function (suggestion) {
$('#<%= txtTo.ClientID %>').val( $('#<%= txtTo.ClientID %>').val() + ',' + suggestion.data);
$('#<%= txtFindName.ClientID %>').val('');
}
});
I'm using the .load() method in jQuery but I've realized that the request to my server should use ISO-8859-1 charset and not UTF-8. The problem is that I can't find how to set load method to use a different encoding. I read that .ajax method has 'content-type' setting to do this, but what about load method? I find load very useful when I need to update data from some divs without refreshing the page.
Any help would be appreciated, thanks.
Using ajaxSetup allows you to specify the settings for new ajax calls.
All subsequent Ajax calls using any function will use the new
settings, unless overridden by the individual calls, until the next
invocation of $.ajaxSetup().
with beforeSend you can provide a callback function to modify the XMLHttpRequest object before it's going to be send. jQuery Reference
Mozilla provides documentation about overrideMimeType():
Overrides the MIME type returned by the server. This may be used, for
example, to force a stream to be treated and parsed as text/xml, even
if the server does not report it as such.This method must be called
before send().
Borrowing code from this answer you could do:
$.ajaxSetup({
'beforeSend' : function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
},
});
//$('body').append('<div id=qqq>dfsdfsdf</div>')
//$('#qqq').load2('/index.php?showtopic=925 #post-29397','','','text/html; charset=utf-8')
//$('#qqq').load2('/index.php?showtopic=925 #post-29397','','','text/plain; charset=windows-1251')
//
jQuery.fn.load2 = function( url, params, callback, overrideMimeTypeVar) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
// ++++++++++++++++++++++++++++++++++++++++++++++++++
beforeSend: function(x) {
if(x && x.overrideMimeType && overrideMimeTypeVar!=''){
x.overrideMimeType(overrideMimeTypeVar);
}}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};