Execute Javascript after ajax response has been rendered - javascript

I want to execute a piece of javascript after the ajax response has been rendered. The javascript function is being generated dynamically during the ajax request, and is in the ajax response. 'complete' and 'success' events to not do the job. I inspected the ajax request in Firebug console and response hasn't been rendered when the complete callback executes.
Does not work:
function reloadForm() {
jQuery.ajax({
url: "<generate_form_url>",
type: "GET",
complete: custom_function_with_js_in_response()
});
};
ajaxComplete does the job, but it executes for all the ajax calls on the page. I want to avoid that. Is there a possible solution?
$('#link_form').ajaxComplete(function() {
custom_function_with_js_in_response();
});

you can also use $.ajax(..).done( do_things_here() );
$(document).ready(function() {
$('#obj').click(function() {
$.ajax({
url: "<url>"
}).done(function() {
do_something_here();
});
});
});
or is there another way
$(document).ready(function() {
$('#obj').click(function() {
$.ajax({
url: "<url>",
success: function(data){
do_something_with(data);
}
})
});
});
Please, utilize this engine for share your problem and try solutions. Its very efficient.
http://jsfiddle.net/qTDAv/7/ (PS: this contains a sample to try)
Hope to help

Checking (and deferring call if needed) and executing the existence of the callback function might work:
// undefine the function before the AJAX call
// replace myFunc with the name of the function to be executed on complete()
myFunc = null;
$.ajax({
...
complete: function() {
runCompleteCallback(myFunc);
},
...
});
function runCompleteCallback(_func) {
if(typeof _func == 'function') {
return _func();
}
setTimeout(function() {
runCompleteCallback(_func);
}, 100);
}

Can't help a lot without code. As an general example from JQuery ajax complete page
$('.log').ajaxComplete(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).text('Triggered ajaxComplete handler. The result is ' +
xhr.responseHTML);
}
});
In ajaxComplete, you can put decisions to filter the URL for which you want to write code.

Try to specify function name without () in ajax options:
function reloadForm() {
jQuery.ajax({
url: "<generate_form_url>",
type: "GET",
complete: custom_function_with_js_in_response
});
};

Related

Separation of concerns and JQuery AJAX callbacks

