jQuery $.post not executing, how to fix - javascript

I am working on a Plugin for WordPress and am having issues with the js code below executing the $.post.
The js is called, form validation takes place, the form inputs are serialized into post data correctly, the $.post just doesn't execute.
The form is being posted from the Admin, currently I can't get the .submit action to work so am using .click to execute the js function. This may be related to the issue, I am not sure... The form will load without submitting if I use the .submit action, versus using the .click action... never had this issue before and it is pretty frustrating to say the least.
Here is the code:
jQuery(document).ready(function($) {
$("#edit_member_submit").click( function() {
// define
var numbers = /^[0-9]+$/;
var referrer_id = $("#referrer_id").val();
// Validate fields START
if( !referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
// Define a data object to send to our PHP
$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null) {
value = this.value;
} else {
value = '';
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
};
var data = $("#edit_member_form").serializeObject(); //the dynamic form elements.
//alert(JSON.stringify(data));
data.action = "edit_member_info"; //the action to call
data._ajax_nonce = custajaxobj.nonce; // This is the name of the nonce setup in the localize_script
// Define the URL for the AJAX to call
var url = custajaxobj.ajaxurl;
//alert( JSON.stringify( data ) );
//alert( JSON.stringify( url ) );
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
return false;
});
});
Seems like the last section is having issues:
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});

$.post( "ajax/test.html", function( data ) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(data);
});

Related

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

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

onSubmit form - Ajax request to validate the form

I have this scenario where when submiting html form we call javascript method to validate the form. Problem is that validation is done through Ajax request calling php function which returns json array which is empty or contains array with errors.
I am using Ajax request as this newValidation function will be used on all forms on my application so all field ids names and stuff is dynamic same as validation messages.
Console log results are:
Undifiend
It should be True or False.
So it looks like .done run after console.log.
I thought .done is waiting until ajax is finished and only then proceed?
Reason why I am asking I need this .done to run first so it can assing answer variable and only then return boolean to the form. Does this even possible?
UPDATED:
Html form:
<form id="systemManagementSettings" action="#" method="POST" onsubmit="return newValidation('systemManagementSettings')">
JavaScript
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
answer = true;
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
answer = false;
}
});
console.log(answer);
return answer;
}
How do you prevent the form from actually being submitted?
Use event.preventDefault().
UPDATE
Submit the form in the done function.
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
$.ajax({
url: $('#'+formId).attr('action'),
type: "POST",
data: {form: $('#'+formId).serializeArray()},
});
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
}
});
return false; //all the time
}

Change javascript validation on form to onblur or onchange instead of submit

I have a form that validates php and javascript.
I would like to change the javascript validation to real time. I have it setup so classes and messages are added if user enters proper information or incorrect information after clicking the submit button. This is a validation I have used for awhile and would like to update to be a live validation. I have tried to add onblur(myFunction) etc to the input fields with a corresponding function. That does not seem to work. I am a javascript noob. I realize the script will need quite a bit of overhaul, however can someone point me in the right direction. I realize there is a jquery plugin that does some of this, however I would like to learn how its happening rather than using an existing code.
$(function () {
$('#contact_form').submit(function(e) {
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
var submit_form = false;
*validation here*
if (pcount == 0 && pcount2 == 0 && pcount3 == 0) {
submit_form = true;
}
if (submit_form) {
$('#loader', form).html('<img src="assets/img/loader.gif" /> Please Wait...');
$.ajax({
type : 'POST',
url : post_url,
data : post_data,
success : function(msg) {
$(form).fadeOut(500, function() {
form.html(msg).fadeIn();
});
}
});
}
});
});
It is not so hard to do, just separate the sending and the validation like this:
$.fn.validateMyForm = function() {
var form = $(this);
/* validation */
if (pcount == 0 && pcount2 == 0 && pcount3 == 0) {
return true;
}
return false;
}
$(function () {
$('#contact_form').submit(function(e) {
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
if ($(form).validateMyForm()) {
/* ajax sending */
});
}
});
And then add the validation on the blur events where needed:
$("input").blur({
$('#contact_form').validateMyForm();
});

How to save var value outside ajax success function?

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Categories

Resources