I have defined a general ajaxComplete function to be triggered after each ajax request as follow;
$(document).on('pfAjaxComplete', function(event, xhr, options) {
doStuff();
});
Note I use pfAjaxComplete instead of ajaxComplete to work under PrimeFaces
Now, on each ajaxcomplete the 'doStuff()' function is being called. Problem is that inside the 'doStuff()' function I trigger several ajax calls to be executed based on a PrimeFaces remoteCommand
function doStuff() {
var elements = $('#wrapper').find("[id*='elements']");
if (elements !== null && elements .length > 0) {
$.each(elements , function(index) {
newAjaxCallBack([{name: 'param', value: 'val'}]);
});
}
}
My remote command
<p:remoteCommand name="newAjaxCallBack" actionListener="#{backingBean.action}" />
This is working fine, the backing bean action method is being called. Problem is the new ajax callback on 'doStuff' triggers a new ajaxOnComplete event, which makes sense of course but then it gets me on an infinite loop. Had tried to work it out but couldn't find any solution to it.
Any ideas or suggestions? Would there be a way to send a parameter on the newAjaxCallBack and then detecting it on the ajaxComplete function so as to avoid the doStuff call? Thanks!
A quick solution would be to append additional parameters to your calls on which you don't want another action to be executed.
If you choose a "paremeter" that is not used on the target page, it won't care about it.
$(document).ajaxComplete(function(event, xhr, options) {
if (options.url.indexOf("noStuff=true") != -1){
alert("Ignoring Ajax Request from noStuff");
return;
}
doStuff();
});
function doStuff(){
alert("doing stuff");
//another fake ajax request
$.ajax({
url: "http://google.de",
data: [
{name: 'param', value: 'val'},
{name: 'noStuff', value: 'true'}
]
});
}
http://jsfiddle.net/3kwhn0kx/
Finally got it working, solution was similar to #dognose one, in my case I had to use the data primefaces handled, this way;
...
$.each(elements , function(index) {
newAjaxCallBack([{name: 'dontcall', value: 'true'}]);
});
...
and then:
$(document).on('pfAjaxComplete', function(event, xhr, options) {
if (xhr.pfSettings.data.indexOf('dontcall') !== -1) {
return;
}
doStuff();
});
As you may see, I'm using the pfSettings object, which has an attribute 'data' that is basically a string with info related to the request including params, so if parameter present, don't do anything.
Related
I am stuck on this since yesterday, now I need help. I don't know how to properly 'question' this, but I think this is around the concern of ajax is asynchronous.
I am unable to complete the ajax call from my view when I call an ajax function inside an ajax postback.
$.ajax({
url: '#Url.Action("GetValidateAssignAccountName", "AccountsAssignment")?companyID=' + companyid,
type: request_method,
data: form_data
}).done(function (data) {
if (data == '') {
PromptAssign(data, post_url, request_method, form_data);
}
else {
Assign(post_url, request_method, form_data);
}
});
Assign function doesn't work/complete. I don't know how to call it, but it goes through the controller and calls the stored procedure, returns a success msg, but for some reason, the procedure did not work/save.
My problem is that, when I call PromptAssign - in which case I call a messageDialog and then call the Assign inside, right there the Assign does the job. Here is the PromptAssign function:
$("#messagedialog").dialog({
open: function () {
$(".ui-widget-overlay").css({ background: "#000000", opacity: 0.5 });
$(".ui-dialog-title").css("color", "#228B22");
//$(".message-img").attr("src", "../Content/images/success.png");
$(".message-wrapper").html(msg);
},
modal: true, height: 250, width: 500,
buttons: {
//'Ok': function () { $(this).dialog('close'); },
'Assign': function () {
Assign(post_url, request_method, form_data);
$(this).dialog('close');
},
'Close': function () { $(this).dialog('close'); }
},
create: function () {
$(this).closest(".ui-dialog")
.find(".ui-button").eq(2)
.addClass("btn btn-default");
},
title: "Confirmation",
dialogClass: "noclose"
});
Initially, the code was just the assign function which calls an sp to save a data. But we added the PromptAssign (first code block, then call a msgbox/PromptAssign, then assign) which is a validation if its existing or not, then the user can still Assign after if he still chooses to.
So when the validation returns nothing, I don't need to PromptAssign, so I just call the Assign straight away. This is not working. Anything I am missing on how to use ajax?
Just to answer the comments, there was an earlier problem like this that goes to the ajax, and then to the controller executing the stored procedure but for some reason the data isn't updated. We fixed the issue by making those ajax calls in a separate function.
For this one, I was trying to apply the same thing to no avail, I know there is nothing wrong in my way of using ajax, turns out, it was a data issue. The specific record in which I was testing is not working properly due to database validations. Still, thank you for looking at it.
I'm super confused by my code. Let me show what it looks like:
$(document).ready(function ($) {
var customer_exists = false;
$.get(window.additional_parameters.customer_exists_url, "json")
.done(function () {
customer_exists = true;
})
.always(function () {
// Don't make request to buy clickable until we know if the customer exists
$('#request-to-buy').on('click', function(e) {
request_to_buy(customer_exists);
});
});
function request_to_buy(customer_exists) {
response = can_request_to_buy();
response.done(function (response) {
if (customer_exists) {
// Actually create the request on the server
$.post(window.additional_parameters.request_to_buy_url,
{'ticket_id': window.additional_parameters.ticket_id},
"json")
.done(function (response) {
request_to_buy_success(response);
})
.fail(function () {
var message = handle_ajax_response(response);
show_ajax_message(message);
});
} else {
show_pre_stripe_popup();
}
})
.fail(function (response) {
var error_message = handle_ajax_response(response);
show_ajax_message(error_message, 'danger');
});
}
$(document).ready(), we set a variable called customer_exists. This variable guides the path of the code afterwards and is pretty important. If the $.get AJAX request is successful, it's true, otherwise it remains it default value of false. After the AJAX response, we attach a click event to "#request-to-buy." My goal here is to create a closure and pass in the value of customer_exists that was just set. This doesn't happen.
A good portion of the time ( I had it work correctly once or twice ), when I inspect request_to_buy in the debugger, I can see that customer_exists is a jQuery click event. why ??? Shouldn't it take on the value of the customer_exists from the surrounding scope of where the function was created? Can anyone explain what is going on here?
Thank you
EDIT: Here's a little more information that describes how it works sometimes...
The first time that I click '#request-to-buy', the handler is
function(e) {
request_to_buy(customer_exists);
}
This is what we would expect. e contains the click event, customer_exists retains it's value, and everything works inside request_to_buy.
Every time I click '#request-to-buy' after the first, instead of the above function being called, request_to_buy is called directly, and instead of passing in customer_exists in the first parameter, the click event is passed in instead. I hope this helps someone.
You should be able to do this without the need for the cumbersome outer var customer_exists.
For example :
$(document).ready(function ($) {
$.get(window.additional_parameters.customer_exists_url, "json").then(function () {
// Don't make request to buy clickable until we know if the customer exists
$('#request-to-buy').on('click', request_to_buy);
}, function() {
$('#request-to-buy').on('click', show_pre_stripe_popup);
});
function request_to_buy(e) {
e.preventDefault();
can_request_to_buy().then(function(response) {
// Actually create the request on the server
$.post(window.additional_parameters.request_to_buy_url, {
'ticket_id': window.additional_parameters.ticket_id
}, "json").then(request_to_buy_success, function() {
show_ajax_message(handle_ajax_response(response));
});
}).fail(function(response) {
show_ajax_message(handle_ajax_response(response), 'danger');
});
}
}
show_pre_stripe_popup will also be passed an event and you may need to do e.preventDefault(); there too.
You will need to check that the correct parameters are passed to the various error handlers. I can't verify them.
If it still doesn't work, then you must suspect other code that's not included in the question, for example the function can_request_to_buy().
var customer_exists = false;
Declare this outside of ready block.
I am making few ajax requests in my jQuery file. On success of these jQuery requests, I wrote few on click events which are not working.
This is my code
$(document).ready(function (){
$.ajax ({
type: "POST",
url: 'myServlet',
async: false,
success: function (response) {
id = parseInt(response);
setOutputEvents();
}
});
function setOutputEvents() {
for (var queryNumber = 0; queryNumber <= id; queryNumber++) {
$.ajax({
type: "POST",
url: 'myOtherServlet',
data: {queryNumber: queryNumber},
success: success,
async: false
});
var success = function (response) {
//some code here
generateTable();
}
}
}
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
});
I understand making multiple ajax requests is a bad programming practice but what could be the reason for on click events not getting triggered?
These are the onclick events which are not working.
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
I am using Google Chrome Version 39.0.2171.95 on Windows 7.
Please do let me know if any further information is necessary.
Since you use ajax to load even the initial content it seems, .class / #me html elements likely do not exist on initial page load of the DOM. As you didn't post html, i'm guessing this is the case.
Thus, you need to use a delegated event click handler to respond to it
so, you would change
$("#me").on("click", function(){
to
$(document).on("click", "#me", function(){
and so forth to link it to the parent element that does exist, the document itself.
This would work:
$(".class").on("click", function(){
alert("me is triggered");
});
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").trigger("click");
}
Some notes:
Event handler must be registered before triggering click.
Triggered click selector must match the class which has the click event registered.
Functions must be defined before the usage.
My problems seems basic, yet I have tried a lot of different ways of putting these functions on one html file to no avail. The problem is that, when the 1st function is called, the second also runs, leaving me with the results of the second function all the time. I have no idea what I am doing wrong, please help. Here is the code in question.
<script>
$(document).ready(function () { // Make sure the elements are loaded on the page
// Listen for a click event on the button
$('#buttonON').click(funct);
$('#buttonOFF').click(funct2);
});
// Now define the function
function favfunct(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "1", "caroff" : "0"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
function funct2(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "0", "caroff" : "1"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
}
</script>
You have omitted the closing brace from the function favfunct().
Please use this,
<script>
$(document).ready(function () {
function funOne(){
};
function funTwo(){
};
$('#buttonON').live('click',function(){
funOne();
});
$('#buttonOFF').live('click',function(){
funTwo();
});
});
NOte: initialize function before use and initialize them into document ready.
I'm trying to use the ajaxStop function in jquery but can't get it to fire, any ideas?
What I'm trying to do is loop through each anchor tag and then update some content inside it, from there I want to use the ajaxstop event to fire a script to reorganize the anchors based on the updates
Thanks for any help
jQuery(document).ready(function($) {
function updateUsers() {
$(".twitch_user").each(function(index, user) {
$.ajax({ url: "https://api.twitch.tv/kraken/streams/" + $(user).attr("id") + "?callback=?", success: function(d) {
if(d.stream) {
$(user).addClass("online");
$(user).removeClass("offline");
$(user).children(".viewers").text(d.stream.viewers + " viewers");
} else {
$(user).addClass("offline");
$(user).removeClass("online");
$(user).children(".viewers").text("0 viewers");
}
console.log(d);
}, dataType: "json"});
});
}
//$(document).ajaxStart(function() {
// console.log("Event fired!");
// updateUsers().delay(2000);
//})
$(document).ajaxStop(function() {
console.log("Event fired!");
// updateUsers().delay(2000);
});
updateUsers();
});
Apparently the global handlers are turned off when doing JSONP requests, as explained in this ticket:
JSONP requests are not guaranteed to complete (because errors are not caught). jQuery 1.5 forces the global option to false in that case so that the internal ajax request counter is guaranteed to get back to zero at one point or another.
I'm not sure if JSONP is your intention or not, but the ?callback=? on the end of the URL makes jQuery handle it as such.
The solution was to set the following:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});