I am working on a web application for debtor management and I am refactoring the code and try to adhere to the principle of separation of concerns. But the async nature of AJAX is giving me headaches.
From a jQuery dialog the user can set a flag for a debtor which is then stored in a database. If that succeeds, the dialog shows a notification. Until now I handled everything inside the jQuery Ajax success callback function: validating input, doing the ajax request and updating the content of the dialog.
Of course this lead to spaghetti code.
Thus I created a class AjaxHandler with a static method for setting the flag, which is invoked by the dialog. I thought that the dialog could update itself according the the return value of the AjaxHandler but I did not have the asynchronity in mind.
The following question was helpful in tackling the return values.
How do I return the response from an asynchronous call?
But how can I update the dialog without violating the SoC principle?
EDIT
$("#button").on("click", function() {
var returnValue = AjaxHandler.setFlag();
if(returnValue) { $("#div").html("Flag set"); }
else { $('#div").html("Error setting flag");
});
class AjaxHandler {
static setFlag(){
$.ajax({
type: "POST",
url: "ajax/set_flag.php",
success: function(returndata){
return returndata; //I know this does not work because of
//ASYNC,but that is not the main point.
}
}
})
There is many ways to handle async responses, but the jQuery way is slightly different, so when you are already using jQuery, handle it this way:
$('#button').on('click', AjaxHandler.setFlag)
class AjaxHandler {
static setFlag () {
this.loading = true
this
.asyncReq('ajax/set_flag.php')
.done(function () {
$('#div').html('Flag set')
})
.fail(function (err) {
$('#div').html('Error setting flag. Reason: ' + err)
})
.always(function () {
this.loading = false
})
}
asyncReq (url) {
return $.ajax({
type: 'POST',
url: url
})
}
})
Consider using events perhaps here?
$("#button").on("click", function() {
$('body').trigger('getdata', ["", $('#div')]);
});
$('body').on('getdata', function(event, datasent, myelement) {
var attach = event.delegateTarget;// the body here
var getAjax = $.ajax({
type: "POST",
url: "ajax/set_flag.php",
data: datasent // in case you need to send something
})
.done(function(data) {
$(attach).trigger('gotdata', [data, myelement]);
});
getAjax.fail(function() {});
})
.on('gotdata', function(event, datathing, myelement) {
myelement.html(!!datathing ? "Flag set", "Error setting flag");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Note that inside those event handlers you could also call some function, pass a namespace for the function, basically do it as you please for your design.

Continue after ajax complete without using the callback

Trying to postpone further processing of script until ajax call is complete without using the callback. Trying something like this, but it locks. How do I do this without locking?
var loaded=false;
$.get(url,function(d){loaded=true;});
while(!loaded) //<--locks here
setTimeout(void(0),100);
//continue script after ajax call is complete
Have you tried with promises?
var jqxhr = $.get( url, function() {
alert( "success" );
})
.done(function() {
void(0);
})
.fail(function() {
void(0);
})
.always(function() {
alert( "finished" );
});
Try this
var loaded=false;
$.ajax({
url : 'your url',
type : 'GET',
async : false, // You need this
complete: function(data) {
loaded=true;
},
});
while(!loaded) //<--locks here
setTimeout(void(0),100);
If you work with jQuery, deferred objects are the way to go. They implement a robust and easy methodology.
However, if you want your script to work, try this:
var loaded = false;
function myfunc() {
if (loaded) {
clearInterval(timeout);
doSomethingAfter();
}
}
var timeout = setInterval(myfunc, 100);
$.get(url,function(d){loaded=true;});

Can't access object made by ajax call

I have this ajax request:
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
});
as you can see it makes new row in #table. But this new objects made by ajax are not accessible from next functions. Result from ajax is not a regullar part of DOM, or what is the reason for this strange behavior?
$('#uid').on('click', function () {
alert('ok');
});
Use event delegation:
$(document).on('click','#uid', function () {
alert('ok');
});
Note that ajax calls are asynchronous. So whatever you do with the data you need to do it in a callback within the success function (that is the callback which is called when the ajax call returns successfully).
Jquery on doesn't work like that. Use have to give a parent which not loaded by ajax, and the specify ajax load element like this
$('#table').on('click','#uid' ,function () {
// what ever code you like
});
Is simple and complex at the same time. Simple to solve but complex if you are getting started with javascript...
Your event handler - onclick is being fired and bound to an object that doesnt yet exist.
So when you append the object to the #table, you need to set up your click handler as the object now exists.
So in your success part of the ajax return add the click handler event there.
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
Or how about you make it dynamic and create a function to do it for you.
function bindClick(id) {
$('#' + id).click(function() {
//Do stuff here
console.log('I made it here' + id);
});
}
Then:
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
bindClick(uid);
});
}
This is a super contrived example but you get the idea you just need to make the rest of it dynamic as well. for example some name and counter generated id number: id1, id2, id3...
Try it like this, add this $('#uid').on('click', function () { into the success
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
});

Ajax recursive function work strange

