I'd like to fire a JavaScript function when AJAX returns the values of drop down items.
The scenario is:
function 1 fires -> ajax gets items from database -> the dropdown items are filles -> my javascript function is called.
Does any of you have idea how to make a handler for such event ?
As you've tagged the question with jQuery, I'll show you a jQuery solution:
$.post("someScript.php", function(data) {
/*This callback function is executed when the AJAX call returns successfully
You would do something with your dropdown items here
and then call your next function.*/
});
The various jQuery AJAX methods (post, get, load for example) all provide a way to pass a callback as an argument. The callback is executed upon a successful response from the server. Inside that callback function you can execute whatever code you need to, to deal with data which contains the response.
If you're not using jQuery, I'll assume you already have an XMLHttpRequest object. XMLHttpRequest has a property called onreadystatechange to which you can assign a function that runs when the state changes:
xhr.onreadystatechange = function(){
if(xhr.readyState == 4) {
//This will be reached if the call returns successfully
}
}
The idea is the same as the jQuery method shown above.
Related
I am using jquery for ajax calls
All the calls are called immmediately on page load and we are getting the responses at almost the same time.
the issue is, the 3 calls are fired and I am getting the data, but the callback function is fired for the first call only.
the other two callbacks are not called, the callback is defined as a separate function,
If I just write an alert instead of calling the callback method, all the 3 alert message are coming
So the issue is when we write the callback method, do any one have any idea of the strange behaviour?
We tried to reorder the calls, the behaviour is similar, which ever is called first, its callback will be called, for the rest, it will not be called
var url = "/test1";
ajaxCall(url, testMethod1, false);
var url = "test2";
ajaxCall(url, testMethod2, false);
var url = "test3";
ajaxCall(url, testMethod3, false);
testMethod1:function(data){
console.log("first"+data);
},
testMethod2:function(data){
console.log("second"+data);
},
testMethod3:function(data){
console.log("thrid"+data);
}
ajaxCall is defined as jquery ajax, the issue is only the testMethod1 is called, the rest 2 are not called
Regards
Hari
Well the thing that immediately caught my eye is that the URL for test1 has a forward slash preceding test1. This means that you are using a valid link in only test1. The alerts will trigger because you are probably not trying to access the data returned (which would still work even though the ajax request fails), where as you are trying to access the data in the coded call back functions you have provided, which will obviously throw a NullPointerException or whatever the equivalent as the ajax call fails due to an incorrect URL. Therefore data never gets set and the code doesn't work.
I have a javascript function as:
function triggerUpload(success, error, callback) {
var options = {
type: 'post',
success: success,
error: error
};
$("input[name=file]").change(function() {
$(this).parent().ajaxSubmit(options);
});
if (callback) {
callback();
}
}
And i use it as:
triggerUpload(function() {
applyPostAjax(postUrl);
});
It works well as: When someone clicks on a Upload the triggerUpload event occurs with applyPostAjax as its parameter assigned to callback which can be kept null as its optional.
Note: These methods were coded by someone else and i can't get them clearly. I'm a newbie to javascript.
My issues is: i pass only one argument to this function. one would think that argument would get assigned to success. How/why does it get assigned to callback? What are these success, error parameters are here for?
Please explain
The parameters success and error are callback functions (same like the parameter you decided to call "callback") that gets executed when the ajaxSubmit method either successfully transmits the form data or encounters errors.
So, in your function call, you've supplied the success callback but not the error callback or callback callback. Since your function gets executed one can assume that the ajaxSubmit operation has successfully submitted the form.
One would be 100% correct to think that the argument gets assigned to success and not to callback.
Full documentation of the jQuery Forms Plugin available here: http://malsup.com/jquery/form/
and here: https://github.com/malsup/form
Specifically, the documentation of the success callback states:
success
Callback function to be invoked after the form has been
submitted. If a 'success' callback function is provided it is invoked
after the response has been returned from the server. It is passed the
following arguments:
1.) responseText or responseXML value (depending on the value of the dataType option).
2.) statusText
3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)
What this means is that the correct prototype of the success function should be:
triggerUpload(function(response,status,xhr,form) {
applyPostAjax(postUrl);
});
Though it's perfectly fine to supply a function with more or fewer parameters because javascript allows functions to be called by fewer or more arguments than exist in their formal declaration. So if you're interested in only the result of the upload function you can just do:
triggerUpload(function(response) {
applyPostAjax(postUrl);
});
Or if you don't care about the response from the server you can just call it like how you did.
As others said, all the three success, error and callback should be functions. However, they have different purpose:
success - called once the ajax submitting is finished successfully
error - called once there is some error in the ajax submitting
callback - called no matter what is happening with the submitting. I guess this is added just to confirm that the change handler is assigned to the input field.
In other words calling triggerUpload doesn't submit the form. You just attach a handler to the file input button. Once you change it, i.e. you choose a file the form is submitted and you get a response after that.
I've a javascript method defined as follows:
updtCrtEdtPage = function() {PrimeFaces.ab({source:'j_id_ev',formId:'j_id_es',process:'typeNewLOB_in lobIdForEdit j_id_ev',update:'createLOBFullPagePanel',oncomplete:function(xhr,status,args){prepareForCrtEdtFullPage();},params:arguments[0]});}
I want to execute certain method (afterComplete()) whenever this method has finished executing. (This method actually initiates an ajax request & appends the received HTML data on the DOM). So I want my afterComplete() method to be executed whenever ajax response has been received.
I cannot directly do like:
updtCrtEdtPage();
afterComplete();
as this would call the afterComplete() soon after ajax request is initiated & not completely finished executing yet.
Is there any JS/ jQuery way I could do that ?
You could pass afterComplete as a parameter so your function can call it when the ajax call is complete. Something like this...
updtCrtEdtPage = function(callback) {
PrimeFaces.ab({
source:'j_id_ev',
formId:'j_id_es',
process:'typeNewLOB_in lobIdForEdit j_id_ev',
update:'createLOBFullPagePanel',
oncomplete:function(xhr,status,args){
prepareForCrtEdtFullPage();
callback();
},
params:arguments[0]
});
}
updtCrtEdtPage(afterComplete);
Since you say you can't modify updtCrtEdtPage, but you can modify prepareForCrtEdtFullPage I'd suggest using a global variable to determine which callback function to call when the method is complete...
updtCrtEdtPageCallback = afterComplete;
and then in prepareForCrtEdtFullPage just add the last line...
updtCrtEdtPageCallback();
The first method is tidier, but the second will suffice for your particular situation.
your updtCrtEdtPage = function() has an oncomplete callback which is called when the ajax response has been received, add your afterComplete function in that callback and it will execute after the ajax request has been completed.
oncomplete:function(xhr,status,args){
prepareForCrtEdtFullPage();
afterComplete()
}
Imagine this scenario:
I have a link that fires up a JavaScript function(has an Ajax request in it).
The JavaScript function has a parameter passed by the link's onclick='jsFunction(param)'.
The JavaScript function sends the parameter value in a function inside a controller that sets the param value to a session variable.
The function in the controller will then send the new value of the session variable back to the JavaScript function's Ajax request.
When the data reached into the Ajax request, another function will be called using the data being passed.
Question:
Since I am talking about the session variable's value being passed to an Ajax request, how can I process the data came from the link to the second function in real-time? I want to post the code here but it's too verbose with the info I only need.
The current state of my code is that, I can't fetch the right/latest data. Instead, I get the previous data came from the previous link I clicked.
Is there an Ajax feature that I can only proceed to the next function if the first function is done processing the latest data?
Any help will be much appreciated.
You can use the callback to any of the jQuery AJAX methods to delay execution of another function until after the request is complete.
$.post('/some/url', somedata, function(returnData) {
// put the code you want to execute on completion here
});
or If you have already defined your function to be called after returning data, you can just write like this:
$.post('/some/url', somedata, processData);
I have 2 javascript functions, the first being a function which loads ajax content (via another function), and a second which is a callback function. They look like:
function createReply(callBack){
ajaxPage('test.html', 'next-reply');
callBack();
}
function updateNext(){
document.getElementById('next-reply').id = "reply-item";
}
createReply(updateNext);
As you can see, I am calling the createReply() function and passing it the name of the callback function, in this case updateNext()
In the createReply() function, I am calling another function which loads content via ajax. When this function is complete, the callback is supposed to be executed. The callback changes the id of the div in which the ajax content is being loaded. This is where the problem is occuring
I am getting the error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
Which is saying that it cannot change the content of the element with the id "next-reply" because it doesn't exist, and the reason it doesn't exist is because the callback function changes the id if that element. The intention is to have the callback fire after the ajax content has been loaded (ie; after the ajaxPage() function has been executed)
Can anyone see what the problem is? Is there a better way of implementing a callback function in plain javascript?
PS: no jQuery
As pointed out in the comments, this is due to the fact that AJAX calls happen asynchronously. The thread that createReply runs in continues to run before a response is returned from the server.
You'll need to re-factor ajaxPage to accept a reference to callback, and call it when the response is ready. Something like:
function createReply(callBack){
ajaxPage('test.html', 'next-reply', callBack);
}
Then, in ajaxPage:
function ajaxPage(url, id, callback){
//Do AJAX stuff
//When the response is returned:
if(callback) callback();
}
Right now you callback is executed right after the ajaxPage function. By right after I mean you do not wait for ajaxPage to return success. It is fired right after the ajax call goes out. It is very likely that it is not completed before your callback is fired.