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

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');
});
}

Related

passing data to jquery modal aside from adding parameters to url?

On click of a #dtDelete button I am opening an ajax modal in bootstrap 3. I am also passing a parameter, selected, along with it and using $_GET on the php page to retrieve it.
As the value of selected may or may not be extremely large I think I should avoid passing the value this way / using $_GET.
How the heck can I pass values other than this method? Due to the nature of opening the modal (loading it then showing it) I am stuck on any other ways.
$('#dtDelete').on('click', function () {
//open the modal with selected parameter attached
$('#modal-ajax').load('/modals/m_keystroke_delete.php?selected='+selected);
$('#modal-ajax').modal('show');
});
Pass a data object as a second param to load for it to make a POST request.
$('#dtDelete').on('click', function () {
var data = { 'propertyA': 'extremely large data' };
//open the modal with selected parameter attached
$('#modal-ajax').load(
'/modals/m_keystroke_delete.php?selected=' + selected, // url
data, // data
function(responseText, textStatus, XMLHttpRequest) { } // complete callback
);
$('#modal-ajax').modal('show');
});
You can even pass your "selected" param through the POST request and use $_POST or even $_REQUEST to retrieve the data. Also notice that the modal now shows once the request has completed.
$('#dtDelete').on('click', function () {
var data = {
'selected': selected
'largeData': '...'
};
$('#modal-ajax').load(
'/modals/m_keystroke_delete.php',
data,
function() {
// Invoke the delete-function
deleteComp();
// Show the modal
$(this).modal('show');
}
);
});

Use fancybox to allow/prevent form submission

Below is the jQuery I'm using to try and prevent/allow a form to be submitted once the user clicks the submit button. The idea will be to present a fancybox modal dialog window with the data the user entered for review. If they ,like, they click Looks Good! and the form is submitted back to the ASP MVC3 controller. If not, since the e.preventDefault method has already been called the modal window closes and they can re-enter the data.
The problem is, obviously as I have this written now, if the user is happy with the data they've entered, the whole thing will go into an infinite loop since I'm the Look's Good! button calls the method that displayed it in the first place.
Is there a way to create a "standalone" method inside the submit() function so I would have access to the event object and, if not, what would be a better way (i.e. actually works) to allow the form to submit after clicking the Look's Good! button?
//Form submit functions
$('form').submit(function (e) {
e.preventDefault();
if ($('#AccountNumber').val() != $('#doubleaccount').val()) {
alert("Please re-enter the correct account number!");
} else {
var display = "<h1>Test</h1>" +
"<input type='button' value='Looks Good!' onclick='submit()'/>" +
"<input type='button' value='Try Again...' onclick='cancel()'/>";
$.fancybox(display, {
// fancybox API options
fitToView: false,
autoScale: true,
autoDimension: true,
closeClick: true,
openEffect: 'fade',
closeEffect: 'fade',
closeBtn: true,
openSpeed: 'fast',
closeSpeed: 'fast'
});
}
});
});//End doc.ready()
function submit() {
$('form').submit();
}
function cancel() {
$.fancybox.close();
}
Since you are preventing default, then you may need to submit the form via ajax to avoid the loop. I think this would do the trick :
function submitForm(){
jQuery.ajax({
cache: false,
type: "POST",
url: "process.asp", // your controller
data: jQuery("#myForm").serialize(), // serialize form with id="myForm"
success: function(data){
jQuery.fancybox("form successfully submitted"); // confirmation message
jQuery('#myForm')[0].reset(); // clear form fields
}
});
}
jQuery(function($) {
$("#myForm").on("submit", function(e){
e.preventDefault();
if ($('#AccountNumber').val() != $('#doubleaccount').val()) {
// validation : something went wrong
alert("Please re-enter the correct account number!");
} else {
var display = "<h1>Test</h1>" +
"<input id='submit' type='button' value='Looks Good!'/>" +
"<input id='cancel' type='button' value='Try Again...'/>";
$.fancybox(display,{
// other API options
afterShow: function(){
$("#submit, #cancel").on("click", function(event){
if( $(event.target).is("#submit") ){
submitForm();
}
$.fancybox.close();
});
}
}); // fancybox
}
}); // on submit
}); // ready
Notice that I added IDs to the form as well as the buttons to submit or cancel so I can bind events to all those selectors. Also notice that I used the afterShow callback to bind the click events in my buttons inside fancybox.
Useful to read : Ajax serialize docs
NOTE : .on() requires jQuery v1.7+
EDIT : you could actually replace this line in your validation conditional
alert("Please re-enter the correct account number!");
by this one :
$.fancybox("Please re-enter the correct account number!");
so everything will look more consistent ;)

