trigger a javascript function before on any AJAX call - javascript

Here, I have a function which needs to be called before any AJAX call present in the .NET project.
Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.
In short, I want to make function behave like an event which will be triggered before any AJAX call
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And below is current way to call function:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>

You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
It reduces the call that you have made onsubmit() of form tag!
UPDATE:
to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});

The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).
jQuery already supports custom publish-subsrcibe
For this specific example just do this:
//Ajax call
function SaveData(element) {
var doAjax = true;
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
if (element === myForm)
{
doAjax = checkConnection();
}
if ( doAjax )
{
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
else
{
// display a message
}
}
Hope i understand correctly what you mean.
UPDATE:
in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))
If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well

You can use:
$(document)
.ajaxStart(function () {
alert("ajax start");
})
.ajaxComplete(function () {
alert("ajax complete");
})
That's it!!

use
beforeSend: function () {
},
ajax method

Related

Ajax - All request are Done/Completed

I have a difficulty to know when all Ajax requests are completed because I need this information to call another function.
Difficulty are to know when my 4/5 function with requests are completed. I use native function of ajax and none is working for me.
I used Chrome, and async requests.
Someone Helps me
I use this(not work):
$(document).ajaxStop(function() {
alert("Completed");
});
and this (not Work):
$(document).ajaxComplete(function() { alert("Completed"); });
Both ways I try use in another function thal calls all requests:
Example:
function Init()
{ Search("123"); Search2("1234"); Search3("12345");
... }
Extract one (of 5 requests,others are very similar ) of my request:
function Search(user) {
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
success: function(response, textStatus, jqXHR) {
try {
if (response != null) {
alert("Have Data");
} else {
alert("are empty");
}
} catch (err) {
alert("error");
}
},
error: function() {
alert("error");
}
}); }
have you tried putting it in a done function? something like...
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP'
}).done(function (data) {
code to execute when request is finished;
}).fail(function () {
code to do in event of failure
});
bouncing off what Michael Seltenreich said, his solution, if i understand where you guys are going with this...might look something like:
var count = 0;
function checkCount(){
if(count == 5 ){
//do this, or fire some other function
}
}
#request one
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
#request two
$.ajax({
url: 'www.example.com/' + user,
type: 'GET',
async: true,
dataType: 'JSONP',
}).done( function(data){
count += 1
checkCount()
})
and do it with your five requests. If that works out for you please make sure to mark his question as the answer;)
You can create a custom trigger
$(document).trigger('ajaxDone')
and call it when ever you finished your ajax requests.
Then you can listen for it
$(document).on('ajaxDone', function () {
//Do something
})
If you want to keep track of multiple ajax calls you can set a function that counts how many "done" values were passed to it, and once all are finished, you can fire the event.
Place the call for this function in each of the 'success' and 'error' events of the ajax calls.
Update:
You can create a function like so
var completedRequests= 0
function countAjax() {
completedRequests+=1
if(completedRequests==whatEverNumberOfRequestsYouNeed) {
$(document).trigger('ajaxDone');
}
}
Call this function on every success and error events.
Then, ajaxDone event will be triggered only after a certain number of requests.
If you wanna track specific ajax requests you can add a variable to countAjax that checks which ajax completed.

Stop Ajax Request And Call New Ajax

in this code, i take typing character from user and search it in database,but when user enter each character,running new ajax request with previous ajax,
i want when call search function, cancel previous ajax request and run new ajax request;
html code :
<input type="text" onkeyup="search()">
js code:
function search () {
var request=$.ajax({
type: "POST",
url: "php/h.php",
data: {k_word:k_word},
dataType: "json",
success: function (data) {
ghtml(data)
}
})
}
Also i tried with abrot() like this :
var request;
function search () {
request.abort();
request=$.ajax({
type: "POST",
url: "php/h.php",
data: {k_word:k_word},
dataType: "json",
success: function (data) {
ghtml(data)
}
})
}
but not working
That's generally not how it's done, instead throttling is used to only call the ajax function when the user stops typing for a given time
First of all, get rid of the inline javascript
<input type="text" id="myInput" />
then use an event handler
$('#myInput').on('keyup', function() {
clearTimeout( $(this).data('timer') );
$(this).data('timer',
setTimeout(function() {
$.ajax({
type : "POST",
url : "php/h.php",
data : {k_word:k_word},
dataType : "json",
success : function (data) {
ghtml(data)
}
});
}, 500)
);
});
This sets a timeout on the ajax call, and that timeout is cleared if a new key is pressed within half a second, so the ajax call is only made when the user stops typing for more than 500 milliseconds

