About AJAX , FORM AND PHP - javascript

My ajax code looks like this which check the registration form username, email, etc...
jQuery(document).ready(function($) {
$("#formform").on('change', 'input',function(event){
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "/registration_check.php",
type: "post",
data: {formData:serializedData},
datetype: "JSON"
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("error");
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
});
And my PHP look like this:
$get_form_data=$_POST["formData"];
parse_str($get_form_data,$form_data);
if(isset($form_data["username"])){
if(strlen($form_data["username"])<5){
echo "Username must be at least 5 character";
}else{
if(ValidUserName($form_data["username"])){
if($checkUser->checkUserName(char_encoder($form_data["username"]))==true){
echo "Sorry this UserName Already Exist";
}else{
echo "UserName Available";
};
}else{
echo "Invalid Username";
}
}
}
Now How do i disable the form when Invalid Username comes from AJAX as response?
I though i should use return false..but don't know how to handle the response?

try as below format you can handle response in success event:
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
type: "POST",
url: "/registration_check.php",
data: {
formData:serializedData
},
beforeSend: function () {
//do stuff like loading process until you get the response
},
success: function (resp) {
var obj = jQuery.parseJSON(resp);
//console.log(obj); // this will display response in console.
//do stuff here
},
error: function(e){
alert("Error in ajax call: "+e);
}
}); // complete AJAX
PHP CODE:
$array = array();
if (isset($form_data["username"])) {
if (strlen($form_data["username"]) < 5) {
$array['success'] = false;
$array['message'] = "Username must be at least 5 character";
} else {
if (ValidUserName($form_data["username"])) {
if ($checkUser->checkUserName(char_encoder($form_data["username"])) == true) {
$array['success'] = false;
$array['message'] = "Sorry this UserName Already Exist";
} else {
$array['success'] = true;
$array['message'] = "UserName Available";
}
} else {
$array['success'] = false;
$array['message'] = "Invalid Username";
}
}
echo json_encode($array);
}

make your ajax call on form submit event and call event.preventDefault(); if ajax returns any error.
Hope this help :)

Related

Is there a way to prevent Enter key from returning a response in json from another page? Codeigniter Ajax

I am using ajax for my operations Create and Update
I can already create and update, but if I press or hit Enter key then this shows from another page which is kinda not look good to see, and it suddenly also create blank data after hitting Enter key.
{"success":false,"type":"update"}
For visual representation, here it what it looks like after hitting the Enter key on input fields
this is what my input is in my View
<input type="text" name="group[]" id="group" placeholder="Enter your Choice" class="form-control" />
in my Controller
public function addGroup(){
$result = $this->group_model->addGroup();
$msg['success'] = false;
$msg['type'] = 'add';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
public function updateGroup(){
$result = $this->group_model->updateGroup();
$msg['success'] = false;
$msg['type'] = 'update';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
And in Model
public function updateGroup(){
$id = $this->input->post('txtId');
$field = array(
'group_name'=>$this->input->post('group')
);
$this->db->where('id', $id);
$this->db->update('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
public function addGroup(){
$field = array(
'group_name'=>$this->input->post('group'),
);
$this->db->insert('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
Ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
$('#myForm').submit(function(e){
$('#btnSave').attr('disabled',true); //disable the button
//.Your other code
success: function(response){
if(response.success){
$('#btnSave').attr('disabled',false); //enable the button
}
}
}
On CLicking the button disable the click event of submnit button which is default behaviour if you press Entern and enable it back if u get successfuly response.
In addition if you just want to disable enter key then u cn do it like this:
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
Change
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
into
$('#myForm').submit(function(e){
e.preventDefault();
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
beforeSend: function(){
$('#btnSave').attr('disabled',true);
},
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
$('#btnSave').attr('disabled',false);
return false;
});
});
Change button into Submit
Hope this Helps !!

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

if use ajax call for contact form submitting, header(location:/path) not working

The issue is if try to ajax call for submitting my contact form. then header("location: /path); starts not working.
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
// header("location: /contact/thankyou.html");
}
} else {
echo "Invalid captcha! Please enter again. ";
}
And yes, because header redirect is not working. I comment it out. And tried to redirect page inside ajax call like below.
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function(){
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data){
response.html(data).fadeIn();
window.location.href ="/contact/thankyou.html";
},
error: function(e){
console.log(e)
}
});
});
});
But this time, it's only redirecting inside the .status div! like in the image Normally I am displaying a error message in that div...
Hey This is wrong practice if you are using ajax req then php not able to redirect to your destination all you need to redirect in ajax success response simple us
$data = array();
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
$data['status'] = 1; // for true
$data['message'] = "your success message"; // for true
}
}
else {
$data['status'] = 0; // for false
$data['message'] = "your error message"; // for false
}
//define content type json if you never echo like echo 'ss' then no need to this
header('Content-Type: application/json');
echo json_encode($data);exit;
and get response in ajax request dataType Json to access json array obj
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'json',
data: form.serialize(),
beforeSend: function() {
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data) {
if (data.status == 1) {
response.html(data.message).fadeIn();
window.location.href = "/contact/thankyou.html";
}
else{
// for error
response.html(data.message).fadeIn();
}
},
error: function(e) {
console.log(e)
}
});
});
});
You have to send header as Base64 string then decode it in the service / Backend.

page redirect is not working in jquery

<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

Categories

Resources