Hello guys here's my code:
var ajax={
chiamata:function(target,url,opzioni){
if (!tools.array_key_exists('caricamento',opzioni)){
opzioni['caricamento']=1;
}
var dati=url.split('?');
$.ajax({
type: opzioni['type'],
url: url,
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
data: dati[1],
dataType: "html",
success: function(msg){
if (opzioni['caricamento']!=0){
ajax.printLoading();
}
$(target).html(msg);
},
error: function(){
alert("Chiamata fallita!");
}
})
},
printLoading:function(){
var body="#colonnaDX";
$(body).ajaxStart(function(){
$(body).append('<div id="loading"><img src="graphic/IMAGE/spinner.gif"/>Loading...</div>');
})
.ajaxStop(function(){
$('#loading').remove();
});
}
},
//Recursive function
var object={
checkAzione:function(target,url,opzioni,interval){
if (!interval)
interval=60000;
ajax.chiamata(target,url,opzioni);
setTimeout(function() {
this.checkAzione(target,url,opzioni,interval);
}, interval);
}
}
$(document).ready(function(){
object.checkAzione(
'#colonnaDX',
'someactions.php',{
'caricamento':0
},
10000
);
})
I'll try to explain the problem as better as i can, When the document is ready, the function "checkAzione" starts and it makes some stuff like DB calls etc, this kinds of ajax calls don't need any visual loading like spinner etc so in the array "opzioni" i set a flag 'caricamento':0 (same of 'loading':0) just check my ajax object to see what i mean, it works until i make some ajax calls that using 'caricamento':1, from that moment every ajax calls in my recursive function makes the "printLoading"... Any tips????
ajaxStart and ajaxStop are global, you add them to the body. You probably shouldn't use ajaxStart/Stop in this case, just add the functionality to your ajax listeners (success and error).

jQuery document ready after ajax request

I'm having problems with updating elements that are not ready after an ajax request.
If I run my myFunction() function on page load like so:
$(function() {
myFunction();
}
I have no problems at all. But if I then use something like
$.ajax({
url: this.href,
dataType: "script",
complete: function(xhr, status) {
myFunction();
}
});
which returns $(".myElement").replaceWith("htmlHere"). The elements are simply not ready when the complete event fires. If I set a delay in there it works fine again.
Is there any other event that gets fired other than 'complete' when the DOM is ready?
Update:
Here's the actual code:
$(function() {
$("a.remote").live("click", function(e) {
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
myFunction();
}
});
e.preventDefault();
return false;
});
myFunction();
});
function myFunction() {
// Modify the dom in here
}
The missing ); was just a typo on my part.
Ive tried using success now instead of complete and it doesn't appear to make any difference.
I have set up a jsfiddle based on your code, and it seems to be working.
This is the current code:
$(function() {
$("a.remote").live("click", function(e) {
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
myFunction();
}
});
e.preventDefault();
return false;
});
});
function myFunction() {
$("span").replaceWith("<p>test</p>");
}
And it replaces span tag with a paragraph. Please check it and compare with your code. If it is the same, then your problem somewhere other than this function (maybe in myFunction?).
You can use $(document).ready(function() { ... }); to wrap up anything you want fired when the DOM has loaded. Your ajax request could be placed inside the document.ready if you want this to wait until the dom has loaded.
If you want to wait until the ajax has loaded its resource then you should use ajax.success rather than complete.
Just change complete: to success: in your $.ajax() call:
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
//make your DOM changes here
myFunction();
}
});
The success function will run once the AJAX request receives a successful response. So make your DOM changes within that function, and then run myFunction().
Edit
You seem to be trying to make the DOM changes using your myFunction(). But if you don't first insert the HTML received in the AJAX response into the DOM, then there will be nothing for myFunction() to modify. If this is indeed what's happening, then you have two options:
Insert the response HTML into the DOM, then call myFunction() (and all of this should happen within the success callback function).
Pass the AJAX response to myFunction() as an argument, so that myFunction() can handle the DOM insertion and then do the necessary modification.
There is a event that triggers after every ajax call. It is called ajaxComplete.
$( document ).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
});
So you can
function Init(){
// stuff here
}
$(document).ready(function()
Init();
});
$(document).ajaxComplete(function()
Init();
});
You are missing the closing parenthesis of the document ready wrapper function.
$(function() {
myFunction();
});
Note the }); at the end.
$(function() {
myFunction();
}
should be
$(document).ready(function() {
myFunction();
});
Or incase you want the ajax to run on load. Do
$(document).ready(function() {
$.ajax();
});

Categories