Jquery Mobile submit button not working after page refresh - ajax

I have a single page mark-up with popup divs that contain forms that the user can use to update his/her account information. After form submission the popup closes and the page refreshes showing the updated information that is located within a li (this seems to be working). The problem is, if the user goes back and tries to update again the button within the popup is not submitting.
Thanks in advance for any suggestions!!!
Javascript
$('#updateadmin').click(function() {
var admin = $('#adminform').serializeArray();
/*alert(admin);*/
$.ajax({
type: "POST",
url: 'adminupdate.php',
data: admin,
success: function(data) {
if(data=="success") {
$('#admindiv').popup('close');
$.mobile.changePage('companyinfo.php', {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true,
changeHash: false
});
} else {
$('#adminupdatestatus').html(data).css({color: "red"}).fadeIn(1000);
}
}
});
return false;
});

It sounds like the #updateadmin link/button is located on the page that gets reloaded, if this is the case then you should delegate your event handler so it affects matching elements in the DOM for all time, not just when the code runs.
You would change this:
$('#updateadmin').click(function() {
to this:
$(document).on("click", "#updateadmin", function() {
This works because you're now attaching the event handler to the document element which always exists. When events reach the document element they are checked to see if the element on which they originally fired matches the selector we put as the second argument for .on().
Documentation for .on(): http://api.jquery.com/on

Related

ajax form submission - skip url processing and go directly to success function?

Haven't come across this before with ajax. On click of a button I am posting a form with ajax. In the successful return function I am opening up a modal window in bootstrap 3 with a single parameter attached from the previous form submission.
I am using the modal as a confirmation window to confirm a user deletion. I am using ajax again then in the modal to do the actual deletion of the user in the db and returning success or fail.
Since all the operations are being processed in the actual modal's ajax (confirm the username exists then perform the delete operations)... is there a way I can skip the initial form processing? In this example p_delete_user.php' really does absolutely nothing other than allow me to return and attach the username parameter to the modal I open.
Can I skip this step somehow and go straight to my success calls with the attached parameter value. I have no need to check if the param is valid or not in this step as the validation occurs in the ajax of the modal that is opened.
my ajax:
// delete user account
var deleteAccount = function() {
$('#delete-user').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: 'post',
url: '/spc_admin/process/p_delete_user.php',
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success) {
// user account exists so show confirmation modal
$('#modal-ajax').load('/spc_admin/modals/m_delete_user.php?username='+response.username+'');
$('#modal-ajax').modal('show');
}
else
{
// show error toast
toastr.error('An error has occurred. Please contact support.', 'Error');
}
});
});
}
Use Javascript to get the username from the form, and put that directly into the modal:
var deleteAccount = function() {
$('#delete-user').on('click', function () {
var username = $(this).closest('form').find("input[name=username]").val();
$('#modal-ajax').load('/spc_admin/modals/m_delete_user.php?username='+encodeURIComponent(username));
$('#modal-ajax').modal('show');
});
}

Event Object is holding previous event properties in Full Calendar

