How to add a callback on click jQuery function? - javascript

I have an asynchronous problem and for solve it I think I must use a callback. I want to execute some code after the code that is inside of the click() function finishes. How can I do that?
$("#mybutton").click(function() {
$.ajax({
type: 'GET',
data: {
accion: "get_option_child",
id: id
},
url: 'webservices.php',
success: function(data) {
var json = JSON.parse(data);
// some code
}
});
});

Just add a call to your desired function at the end of the success handler for ajax:
$("#agregar_opcion").click(function() {
// ...
$.ajax({
// ...
success: function(data) {
// ...
functionThatRunsAfterAjaxSuccess();
}
});
});
function functionThatRunsAfterAjaxSuccess() {
// gets called once the ajax call happening on click is successful
}

Related

Call Function to another class

I have problems to pass the variables to another file, I already realize the code and I do not find the solution, it sends me error in the function
onclick="limit();javascript:AyudaTipos(2)"/>
function
function limit (){
$.ajax({
url: 'Tipos.php',
type: 'POST', // GET or POST
data: {"acreedor":$("#acreedor").val(),"importe2":$("#importe2").val(),
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error! Funcion Limite Anual");
}
}
});
}
Resolved:
$(function(){
$('#help').click(function(){
$.ajax({
url: 'Tipos.php',
type: 'POST', // GET or POST
data: {"acreedor":$("#acreedor").val(),"importe2":$("#importe2").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!nuevo");
}
});
});
});
Thank You

How to pass a variable from ajax to nested ajax

I'm sending ajax call and getting an answer that I need from the first ajax then I want to pass my result to my nested ajax, my var (result) is null in the nested ajax/settimeout fun, can I pass it ? Am I missing something ?
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
contentType:'json' ,
dataType:'text',
success: function (result) {
alert(result);**-> is fine - not null**.
// a or result is null when I hit the getCurrentDoc- function althought I get the data I need from getCustomerGuidId function
var a = result;-> tried to pass it to a new var..IDK.. I
thought it will help... it didn't.
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,-> here it's null
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});
You can try something like this will help to pass value to nested ajax call
function test(){
var myText = 'Hello all !!';
$.get({
//used the jsonplaceholder url for testing
'url':'https://jsonplaceholder.typicode.com/posts/1',
'method':'GET',
success: function (data) {
//updating value of myText
myText = 'welcome';
$.post({
'url':'https://jsonplaceholder.typicode.com/posts',
'method':'POST',
//data.title is the return value from get request to the post request
'data':{'title':data.title},
'success':function (data) {
alert(data.title +'\n' + myText);//your code here ...
}
});
}
});
}
An old question and you've likely moved on, but there's still no accepted answer.
Your setTimeout takes an anonymous function, so you are losing your binding; if you have to use a Timeout for some reason, you need to add .bind(this) to your setTimeout call (see below)
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
contentType:'text',
data: a,
success: function (data) {
}
});
}.bind(this), 2000);
At a guess you're using a Timeout because you want to ensure that your promise (i.e. the first ajax call) is resolving prior to making the nested call.
If that's your intention, you can actually scrap setTimeout completely as you have the nested call in the first ajax success call, which only runs once the promise has been resolved (providing there isn't an error; if so, jQuery would call error rather than success)
Removing setTimeout means you won't lose your binding, and a should still be result (hopefully a is an object, otherwise your second call is also going to experience issues...)
Lastly, after overcoming the binding issue you wouldn't need var a = result; you should be able to pass result directly to your nested ajax call.
Good luck!
In the nested ajax you send a as a param name, not as a param value.
So you can try the following (change param to actual param name which your server expects):
$.ajax({
url: '#Url.Action("getCustomerGuidId", "Document")',
type: 'POST',
cache: false,
data: { "classNum": currentclassNum},
dataType:'text',
success: function (result) {
setTimeout(function () {
$.ajax({
type: "GET",
url: '#Url.Action("getCurrentDoc", "Document")',
data: {param: result},
success: function (data) {
}
});
}, 2000);
},
error: function (result) {
alert("fail " + result);
}
});

Ajax calling order within multiple functions

