jQuery AJAX not returning false - javascript

I want my program below to return false if the employee ID exists. My PHP file echoes true if the employee ID exists and it is returned to the AJAX function.
$.post("connect_ajax_php.php",
{type: "checkId", val: val, field: "emp_id", table: "employee"})
.done(function(data, succ){
data = $.trim(data);
if( succ =="success" && data=="true" ){
$( errContId ).html( val+" already exist" );
$( id ).css( {"border":"1px solid red"} );
$('#'+sucImg).html("<img src='images/background/error.png'>");
return false;
}else{
$( errContId ).html("");
$( id ).css( {"border":"1px solid #ccc"} );
$('#'+sucImg).html("<img src='images/background/success.png'>");
}
});

If you are using the ajax call as a validation step you will manually submit the form in the ajax callback. Then move the return false to the click handler rather than call it from the ajax response handler.
<form id="myform" action="/url" method="post">
...
<button id="submitbtn" type="submit">Submit</button>
</form>
$("#submitbtn").on("click", function(event) {
$.ajax({
url: "connect_ajax_php.php",
method: "post",
data: {type: "checkId", val: val, field: "emp_id", table: "employee"}
})
.done(function(result) {
if (result == "true") {
// id exists
}
else {
$("#myform").submit();
}
});
return false; // prevent standard form submission
});

Related

Ajax serialize form - PHP can't get individual input data

I have a JQuery UI dialog that is used for making a backup of a file. It contains an input box so users can add a short description that will become part for the name of the backup file. So if the user enters "blue", the backup file name will be: file_blue_2020-08-08-11:10:23.
The form name is: bckup
In my Ajax code, I'm using var frm = $('form[name="bckup"]').serialize(); for the form.
The name of the input field is: dscrb
As you can see in my PHP code, I'm trying to get the value of dscrb but it does not work. The resulting file name is: file_2020-08-08-11:10:23. However, if I change the PHP code to use $_POST["frm"] instead of $_POST["dscrb"], the resulting file name is: file_dscrb=blue_2020-08-08-11:10:23
So this tells us that the data is being posted to the PHP page.
Why then does $_POST["dscrb"] not work?
HTML:
<div id="dialog-backup" style="display: none;" title="Blah?">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0px 12px 22px 0px;"></span>Blaha.</p>
<form name="bckup">
<p style="margin-left: 28px;"><label for="dscrb">Description: </label><input id="dscrb" type="text" style="z-index:10000" name="dscrb"> (optional)</p>
</form>
<p style="margin-left: 28px;">Blah?</p>
</div>
JS:
$("#backup").click(function() {
$( "#dialog-backup" ).dialog({
stack: true,
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Save": function() {
//$( this ).dialog( "close" );
$("#saveConf").trigger("click");
},
"Create a backup": function() {
$( this ).dialog( "close" );
var frm = $('form[name="bckup"]').serialize();
$.ajax({
url : "ajax_functions.php",
type: "post",
data: { action: "backup", frm: frm },
//dataType: "text",
dataType: 'json',
success : function (response) {
var response = response[0]
if (response && response.toLowerCase().indexOf("success") >= 0) {
$("#dialg-success-msg").text(response);
$("#dialg-success").dialog("open");
} else {
$("#dialg-failed-msg").text(response);
$("#dialg-failed").dialog("open");
}
},
error : function(response) {
$("#dialg-failed-msg").text(response);
$("#dialg-failed").dialog("open");
}
});
//return false;
//////////////////
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
PHP:
$dscrpn = isset($_POST["dscrb"]) ? trim(stripslashes($_POST["dscrb"]))."_" : '';
$backup_file = "backups/File_".$dscrpn.date('Y-m-d-H:i:s');
Since you are sending your post-data as frm: frm you will have to use $_POST['frm'] in PHP.
You will get a string like dcsbr=.... To convert this to an array use parse_str.
$form = [];
parse_str($_POST['frm'], $form);
var_dump($form);
Working example.

onsubmit return false is not working

The following script shows the error message correctly, but the form always submits whether confirm_shop_code() returns true or false. I tried in many ways to solve the bug but it still persists. I have to stop the form from submitting when it returns false, but allow it to submit when it returns true. Please can any one help me to solve this?
<h2 id="shop_data"></h2>
<!-- form -->
<form action="" class="form-horizontal form-label-left input_mask" method="post" onsubmit="return confirm_shop_code();">
<div class="col-md-4 col-sm-4 col-xs-8 form-group">
<input type="text" class="form-control" id="shop" name="code" value="<?php echo $account->code; ?>" placeholder="Enter Shop Code">
</div>
</form>
<!-- validation script -->
<script>
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
return true;
} else {
return false;
}
}
});
} else {
$( '#shop_data' ).html("");
return false;
}
}
</script>
<!-- php code -->
<?php
include "system_load.php";
$code = $_POST['shop_code'];
global $db;
$query = "SELECT code from accounts WHERE code='".$code."'";
$result = $db->query($query) or die($db->error);
$count = $result->num_rows;
if($count > 0) {
echo "SHOP CODE already Exists";
} else {
echo "OK";
}
exit;
?>
The reason it is submitting is because AJAX calls are asynchronous by default. I wouldn't suggest making it synchronous because this will block the rest of the javascript execution. Also, you are returning false from the success method of $.ajax. This is not in the same scope as the parent function and therefore does not also cause the parent function to return false. So in fact, your confirm_shop_code() function is not returning anything unless code is false and that's why your form is always being submitted, no matter what happens with the AJAX call.
I would recommend using jQuery to bind to the form's submit event and just disable form submitting with preventDefault(). First, just add an id attribute to the form (e.g. "yourform") and do something like:
$("form#yourform").submit(function(e) {
e.preventDefault();
var form = $(this);
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
form.unbind('submit').submit()
}
}
});
} else {
$( '#shop_data' ).html("");
}
});
You need to add async:false to your ajax code
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
var stopSubmit = false;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
async:false,
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
stopSubmit = false;
} else {
stopSubmit = true;
}
}
});
} else {
$( '#shop_data' ).html("");
stopSubmit = true;
}
if(stopSubmit){
return;
}
}
You should call return false; function on the click event of the submit button.
<button type="submit" id="submit" onclick="return false;" class="btn btn-primary col-4">Proceed</button>
or you can use:
document.getElementById("submit").addEventListener("click", function (e) {
//your logic here
//this return false will not work here
return false;
//this will work
e.preventDefault();
});