I've got a problem with FullCalendar and I was looking for solution without any success.
I use eventClick to open overlay form with data of current event. Everything works great until I change my mind and don't want to edit this event but another one. And that causes ajax send request 2 times, once for opened event (which was ready to edit but form was not submitted) and once for event which was really edited and submitted.
$('#sc-calendar').fullCalendar({
eventClick: function(event) {
//opening overlay form window
$('#submit-event-update').bind('click',function() { //click submit
$.ajax({
type: "GET",
url: "event_update",
data: "id="+event.id+"&title="+event.title+"&start="+event.start+"&end="+event.end,
cache: false,
success: function() {
$('#submit-event-update').unbind();
$('#sc-calendar').fullCalendar('updateEvent',event);
}
});
});
}
});
This is starting to be my nightmare. Please help!
It seems to me like there is a problem with the onclick event listener for #submit-event-update.
You should modify your code in this way:
$('#sc-calendar').fullCalendar({
eventClick: function(event) {
//opening overlay form window
//Assign the event id of this event to the global variable event_id
event_id = event.id;
}
});
$('#submit-event-update').bind('click',function() { //click submit
$.ajax({
type: "GET",
url: "event_update",
data: "id=" + event_id + ..., //Note how event.id is not used anymore
cache: false,
success: function() {
$('#sc-calendar').fullCalendar('updateEvent',event);
}
});
});
I changed it so that you bind the onclick event handler to the button just once as opposed to every time an event is clicked. I also assign a variable event_id that holds the value of the current event's id.
Now, for an explanation. You said:
Everything works great until I change my mind and don't want to edit
this event but another one.
What happens when you click on an event?
You bind the onclick event to the #submit-event-update. Now if you do click the button, then you will go into the success() callback of your AJAX call and then unbind the button. But what if you change your mind and don't click the submit button? Now, you have one onclick listener with the old data already tied to the button. When you pick another event, you have two event listeners tied to the same button and hence, an AJAX request is sent two times.
It might be worth reading up on how JavaScript handles event binding here.

Jquery load in Dialog is repeated exponentially

I have a really annoying issue with jQuery and/or the jQuery UI Dialog Box.
After clicking on a special link a modal dialog will pop up with some loaded content (ajax) and inside this loaded content are new links/buttons that load their url inside the same div Box, so the dialog still is loaded, but with new content then. The Problem is, that if you link on that link (inside a fresh loaded dialog box and on a recently reloaded website) it works as it should, but with the second click it loads the url twice, with the third it loads 4 times ... It growing exponentially with every new link loaded inside the dialog. I testet this with a counter stored inside $_SESSION.
This is the Javascript Code:
var somedialog = $('<div></div>').dialog({
autoOpen: false,
resizable: false,
modal: true,
/*show: 'fade',
hide: 'puff',*/
closeOnEscape: true,
close: function(){
}
});
function openInDialog(url, title, width, height)
{
somedialog.empty();
somedialog.dialog("option", "width", width);
somedialog.dialog("option", "height", height);
somedialog.dialog("option", "title", title);
somedialog.load(url,{},function (responseText, textStatus, XMLHttpRequest)
{
somedialog.dialog('open');
}
);
//somedialog.load(url,{},function (responseText, textStatus, XMLHttpRequest){
// dialogdiv.somedialog('open');
//});
}
$('a.ajaxBuyItemDialog').on('click',function(){
openInDialog(this.href, this.title, 400, 300);
//prevent the browser to follow the link
return false;
});
There seemed to bee other people with this issue, but that was not a very effective discussion: https://stackoverflow.com/questions/6471360/jquery-load-after-load-repeated-results-problem
Thanks for your help!
EDIT:
This is part of the code which is located in the loaded script:
$("#_BUYITEM_FORM").live('submit', function(){
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response){ // on success..
$("#_BUYITEM_CONTENT").html('<p class="AjaxLoaderImg"><span>Einen Moment bitte...</span></p>');
$("#_BUYITEM_CONTENT").html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
Without it I can't get it to refresh the dialog box with new content.
It seems that your javascript code is replicated in every $('a.ajaxBuyItemDialog') destination page clicked. Adding that script to the dialog again at every click causes event to be triggered more than once.
If you reload the script numerous times it will add a new submit handler to form each time since you are using live().
live() will delegate the handler to the document and thus should either only be called once or you need to call die() before script loads each time.
if you were to get rid of using live() you could move the submit handler to the success callback of load() and use submit() rather than live(). If the original form is replaced...the original submit() event handler will also be gone
"Dirty" solution
function watchBuyItemForm(){
$("#_BUYITEM_FORM").submit(function(){
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response){ // on success..
somedialog.html(ajaxLoader);
somedialog.html(response); // update the DIV
watchBuyItemForm();
}
});
return false; // cancel original event to prevent form submitting
});
}

JQM (jQueryMobile) problem with AJAX content listview('refresh') not working

