Parametrizable success function for jQuery ajax call - javascript

I want to create a function to call the jQuery $.ajax function with a parameter that indicates the success function name that must be called after the success event.
Something like this, but I don't know how to fill the "complete" parameter, or even if it's possible to do this:
function callService(successFunctionName){
$.ajax({
url: "serviceURL",
type: "POST",
data: "request",
contentType: "text/xml; charset=\"utf-8\"",
complete: successFunctionName
});
}
succesFunction1(){
}
successFunction2(){
}
Edit: I have to clarify that successFunctionName is an string

If successFunctionName is a string you could then use window[successFunctionName]. If it is the function itself it should work already
function callService(successFunctionName) {
$.ajax({
//...
complete: (typeof successFunctionName === "string" ? window[successFunctionName] : successFunctionName)
})
}

What you've done is correct.
When calling your callService you would do:
callService(function(resp)
{
alert('Success: ' + resp);
}):

I think you want to have call back for Ajax success, not complete ?
For success :
$.ajax({
......
success: successFunctionName
});
For complete :
$.ajax({
......
}).done(function(){
successFunctionName();
});

Related

How to return data from PHP to a ajax function

Hi I am currently learning php and I am trying to get data from php file using the below script but i am not getting any response
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " ); // not triggering
}
});
my php return stmt
There might be problems with File URL or file access. You can use complete callback to check request for errors like that:
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " );
},
// This method will be fired when request completes
complete: function(xxhr, status) {
alert("Status code: " + status);
}
});
If the status code is not success that means there is something wrong with your request.
You can check more callback options here.
It doesn't matter whether you use return or echo in your PHP file.
The success method must get a call if it's fine. However, if you use
return instead of echo, nothing will append to your request's data.
On the other hand, The PHP response will include in your 'data' variable in the function success.
You need use data in the assync function success
success: function(data) {
alert("Response : " + data);
},
Thanks for your Responses. I got the Solution to my problem. It seems since Ajax is asynchronous... its taking time to receive the resultant echo value from my php file. so I had to synchronize my Jquery using async : False.
$(function(){
$('#formID').on('submit',function(){
const data_set={
name:"Nipu chakraborty",
"phone":"01783837xxx"
}
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});

Jquery deferred not behaving as expected

I make 2 ajax calls. Second one should be called only when the first is finished:
var deferred = $.Deferred();
firstAjaxCall();
deferred.done(function () {
secondAjaxCall();
});
function firstAjaxCall() {
$.ajax({
url: '/SomeUrl',
type: 'POST',
success: function () {
deferred.resolve();
}
});
}
function secondAjaxCall() {
$.ajax({
url: '/SomeOtherUrl',
type: 'Get',
});
}
I also tried like this (jQuery deferreds)
$.when(firstAjaxCall()).done(function() {
secondAjaxCall();
});
but no luck.
Still, in the first example, sometimes the second call gets called first, sometimes it doesn't
In the first example the flow is like this:
firstAjaxCall();
secondAjaxCall();
deferred.resolve();
why is second call called first and before deferred.resolve() ?
You have to actually return the Deferred from $.ajax to $.when to make that work
function firstAjaxCall() {
return $.ajax({
url : '/SomeUrl',
type : 'POST'
});
}
function secondAjaxCall(data_from_first) {
return $.ajax({
url : '/SomeOtherUrl',
type : 'Get',
});
}
firstAjaxCall().done(secondAjaxCall);
You can try to call secondAjaxCall() in the success function of the first one
Like this :
function firstAjaxCall() {
return $.ajax({
url: '/SomeUrl',
type: 'POST',
success: secondAjaxCall()
});
}

how to set a deferred on ajax with jquery?

let me start with some code:
function sendAjax(data, type)
{
$.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}
$.when(sendAjax(someData, 'url')).then(function(data){
console.log(data); //undefined
});
$.when(sendAjax(someOtherData, 'url')).then(function(data){
console.log(data); //undefined
});
the issue i'm having is that data comes in as undefined
if i use success in the $.ajax the data comes in fine
The main idea here is that i should write the sendAjax() method once and use it through the application, but i don't think i set it up properly
ant ideas?
You need to return the promise return by $.ajax() from sendAjax
function sendAjax(data, type)
{
return $.ajax({
type : "GET",
dataType : "jsonp",
url : rest + type,
data : data,
});
}

$.ajax + make success function parameterized

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);

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