Custom Form Validation and Submit - php

I have a form validation run when the submit button is selected but i do not want the default submit function to run. Instead i want to run an ajax post code to store the data in the form along with post the data from server side.
I am having trouble finding where to cancel the default submit and add in the ajax code.
Here is the validate code i have
$("#formEnroll").validate({
errorElement:"p",
submitHandler: function(form) {
var phoneNumber = form.day_phone.value;
var phoneParts = phoneNumber.split("-");
form.dayArea.value = phoneParts[0];
form.dayPrefix.value = phoneParts[1];
form.daySuffix.value = phoneParts[2];
form.submit();
}
});
And here is the ajax code i want to run instead of the default submission
$.ajax({
type: "POST",
url: "/php/localProxy.php",
data: $('#formEnroll').serialize(),
success: function (response) {
document.location = 'http://www.xxxx.com/thank-you';
},
error: function () {
alert('There was a problem!'); // handle error
}
});

you can call the the ajax function instead of form.submit();
form.submit(); will submit your code using default submission.
$('#formEnroll').on('submit', function(e){
e.preventDefault();
$(this).validate({
errorElement:"p",
submitHandler: function(form) {
var phoneNumber = form.day_phone.value;
var phoneParts = phoneNumber.split("-");
form.dayArea.value = phoneParts[0];
form.dayPrefix.value = phoneParts[1];
form.daySuffix.value = phoneParts[2];
submitform();
}
});
})
function submitform(){
$.ajax({
type: "POST",
url: "/php/localProxy.php",
data: $('#formEnroll').serialize(),
success: function (response) {
document.location = 'http://www.xxxx.com/thank-you';
},
error: function () {
alert('There was a problem!'); // handle error
}
});
}

You could wrap your validate plugin into a generic form submit function to stop standard execution.
$('#formEnroll').on('submit', function(e)
{
e.preventDefault(); // stop form submission
// Run validation
$(this).validate({
errorElement:"p",
submitHandler: function(form) {
var phoneNumber = form.day_phone.value;
var phoneParts = phoneNumber.split("-");
form.dayArea.value = phoneParts[0];
form.dayPrefix.value = phoneParts[1];
form.daySuffix.value = phoneParts[2];
submitform(); // call your ajax function here
}
});
});
function submitform(){
$.ajax({
type: "POST",
url: "/php/localProxy.php",
data: $('#formEnroll').serialize(),
success: function (response) {
document.location = 'http://www.xxxx.com/thank-you';
},
error: function () {
alert('There was a problem!'); // handle error
}
});
Instead of using the event object e you can also just return false; at the end of the .on function to stop default events from firing.

You can send the data by ajax using the click event in the jquery by clicking the submit button and that function should return false for avoiding the default submission by the way you can send the data using ajax and avoid the default submission.

Related

ajax form validation in laravel 5

I am new in laravel and need help.
These are the values I'm getting via ajax, all values are to be stored in db, but how do I validate[check] if there are existing values or not before submitting a form using ajax?
$("#submit").click(function(e){
e.preventDefault();
var url = "{!! URL::to('/') !!}";
var id="{!! #$department->id !!}";
var token = "{!! csrf_token() !!}";
var customer_id = $("#customer_id").val();
var visiting_address1 = $("#visiting_address1").val();
var department_id = $("#department_id").val();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: url+"/customer/"+customer_id+"/popup_store",
data: { '_token':token, 'rest':'true', 'customer_id':$("#customer_id").val(), 'main_address':$("#main_address").val(),'visiting_city':$("#visiting_city").val(),'visiting_address':$("#visiting_address1").val(),'visiting_zip':$("#visiting_zip").val()},
async : false,
success : function(data) {
if(data == "success")
{
$("#addrecords").modal('hide');
}
else
alert(data);
}
});
});
First of all define you Jquery validation for you form like this:
$("#myForm").validate({
// Specify the validation rules
rules: {
name: "required",
},
// Specify the validation error messages
messages: {
name: "Please enter name",
},
submitHandler: function (form) {
// leave it blank here.
}
});
And then in your click button of submit button, write if condition to check validations:
$("#submit").click(function (e) {
if ($('#myForm').valid()) {
// your Ajax Call Code
} else {
return false;
}
});

php form not submitting using ajax jquery