In the following code, I want the alerts to come in order (1st call followed by the second), but it keeps coming the other way around. This is causing some variables to become undefined. What is the order of execution when having multiple ajax queries in the same code? How can I change the order of the alerts?
$(document).ready(function () {
function get_det() {
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
}
});
}
$.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php",
success: function (result) {
initializeMap();
}
});
function initializeMap() {
//other code
calculateAndDisplayRoute();
//other code
function calculateAndDisplayRoute() {
//other code
get_det();
alert("2nd call");
//other code
}
}
});
Ajax is by default Asynchronous meaning there will be no wait for response.
That is why your 2nd call is calling before ajax request.
You can make ajax Syncronuous by setting async: false. Not recommended as it could cause browser hanging.
For Asynchronous process you can use callback function which only call when your request is completed.(Recommended)
In javascript you can do like this(For your code):
function get_det(callback) {//Your asynchronous request.
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
callback();//invoke when get response
}
});
}
call like this:
get_det(secondFunction);//calling with callback function
function secondFunction()//your callback function
{
alert("2nd Call");
}
The difference in behavior is due to async nature of ajax calls. In your case, you want to perform some code once the call has executed, hence, you need to use callback functions.
Update your code to following
function get_det(callback) {
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
if(callback) {
callback();
}
}
});
}
function calculateAndDisplayRoute() {
//other code
get_det(function() {
/* this is the place where you need to put code
* that needs to be executed after the ajax has been executed */
alert("2nd call");
});
}
I suggest chaining the promises that $.ajax returns.
$(document).ready(function () {
function get_det() {
return $.ajax({
url: "aa.php",
type: "POST"
}).then(function(result) {
// Do some stuff - you can even modify the result!
// Return the result to the next "then".
return result;
})
}
// Named after the php script you're hitting.
function dd() {
// Return the promise from Ajax so we can chain!
return $.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php"
});
}
function initializeMap() {
// Do stuff before call
return get_det().then(function(getDetResult) {
// Do stuff after AJAX returns..
return {
getDetResult: getDetResult,
mapInitialized: true
};
});
}
// use it!
dd().then(function(result) {
alert('1st call');
// Pass result from dd to initializeMap.
return initializeMap(result);
}).then(function(initMapResult) {
alert('2nd call', initMapResult.mapInitialized);
});
});

how to use ajax response data in another javascript

I am working with google map.My map data come from php using ajax response.
My ajax code:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
console.log(result);
}
});
</script>
Now I have need to put my response data in my map var location
function initialize() {
var locations = [
//Now here I put my ajax response result
];
How can I do that?
You'll have to refactor your code a little. I'm assuming you call initialize from the success callback.
Pass the locations array as an argument to initialize.
function initialize(locations) { ... }
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
initialize(result);
}
});
Then you can cut down even more and just do success: initialize, as long as initialize doesn't expect other parameters.
Here is a fiddle with an example using $.when but its for SYNTAX only not making the call
http://jsfiddle.net/2y6689mu/
// Returns a deferred object
function mapData(){ return $.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text'
});
}
// This is the magic where it waits for the data to be resolved
$.when( mapData() ).then( initialize, errorHandler );
EDIT** function already returns a promise so you can just use
mapData().then()
per code-jaff comments
This is done using callbacks, http://recurial.com/programming/understanding-callback-functions-in-javascript/ , here's a link if you want to read up on those. Let's see your current code here:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
console.log(result);
}
});
</script>
As you noticed, the 'result' data is accessible in the success function. So how do you get transport it to another function? You used console.log(result) to print the data to your console. And without realizing it, you almost solved the problem yourself.
Just call the initialize function inside the success function of the ajax call:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
initialize(result);
}
});
</script>
Is expected dataType response from $.ajax() to mapajax.php call text ?
Try
$(function () {
function initialize(data) {
var locations = [
//Now here I put my ajax response result
];
// "put my ajax response result"
// utilizing `Array.prototype.push()`
locations.push(data);
// do stuff
// with `locations` data, e.g.,
return console.log(JSON.parse(locations));
};
$.ajax({
type: "POST",
url: "mapajax.php",
dataType: 'text',
success: function (result) {
initialize(result);
}
});
});
jsfiddle http://jsfiddle.net/guest271314/maaxoy91/
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

Two Ajax onclick events

So I have had to modify some old existing code and add another ajax event to onclick
so that it has onclick="function1(); function2();"
This was working fine on our testing environment as it is a slow VM but on our live environment it causes some issues as function1() has to finished updating some records before function2() gets called.
Is there a good way to solve this without modifying the js for function2() as this the existing code which is called by other events.
Thanks
Call function2 upon returning from function1:
function function1() {
$.ajax({
type: "POST",
url: "urlGoesHere",
data: " ",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//call function2
},
error:
});
}
Or wrap them in a function that calls both 1 and 2.
You need to use always callback of ajax method, check out always callback of $.ajax() method http://api.jquery.com/jquery.ajax/.
The callback given to opiton is executed when the ajax request finishes. Here is a suggestion :
function function1() {
var jqxhr = $.ajax({
type: "POST",
url: "/some/page",
data: " ",
dataType: "dataType",
}).always(function (jqXHR, textStatus) {
if (textStatus == 'success') {
function2();
} else {
errorCallback(jqXHR);
}
});
}
I'm assuming you use Prototype JS and AJAX because of your tags. You should use a callback function:
function function1(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function function2(callback) {
new Ajax.Request('http://www.google.nl', {
onSuccess: function(response) {
callback();
}
});
}
function both() {
function1(function() {
function2();
});
}
Then use onclick="both();" on your html element.
Example: http://jsfiddle.net/EzU4p/
Ajax has async property which can be set false. This way, you can wait for that function to complete it's call and set some value. It actually defeats the purpose of AJAX but it may save your day.
I recently had similar issues and somehow calling function2 after completing function1 worked perfectly. My initial efforts to call function2 on function1 success didn't work.
$.ajax({
type: "POST",
url: "default.aspx/function1",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // to make function Sync
success: function (msg) {
var $data = msg.d;
if ($data == 1)
{
isSuccess = 'yes'
}
},
error: function () {
alert('Error in function1');
}
});
// END OF AJAX
if (isSuccess == 'yes') {
// Call function 2
}

Categories