jQuery how to manage HTML form action attribute executing - php

I need to validate a HTML form before executing the action attribute. But it gives me a hard time.
Please see the comment in the else statement, and the comment after returning false for an explanation of this issue
$(document).ready(function(){
$("#ajax-payment-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
alert("success");
} else {
event.preventDefault(); // I have tried with or without this method
alert("fail");
}
}
});
return false; // when return false, the action will not execute. If false is removed the action will execute, even if event.precentDefault(); is called in the else statement.**
});
});
Thanks for your time,
Troels

Your ajax call is asynchronous. This means that this function is executed, and it doesn't wait for a response from the function before it proceeds forward. This means that return false; will always fire before the result of the ajax function returns to you. Given your current circumstances, the easiest thing to do is call this.submit() from within the success function, but always return false; under the default scenario. This will avoid recursion, and also the asynchronous call won't be problematic anymore.
$(document).ready(function(){
$("#ajax-payment-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this, //needed to tell the ajax function that "this" belongs to the form, not the ajax call.
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
alert("success");
this.submit(); //it's magic, john.
} else {
//no reason to prevent the default, as the form will automatically return false anyway.
alert("fail");
}
}
});
return false; //just leave this right here.
});
});

The issue is two fold: event is not declared in your function call, and that you are not submitting the form upon the success funtion. The logic of your submit event should be as follow:
Listen to submit event on the <form> element.
Prevent default form actions first, using e.preventDefault()
Make AJAX call. Depending on the outcome of the returned data, determine whether to proceed with submitting the form. I strongly suggest not using the deprecated jqXHR.success function, but the deferred functions jqXHR.done() or jqXHR.fail().
Also, you can always use console.log() to check your script, instead of relying on alert() which blocks downstream code execution. Here's the code:
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this // So that you can use $(this) later
}).done(function(msg) {
// If a response is received from your server
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
} else {
console.log('Validation failed, will not do anything more');
}
}).fail(function() {
// Catch ajax errors here
console.log('AJAX error');
});
});
});

Related

Inline ajax's response fails in checking condition even though the condition is true

I am using an inline jquery ajax to delete a list one by one. When giving an action to delete a list, the ajax will send some post data and the response is json encoded. Upon successful response, a pop up box will open in the first ajax success field asking for the username and password. Then an inline ajax will execute there, sending the pop up box's values along with the response from first ajax. I have given a condition in the inline ajax success field to validate the response for the second posted values. The response is coming true but the condition fails, i don't know why. Please refer the code...
$('.deleteButton').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: 'phpPage.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize() + "&del=del",
success: function (d) {
$(".popupContainer").show();
var text = "Do you really want to delete the report dated:";
$('#info').text(text);
$('#delForm').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: 'delRept.php',
type: 'POST',
data: $(this).serialize() + "&vtime=" + d.vtime + "&vdate=" + d.vdate + "&delbox=delbox",
success: function (data) {
if (data == 'string') {
$('#rrr').append("True : Delete it");
} else {
$('#rrr').append(data);
}
}
});
});
return false;
}
});
});
Here it will execute the else condition even if the response is true. Please help me to find the mistake in the coding...
Thanks

Send data from Javascript to PHP and use PHP's response as variable in JS

I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3

Identifying what is returned when submitting a form using jquery

Is it possible to identify what a page returns when using jquery? I'm submitting a form here using jquery like this:
$("#sform").submit(function() {
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "user_verify.php",
success: function(data) {
$("#form_msg").html(data);
}
});
return false;
});
​
The user_verify.php page does its usual verification work, and returns error messages or on success adds a user to the db. If its errors its a bunch of error messages or on success its usually "You have successfully signed up". Can I somehow identify using jquery if its errors messages its returning or the success message. So that way if its errors I can use that data in the form, or if its success, I could close the form and display a success message.
Yes, it's this:
success: function(data) {
$("#form_msg").html(data);
}
You can manipulate data in any way you want. You can return a JSON (use dataType) encoded string from server side and process data in the success function
success: function(data) {
if(data->success == 'ok'){
// hide the form, show another hidden div.
}
}
so user_verify.php should print for example:
// .... queries
$dataReturn = array();
$dataReturn['success'] = 'ok';
$dataReturn['additional'] = 'test';
echo json_encode($dataReturn);
die; // to prevent any other prints.
You can make you php return 0 if error so you do something like this inside
success: function(data) {
if(data==0){
//do error procedure
}else{
//do success procedure
}
}
Hope this helps
You can do and something like this:
$.ajax({
type:"POST", //php method
url:'process.php',//where to send data...
cache:'false',//IE FIX
data: data, //what will data contain
//check is data sent successfuly to process.php
//success:function(response){
//alert(response)
//}
success: function(){ //on success do something...
$('.success').delay(2000).fadeIn(1000);
//alert('THX for your mail!');
} //end sucess
}).error(function(){ //if sucess FAILS!! put .error After $.ajax. EXAMPLE :$.ajax({}).error(function(){};
alert('An error occured!!');
$('.thx').hide();
});
//return false prevent Redirection
return false;
});
You can checke the "data" parameter in "success" callback function.
I noticed that there is a problem in your code. Look at this line :
data: $(this).serialize(),
Inside $.ajax jquery method, "this" is bind to the global window object and not $('#sform')