.on('success.form.bv', function(e) {
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
If i comment this code, then form submits.PLease tell me the error.This is the form

wordpress admin ajax don't work

i'm making a plugin for sending messages to users
and i'm using ajax in the plugin
and i'm not getting it the right way
here is my jQuery code
i tryed many times but i cant get it done
<script type="text/javascript">
$(document).ready(function () {
$(document).ajaxStop(function () {
$.unblockUI();
});
//if form is submitted
$('#whatsappform').submit(function (e) {
if ($('#whatsappform').validate().form() === false) {
return false;
}
//Store original html to replace back in box later.
var original = $('#faketextbox').html();
//Scan html code for emojis and replace with text and special marker.
$('#faketextbox img').each(function (index) {
var emojiUnicode = this.outerHTML.match(/emoji-(.*?)"/)[1];
$(this).replaceWith('##' + emojiUnicode + '##');
});
//Replace all BR's with line breaks.
var message = $.trim($('#faketextbox').html().replace(/<br\s?\/?>/g, "\n"));
//Copy the corrected message text to our hidden input field to be serialised.
$('#message').val($('#faketextbox').html(message).text());
//Replace the corrected text with the original html so it shows properly on a browser.
$('#faketextbox').html(original);
//Continue with the form.
var formData = $("#whatsappform").serialize();
$.ajax({
type: "POST",
url: "http://localhost:81/wp/wp-admin/admin-ajax.php",
cache: false,
data: formData,
dataType: "json",
timeout: 45000,
success: onSuccess,
error: onError,
//beforeSend: function(jqXHR, settings) {
//},
complete: function () {
$.unblockUI();
}
});
return false;
});
</script>
sorry for the bad english :)
WordPress expects your JS in noconflict mode, wrap the code as follows:
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
});

Making Java Script global variables

I am using the var function to create variables so that I can use them in PHP So I can use the post function, Basically I imported them in javascript.
Anyway how do I make them global variables?
Ive tried including them in the document.ready function or even before the code starts executing document.ready function. it be alot neater then just repeating those var everywhere.
Here is the code
$(document).ready(function () {
var user_login = $('#user_login').val();
var user_pass = $('#pass_login').val();
$('#field').keyup(function (e) {
if (e.keyCode == 13) {
//If enter is pressed vailidate the form
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
user_login: user_login,
pass_login: user_pass
},
success: function (data) {
$('#content').html(data);
}
});
};
});
$('#submit').click(function (e) {
if (e.keyCode != 13) {
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
user_login: user_login,
pass_login: user_pass
},
success: function (data) {
$('#content').html(data);
}
});
}
});
});
You probably dont want them to be global, as there is no reason. As you have this coded now the variables will be evaluated only once as soon as the document is ready which will be before a user has entered anything in your form fields. You want to evaluate them in your onkeyup handler or on submit of the form so that you have the current values. Im not sure that your check.php does but it should look something like this:
$(function(){
$('form#theform').submit(function(e){
e.preventDefault();
var user_login = $('#user_login').val(),
user_pass = $('#pass_login').val();
// you ajax submit here
});
$('#field').keyup(function(e){
e.preventDefault();
var user_login = $('#user_login').val(),
user_pass = $('#pass_login').val();
// do your validation, if successful then do: $('theform').trigger('submit');
});
});
The reason you dont want to use globals here is because you ALWAYS need the most recent input. If you use a global variable then there is no way to tell that you have the most recent input because things are going to get out of sync.
Global is probably not the way to go here. It sounds like you are more interested in reducing the duplicate code? You could refactor the current code into something like:
$(document).ready(function () {
function submitForm() {
var user_login = $('#user_login').val();
var user_pass = $('#pass_login').val();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {
user_login: user_login,
pass_login: user_pass
},
success: function (data) {
$('#content').html(data);
}
});
}
$('#field').keyup(function (e) {
if (e.keyCode == 13) {
//If enter is pressed vailidate the form
e.preventDefault();
submitForm();
};
});
$('#submit').click(function (e) {
if (e.keyCode != 13) {
submitForm();
}
});
});
You need to call .val() on your input each time you want to get the current value of the inputs. If you only call it once at the beginning, the variables won't stay up-to-date as the user types in the inputs.
Do something like this:
$(document).ready(function() {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
user_login: $('#user_login').val(),
user_pass: $('#pass_login').val()
}
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
$('#content').html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function(e) {
if (e.keyCode == 13) check(e);
});
$('#submit').click(function(e) {
if (e.keyCode != 13) check(e);
});
});

ajaxStart and ajaxStop for a specific event

How can I bind an ajaxStart function for a specific event, using :
$(document).ajaxStart(function () {
alert("started");
});
$(document).ajaxStop(function () {
alert("Ended");
});
Tried this code but it runs whenever autocomplete starts.
Scenario must be like this : whenever I submit a form, that function will be called.
But when I'm just fetching values using autocomplete via ajax, ajaxStart and ajaxStop shouldn't be called.
But when I'm just fetching values using autocomplete via ajax,
ajaxStart and ajaxStop shouldn't be called.
You can create a boolean variable to keep track of whether user is typing or not something like:
<script>
var isTyping = false;
// inside your autocomplete handler set isTyping to true
$(document).ajaxStart(function(){
if (! isTyping) alert("started");
});
$(document).ajaxStop(function(){
if (! isTyping) alert("Ended");
});
</script>
It is better if you uses the main function and it's sub-functions.
$.ajax({
url: 'url_to_page'
beforeSend: function(req){ //Before the request is taking off},
error: function(req){ //If there were a error},
success: function(req){ //When it all was done}
});
$.ajax({
url :'your url',
data: {
//data to send if any
},
type: 'POST',
success:function(msg){
//eqv to ajaxstop if OK
},
beforeSend:function(){
//before ajax starts
},
error:function(){
//failure in ajax
}
});

Categories