jQuery Wait until async ajax calls are finished

Hi I have 2 ajax calls in my script, I need them run asnyc to spare time, but I need the second to wait until the first is finished.
$.ajax({
type: "POST",
url: "getText.asmx/ws_getText",
data: parO1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d.data);
},
error: function () {
chyba("chyba v požadavku", "df");
}
});
if (parO2.length > 0) {
$.ajax({
type: "POST",
url: "getText.asmx/ws_getText",
data: parO2,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/*WAIT UNTIL THE FIRST CALL IS FINISHED AND THAN DO SOMETHING*/
},
error: function () {
chyba("chyba v požadavku", "df");
}
});
}
So any ideas? Thanks
If using jQuery 1.5+, you can use jQuery.when() to accomplish this. Something like (shortened the ajax calls for brevity, just pass the objects as you're doing above)
$.when($.ajax("getText.asmx/ws_getText"),
$.ajax("getText.asmx/ws_getText")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the
// first and second ajax requests, respectively
var jqXHR = a1[2]; // arguments are [ "success", statusText, jqXHR ]
});
You don't know in which order they will return so if you were rolling this by hand, you would need to check the state of the other request and wait until it has returned.
You need to wire up the second call to be contained within the callback of your first ajax call. Like so:
success: function(msg)
{
alert(msg.d.data);
if(par02.length > 0)
{
// Your 2nd ajax call
}
},
Since JavaScript doesnt run in multiple threads on the client, you can't block the thread until certain conditions are met.
Using jquery
$.ajax({
type: "POST",
async:false, // ** CHANGED **
url: "getText.asmx/ws_getText",
data: parO1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d.data);
}
, error: function () {
chyba("chyba v požadavku", "df");
}
});
Here is another answer on running dual ajax requests. Like Tejs, the user makes an ajax call within the success method...
The poster states You're better off having the success method launch a new ajax request.."
Having two $.ajax() calls in one script

Jquery Display Message then Ajax then hide message

il give an example
document.ready(function() {
$("#Show").bind("click", function()
{
var F = Function2();
if (F)
{
// Do Other Stuff.
}
}
});
function Function2()
{
$("#Message").Show();
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").Hide();
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
}
</script>
<div id="Message" style="display:none;">
<!-- Loading Image In here -->
</div>
<a href="#" id="Show" onclick="return:false;">Show then Hide</false>
</code>
Now what I want to happen is for this messagebox to show however the AJAX for some reason wont show it until the AJAX Request is finished by which point it is too late. I have set async to false which hasent helped either.
I think the root of this issue is a syntax error. JavaScript is case sensitive, so the correct syntax would be lowercase show() and hide()
If you're still having an issue after fixing the syntax errors, try using the ajaxStart event to show the message and hide it on success.
//use the ajaxstart event to display the message
$('#message').ajaxStart(function() {
$(this).show("slow");
});
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").hide("slow"); //hide message on success
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
Delaying the show or hide
$("#message").delay(3000).hide("slow");
Here's a jsFiddle: http://jsfiddle.net/rs83R/
Try hiding the Message div in the click event after getting true or false.
Remove the async:false, I do not think that is anyway relevant to fixing this problem. The purpose of AJAX call is to make an asynchronous call.
Also, there is an error its not $("#Message").Show() its $("#Message").show() with all lowercase, same goes for hide().
Try changing these, I hope it should work.

Conditionally adding option to jQuery Ajax call

I have the following working Ajax call -
$.ajax({
url: ajaxUrl,
type: sendHttpVerb,
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
complete: function () {
setTimeout($.unblockUI, 2000);
},
success: function (response, status, xml) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
callbackFunction(response);
},
error: function (jqXHR, textStatus, errorThrown) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
dcfForm.ajaxErrorDisplay(jqXHR, textStatus, errorThrown)
}
});
My problem is the I conditionally want to add an option when I invoke the Ajax call. For example, adding data: sendRequest before I issue the Ajax request.
My problem I cannot find an example for the syntax on how to do this without completely duplicating the entire function.
what about a ternary operation:
$.ajax({
data: condition ? sendRequest : undefined,
... the rest
});
If that's not your taste, some people seem to forget $.ajax doesn't take a long group of paramters, but an object:
var ajax = {};
ajax.success = function (data) { ... };
ajax.type = 'GET';
if (myCondition) {
ajax.data = sendRequest;
}
$.ajax(ajax);

Categories

Resources