Jquery Mobile submit button not working after page refresh

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

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.

ajax - When to use $.ajax(), $('#myForm').ajaxForm, or $('#myForm').submit

Given so much different options to submit sth to the server, I feel a little confused.
Can someone help me to clear the idea when I should use which and why?
1> $.ajax()
2> $('#myForm').ajaxForm
3> ajaxSubmit
4> $('#myForm').submit
Thank you
I personally prefer creating a function such as submitForm(url,data) that way it can be reused.
Javascript:
function submitForm(t_url,t_data) {
$.ajax({
type: 'POST',
url: t_url,
data: t_data,
success: function(data) {
$('#responseArea').html(data);
}
});
}
HTML:
<form action='javascript: submitForm("whatever.php",$("#whatevervalue").val());' method='POST'> etc etc
edit try this then:
$('#yourForm').submit(function() {
var yourValues = {};
$.each($('#yourForm').serializeArray(), function(i, field) {
yourValues[field.name] = field.value;
});
submitForm('whatever.php',yourvalues);
});
Here is my understanding
$.ajax does the nice ajax way to send data to server without whole page reload and refresh. epically you want to refresh the segment on the page. But it has it's own limitation, it doesn't support file upload. so if you don't have any fileupload, this works OK.
$("#form").submit is the javascript way to submit the form and has same behaviour as the input with "submit" type, but you can do some nice js validation check before you submit, which means you can prevent the submit if client validation failed.
ajaxForm and ajaxSubmit basically are same and does the normal way form submit behaviour with some ajax response. The different between these two has been specified on their website, under FAQ section. I just quote it for some lazy people
What is the difference between ajaxForm and ajaxSubmit?
There are two main differences between these methods:
ajaxSubmit submits the form, ajaxForm does not. When you invoke ajaxSubmit it immediately serializes the form data and sends it to the server. When you invoke ajaxForm it adds the necessary event listeners to the form so that it can detect when the form is submitted by the user. When this occurs ajaxSubmit is called for you.
When using ajaxForm the submitted data will include the name and value of the submitting element (or its click coordinates if the submitting element is an image).
A bit late, but here's my contribution. In my experience, $.ajax is the preferred way to send an AJAX call, including forms, to the server. It has a plethora more options. In order to perform the validation which #vincent mentioned, I add a normal submit button to the form, then bind to $(document).on("submit", "#myForm", .... In that, I prevent the default submit action (e.preventDefault() assuming your event is e), do my validation, and then submit.
A simplified version of this would be as follows:
$(document).on("submit", "#login-form", function(e) {
e.preventDefault(); // don't actually submit
// show applicable progress indicators
$("#login-submit-wrapper").addClass("hide");
$("#login-progress-wrapper").removeClass("hide");
// simple validation of username to avoid extra server calls
if (!new RegExp(/^([A-Za-z0-9._-]){2,64}$/).test($("#login-username").val())) {
// if it is invalid, mark the input and revert submit progress bar
markInputInvalid($("#login-username"), "Invalid Username");
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
return false;
}
// additional check could go here
// i like FormData as I can submit files using it. However, a standard {} Object would work
var data = new FormData();
data.append("username", $("#login-username").val());
data.append("password", $("#login-password").val()); // just some examples
data.append("captcha", grecaptcha.getResponse());
$.ajax("handler.php", {
data: data,
processData: false, // prevent weird bugs when submitting files with FormData, optional for normal forms
contentType: false,
method: "POST"
}).done(function(response) {
// do something like redirect, display success, etc
}).fail(function(response) {
var data = JSON.parse(response.responseText); // parse server error
switch (data.error_code) { // do something based on that
case 1:
markInputInvalid($("#login-username"), data.message);
return;
break;
case 2:
markInputInvalid($("#login-password"), data.message);
return;
break;
default:
alert(data.message);
return;
break;
}
}).always(function() { // ALWAYS revert the form to old state, fail or success. .always has the benefit of running, even if .fail throws an error itself (bad JSON parse?)
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
});
});

Resources