jQuery serialize function with multiple values

I try to use jQuery to post multiple values to PHP page, and then use that values as a single values.
I start with code from Jquery site :
<form ><br>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select>
<br>
<br>
</form>
<p><tt id="results"></tt></p>
<script>
function showValues() {
var str = $( "form" ).serialize();
$( "#results" ).text( str );
}
$( "input[type='checkbox'], input[type='radio']" ).on( "click", showValues );
$( "select" ).on( "change", showValues );
showValues();
</script>
Result is: multiple=Multiple&multiple=Multiple2, and that is fine.
Now mycproblem is how to post these values to test.php page, and then to use unique values, like this :
$multiple=[first value]
$multiple2=[second value]
etc...
Change your multiple to multiple[] in your form. This will submit your values as multiple[]=1st value, multiple[]=2nd value and more.
jQuery,
$('form').on('submit', function(e)
{
e.preventDefault();
formData=$('form').serialize();
$.ajax(
{
type: "POST",
url: "test.php",
data: formData,
success: function(data)
{
alert("Form submitted");
},
error: function()
{
alert("Error in form submission");
}
});
});
At the PHP end,
$multiple=$_POST['multiple']; // Get the array input
Now proceed with the values respectively,
foreach($multiple as $key => $value)
{
echo "value number $key is $value"; // This will print as value number 0 is 1st value, value number 1 is 2nd value and more.
}
You have to post the form to test.php using AJAX. Try this -
$("form").on('submit', function(ev){
ev.preventDefault();
var form = $(this);
var action = 'test.php';
var data = $(this).serialize();
$.post(action, data)
.done(function(response){
if(response.success == false)
{
// If failed
}
else
{
// If successfully submitted
}
});
});
And on the other side (test.php), you'll get an array of your multiple values like this,
$multiple1 = $_POST['multiple']['0'];
$multiple2 = $_POST['multiple']['1'];

Jquery Form on submit show success message