How to check whether an ajax request has allready been sent with Jquery?

I am using an Ajax request to post a form with Jquery.
$.ajax(
{
type: "POST",
url: "login.php",
data: $("#signin").serialize(),
dataType: "json",
cache: false,
success: function(data, textStatus) {
if (data.redirect) {
window.location.replace(data.redirect);
}
else {
$('#some').fadeOut(200);
$('#some2').fadeIn(200);
$("#some3").html(data.form);
$("#some").delay(2000).fadeOut(200);
$('#some2').delay(2800).fadeIn(300);
}
}
});
Now the ajax request will take place as soon as you click on a button "Login". The problem now is that if you press the button more than once the else case will be executed several times which will cause #some, #some2 and #some3 to fade out and in several times. So how could I check whether the request has allready been sent (without having to write something into my db)?
From here:
You can use .one() method and set it again in ajax callback.
function doAjax(){
// Your Ajax call.
$.ajax({..., complete: function() {
// Ajax call done, re-enabling the button/link
$("#buttonId").one('click', doAjax);
}, ...});
}
$("#buttonId").one('click', doAjax);
Make boolean flag, say, login_in_process, on login check this flag in true value. And check this flag on every click if it true then make empty return. In success and error callbacks set it in false state.
You can use a boolean value to record whether or not it has been clicked:
var loginClicked = false;
$('input_button_element').click(function(){
if (!loginClicked) {
loginClicked = true;
// your js here - you may want to add some visual feedback to the user also
}
});
You will have to store a boolean in a global scope, e.g. one stored on the window object:
if (!window.isClicked) {
window.isClicked = true;
...Do your ajax call here
}
Remember to ALWAYS restore the value of window.isClicked, not only in the success callback of ajax():
var jqxhr = $.ajax( ... )
.done(function() { })
.fail(function() { })
.always(function() { window.isClicked = false });
you can make a global var
var loginClick = false;
Inside your method you first check that value
if (!loginClick) {
loginClick = true;
//your ajax code;
}

JQuery .ajax() on username validation

I was trying to validate username whether exist or not with the following code. But it somehow don't work to prevent the existing username.
**NOTE: checkusr2.php is a simple php to check wheter the username in database.
function verifyUser() {
var usr = $("#username").val();
$.ajax( {
type: "POST",
url: "checkusr2.php",
data: "username="+ usr,
success: function(msg) {
$("#txtHint").ajaxComplete(function(event, request, settings){
FormErrors = false;
if(msg == 'OK') {
FormErrors = true;
$('#formElem').data('username',FormErrors);
} else {
$('#formElem').data('username',FormErrors);
}
});
}
});
}
/** calling the function to check. **/
verifyUser();
if($('#formElem').data('username')){
alert('Username exist, please try another username.');
return false;
}
Use an http proxy like Charles, Fiddler, WireShark, etc... to view the ajax request you are sending and verify that the response is what you expect.
For one thing, you are making an asynchronous call (the A in Ajax) to get the response for whether the username exists. The check, immediately after the verifyUser call is being called as soon as you call the verifyUser and the the request to checkusr2.php may or may not have actually returned by then.
I have also never seen the ajaxComplete set inside of the success handler. I think you may want to change it like this:
function verifyUser() {
var usr = $("#username").val();
$.ajax( {
type: "POST",
url: "checkusr2.php",
data: "username="+ usr,
success: function(msg) {
if(msg != 'OK') {
alert('Username exists, please try another username.');
$("#username").val("");
}
};
});
}
Your problem is in trying to use verifyUser synchronously. The code seems fairly sound, the problem is that $.ajax executes asynchronously using XMLHTTPRequest. This means that your code immediately following the call to verifyUser cannot depend on the side effect of its completion.
What you need to do is run the verifyUser callback earlier (like, say, when the user un-focuses the username field), so that when it comes time to submit you've already got the result.
For example:
$('#username').blur(function() { verifyUser() });
A further change would be instead of preventing submit, you can make verifyUser show a div with a message next to the field when the username is invalid. You'd make these changes to your handler:
if(msg == 'OK') {
FormErrors = true;
$('#username_invalid').show();
} else {
$('#username_invalid').hide();
}
Then you could show the user the username cannot be chosen immediately, without wasting their time submitting it.
Try this
$("#txtHint").ajaxComplete(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html' && xhr.responseHTML=="Ok") {
FormErrors = true;
$('#formElem').data('username',FormErrors);
} else {
$('#formElem').data('username',FormErrors);
}
})
Thanks for bringing up this .ajaxComplete() that I didn't know about. I think it will be of great help for me in the future.
But anyway I don't think it's what you want to use in this specific case:
function verifyUser() {
var usr = $("#username").val();
$.ajax( {
type: "POST",
url: "checkusr2.php",
data: {'username':usr},
success: function(msg) {
if ( msg != 'OK' ) {
alert('Username exist, please try another username.');
return false;
}
});
});
}
The function that you want to execute after the Ajax call must be passed as a callback of the Ajax function, otherwise, and even if you put it after your Ajax function, it will execute before the server's response.

Categories