This is a mock of what I'm doing:
function loadPage(pn) {
$('#'+pn).live('pagecreate',function(event, ui){
$('#'+pn+'-submit').click( function() {
$.mobile.changePage({
url: 'page.php?parm=value',
type: 'post',
data: $('form#'+pn+'_form')
},'slide',false,false);
loadAjaxPages(pn);
});
});
function loadAjaxPages(page) {
// this returns the page I want, all is working
$.ajax({
url: 'page.php?parm=value',
type: 'POST',
error : function (){ document.title='error'; },
success: function (data) {
$('#display_'+page+'_page').html(data); // removed .page(), causing page to transition, but if I use .page() I can see the desired listview
}
});
}
in the ajax call return if I add the .page() (which worked in the past but I had it out side of the page function, changing the logic on how I load pages to save on loading times), make the page transition to the next page but I can see the listview is styled the way I want:
$('#display_'+page+'_page').html(data).page();
Removing .page() fixes the transition error but now the page does not style. I have tried listview('refresh') and even listview('refresh',true) but no luck.
Any thoughts on how I can get the listview to refresh?
Solution:
$.ajax({
url: 'page.php?parm=value',
type: 'POST',
error : function (){ document.title='error'; },
success: function (data) {
$('#display_'+page+'_page').html(data);
$("div#name ul").listview(); // add div wrapper w/ name attr to use the refresh
}
});
Be sure to call .listview on the ul element
If it didn't style earlier, you just call .listview(), bot the refresh function. If your firebug setup is correct, you should have seen an error message telling you that.
I didn't have time to get down to creating some code before you posted your fix, but here's a little recommendation from me:
if(data !== null){ $('#display_'+page+'_page').html(data).find("ul").listview() }
This is a bit nicer than a new global selector. Also - you don't need the div and you can provide a detailed selector if you have multiple ULs.
caution: the above code requires data !== null. If it's null - it will throw an error.
If you add items to a listview, you'll need to call the refresh() method on it to update the styles and create any nested lists that are added. For example:
$('#mylist').listview('refresh');
Note that the refresh() method only affects new nodes appended to a list. This is done for performance reasons. Any list items already enhanced will be ignored by the refresh process. This means that if you change the contents or attributes on an already enhanced list item, these won't be reflected. If you want a list item to be updated, replace it with fresh markup before calling refresh.
more info here.

jquery ajax post - not being fired first time

I'm trying to do an ajax post after a button is clicked, and it works in firefox but not in IE the first time the page is loaded. It does work if I refresh the page and try again second time - but not first time and this is crucial.
I've scanned over various web pages - could it be anything to do with the listener? (I've just seen this mentioned mentiond somewhere) Is there something not set correctly to do with ajax and posting when page first loads?
$(document).ready(function() {
$('#btnCont').bind('click',function () {
var itm = $("#txtItm").val();
var qty = $("#txtQty").val();
var msg = $("#txtMessage").val();
var op_id = $("#txtOp_id").val();
//if i alert these values out they alert out no prob
alert(itm+'-'+qty+'-'+msg+'-'+op_id);
$.ajax({
type: "POST",
url: "do_request.php?msg="+msg+"&itm="+itm+"&qty="+qty+"&op_id="+op_id,
success: function (msg) {
document.getElementById('div_main').style.display='none';
document.getElementById('div_success').style.display='block';
var row_id = document.getElementById('txtRow').value;
document.getElementById('row'+row_id).style.backgroundColor='#b4e8aa';
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error submitting request.');
}
});
});
I would start debugging the click event. I.e. if you try to put .bind into a a href tag, the tag itself has a click event that may act on an unwanted way. There exist a command that are named something like event.preventDefaults() that avoids the standard feature of click. After All, you try to manipulate the DOM last of all actions (document.load).
$('#btnCont').bind('click',function () { .. }
I would also try to debug the same functionality with adding onClientClick to the tag instead of adding bind to the document load.
I hope that bring some light.

Resources