I have a form that uses Jquery to show a message for
*field required error message
I am trying to get it to show a success message if the form is submitted.
The form submits as long as the req fields are filled in.
Does anyone know how I can modify this code to show the "success" div if
all the "req" fields are filled out?
Thanks
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit( validateform );
$('$name').submit();
});
});
submitHandler: function(form){
$(form).ajaxSubmit({
target: '#preview',
success: function() {
$('#form id').slideDown('slow'),
<!-- RESET THE FORM FIELDS AFTER SUBMIT STARTS HERE-->
$("#form")[0].reset();
<!--RESET THE FORM FIELDS AFTER SUBMIT ENDS HERE--->
}
});
}
There are two simple ways that will allow you to render a success message. You can either use ajax with the callback success function, or if you want a full post, you you can check at the top of your file if a certain POST was set, and if so, render a success message.
Here is an example of checking POST:
if(isset($_POST['name attribute posting'])) {
$util->showSuccessMessage();
//OR echo "<div class='popup'></div>"
}
And here is an example of using Ajax's success callback function:
function submitForm() {
$.ajax({
url : 'this_file.php',
type: 'POST',
success : showSuccessMessage //function call
})
}
$(function() {
function validateform() {
var valid = true;
$(".req").css("border","1px solid #ccc");
$(".req").each(function() {
if ( $(this).val() == "" || $(this).val().replace(/\s/g, '').length == 0 ) {
$(this).css("border","1px solided");
$(".required").css("display","block");
valid = false;
}
});
return valid;
}
$("#submit").click( function() {
$('#myform').submit(function()
{
if( validateform)
{
$('$name').submit();
}
} );
});
});
reference submit

Retrieving AJAX value from a different Javascript function

In this simplified example of a larger web app, consider a simplistic registration form with fields: username, firstname, lastname and a Register button type="button".
<form action="" method="post" id="cns_form">
<table id="companyTable"><tr>
<td width="200">
First name*:<br />
<input type="text" id="first_name" name="first_name">
</td>
<td width="200">
Last name*:<br />
<input type="text" id="last_name" name="last_name">
</td>
</tr></table>
<input type="button" value="Register" id="register" >
</form>
<div id="alert" title="Alert"></div>
When the username field is completed, jQuery fires an ajax search of a database to see if that username already exists. This same search is also triggered when one clicks Register (for reasons removed from this simplified example).
PROBLEM: Everything works great when leaving the username field. However, after clicking Register, I don't know how to retrieve the result of the AJAX search and stop the form from submitting if the username already exists. I've tried all kinds of different things, but have returned the code to this state so it is easiest for the reader to assist.
For example, I tried integrating the suggested solution from this question, but I was unsuccessful applying it to my situation... I tried setting async:false inside the ajax function... I also tried calling the checkUsername(uname) from inside the checkForm function, but that didn't work either. A little help?
jQuery document.ready:
$(function(){
$('#username').blur(function() {
var uname = $.trim($(this).val());
checkUsername(uname);
}); //END BLUR username
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkUsername(uname);
checkForm();
});
}); //END document.ready
AJAX Call:
function checkUsername(uname) {
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
}
checkForm Function:
function checkForm() {
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
}
One both rejoices and weeps when answering his own question, but here goes. The solution was to send the checkUsername() function as an input param to the checkForm() function, and to make the checkUserName() function return a value that we could check inside checkForm().
Therefore, we must modify the $('#register').click function thusly:
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkForm(checkUsername(uname)); //<===========================
});
THEN the checkUsername() function, thus:
function checkUsername(uname) {
var returnVal = 0; //<=================================
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
returnVal = 0; //<============================
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
return returnVal; //<==============================
}
AND the checkform() function thus:
function checkForm(exists) { //<============================
alert('sub checkForm(). value of exists: ' + exists);
if (exists==9) { //<================================
$( '#alert' ).html( 'That username is already in use' + existing +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
}else{ //<==========================================
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
} //<===================================================
}
Thanks and kudos to Felix Kling for this helpful post.
Might put return false in the function call in the HTML form markup.
<form>
<bunchOfElements />
<button onclick="checkUserName(); return false">Check Name </button>
</form>
Also, you might bind the function to the button's click event using
$(document).ready(function(){
$("#buttonID").bind('click', function(){
//do your thing
checkForm();
});
});
Put a return false at the end of your #register button click function, right below checkForm(). The button is continuing to fire the form submit. when you have that handled by your javascript function.

Categories

Resources