$.ajax + make success function parameterized - javascript

A stupid question.
I am calling $.ajax function in many of my button clicks, text changed, drop down value changed etc. So I thought of making this function parameterized. Below is the code I was trying to use.
function ajaxCall(ajaxUrl, methodName) {
try {
$.ajax({
type: 'POST',
url: ajaxUrl,
success: methodName
},
dataType: "html"
});
}
catch (e) {
alert(e.message);
}
}
In this the "methodName" should be the name of the method the control should go.
Or in short, when I use ajaxCall('test.aspx','testMethod'), the control should be transferred to
function testMethod(xmlResponse){
alert ('Inside testMethod');
}

In JavaScript you can use functions as variables, so just call ajaxCall with url and success handler.
function testMethod (xmlResponse) {
alert('Inside testMethod');
}
function ajaxCall (ajaxUrl, methodName) {
try {
$.ajax({
url: ajaxUrl,
type: 'POST',
dataType: 'html',
success: methodName
});
}
catch (e) {
alert(e.message);
}
}
ajaxCall('test.aspx', testMethod);

Related

Setting global variable inside nested ajax calls

I have a specific requirement with nested ajax calls. I am trying to set a globally accessible variable inside success of one ajax call and this ajax call is being invoked inside success of another ajax call. Eventually the parent success method of parent ajax call utilizes the global variable to perform further operations. The problem is that the value of global variable always remains blank. It works if I make the second ajax request as async:false; but this solution defeats the very purpose of using ajax in the first place.
Let me share a small sample code to illustrate my problem:
//global variables
var xURL = "https://sampleurl.com";
var glblID = "";
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json",
success: function (msg) {
//some js code here
//second ajax call
FetchID();
//more js code here
if(glblID != "")
{
window.location.href = xURL + "?id=" + glblID
}
else
{
window.location.href = xURL;
}
}
});
function FetchID()
{
$.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json",
success: function (data) {
glblID = data.d;
}
});
}
As of jQuery 1.5 implement the Promise interface, giving them all
the properties, methods, and behavior of a Promise
//first ajax call
$.ajax({
url: url1,
data: data1,
type: "POST",
contentType: "application/json"
}).then(function (msg) {
//second ajax call
FetchID().then((data) => {
var glblID = data.d;
if (glblID != "") {
//do something with glblID
} else {
//do something else
}
});
});
function FetchID() {
return $.ajax({
url: url2,
data: data2,
type: "POST",
contentType: "application/json"
});
}

trigger a javascript function before on any AJAX call

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

call and end ajax function

When I call ajax function such
$(save_Data()).ajaxStop(function()
{
new_Form(code);
}
function save_Data()
{
// here send data to php and save it
}
Now, I call another ajax function such
$(get_Data()).ajaxStop(function()
{
// doing some thing
}
function get_Data()
{
$.ajax
({
type: 'POST',
url: 'insert_Stock.php',
data: { insert_Data : inserted_Data },
dataType: 'json',
success:function(data)
{
// doing some thing such call another function to control on form
}
});
}
When I call save_Data function already new_Form function execute, after that when I call get_Data function the new_Form function execute automatically.
Why new_Form function execute?
If I understood you this is what you want.
function doSomething(){
//your code here if success
}
function doSomethingElse(){
//your code here if error
}
function finallyDoSomethingElse(){
//your code here no matter what is the result of post
}
$.ajax({
type: 'POST',
url: 'insert_Stock.php',
data: { insert_Data : inserted_Data },
dataType: 'json',
success: doSomething,
error: doSomethingElse,
complete: finallyDoSomethingElse
});

Creating callbacks with Javascript

Alright, so I'm a little confused on how to create callbacks in JavaScript and a mix of jQuery.
Here's what I'd like to do:
function saveArtDep(vars, callback) {
$.ajax({
url: 'j_artDepAjax.php',
type: 'POST',
data: vars,
success: function(data) {
// callback to fire when success
}
});
}
The reason I want to do this is to be able to re-use this function and having a different "loading" message for what I need it for. In other words, the scenario would look like this:
$('div#job').html('loading...');
saveArtDep('job_id=3&update_art=true', function(){
$('div#job').html('success!');
});
Any help would be great!
In saveArtDep the parameter callback refers to a function, so you can invoke it using callback()
function saveArtDep(vars, callback) {
$.ajax({
url: 'j_artDepAjax.php',
type: 'POST',
data: vars,
success: function(data) {
// callback to fire when success
callback();
}
});
}
You almost had it. You can pass anything to callback and we make sure that it is a function before executing it, in the below seen code.
function saveArtDep(vars, callback) {
$.ajax({
url: 'j_artDepAjax.php',
type: 'POST',
data: vars,
success: function(data) {
// callback to fire when success
if (typeof callback === 'function') {
callback();
}
}
});
}
success: function(data) {
if(typeof callback == 'function') {
callback(data);
}
}

problems executing a jquery ajax call within a function

I would like to put an ajax call within a function since I use it repeatedly in multiple locations. I want a manipulated version of the response returned. Here's what I'm trying to do (greatly simplified).
a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
return response;
});
}
What's happening, however, is that the append function is running before "a" has been defined in the getAjax function. Any thoughts?
AJAX is asynchronous. This means that the code in the success handler is delayed until the request is successful, while the rest of the code continues as normal. You need to put the relevant code in the AJAX success handler:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
$(document.body).append('<div>'+response+'</div>');
});
}
Note that I have also optimised your body selector by using the native Javascript document.body rather than using the standard tag selector.
Edit Callback version
function getAjax(callback) {
$.ajax({
type: 'GET',
url: 'someURL',
success: callback
});
}
You can now do the code inline using a callback function:
getAjax(function(response) {
$(document.body).append('<div>'+response+'</div>');
});
or
getAjax(function(response) {
alert(response);
});
or whatever.
The code inside the anonymous function call will be processed when the AJAX request is complete.
There are two ways to taggle this. one is to use the success callback:
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
the other is to set async to false http://api.jquery.com/jQuery.ajax/:
var a;
getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
async: false,
success: function(response) {
a = response;
});
}
Important note on non async:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
Why don't you return the response to another function in the success callback. This should handle your need for different responses:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
}
function AppendResponse(response) {
$('body').append('<div>'+response+'</div>');
}
One suggestion I have is to pass a trigger to the command you want to run into the AJAX function so that it will run after AJAX has received a response-
a = getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
inputText(response);
});
}
inputText(someText) {
$(document.body).append('<div>'+ someText +'</div>');
}
That way you can create if statements / other alternatives to continue to use the same AJAX command for different results
You can give a handler to the function getAjax(), but if the user needs the information for the next decision then why not wait using async: false?
function getAjax(handler) {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
handler(response);
});
};
function callGetAjax(response) {
if(response === undefined) {
getAjax(callGetAjax);
} else {
$('body').append('<div>'+response+'</div>');
}
}

Categories

Resources