Validation on form action when using preventDefault - php

I'm making a ajax call to a server side function to send an email. It works fine. My issue is before sending the email i need to validate the captcha where the server side code resides in CaptchaValidation.php. If i call "CaptchaValidation.php" on form action it should work fine but here since i'm doing a ajax call i need to use e.preventDefault();. So that form action is not working.
How can i make it work?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#divLoading').hide();
$('#appointment').submit(function (e) {
e.preventDefault();
var serviceURL = 'WebService.asmx/SendMail';
var Name = $("#fname").val();
var Email = $("#email").val();
var Telephone = $("#phone").val();
var Comment = $("#comment").val();
if ($("#fname").val().length == 0) {
alert("Please Enter Name");
$("#fname").focus();
return false;
}
if ($("#email").val().length == 0) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf("#") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
if (Email.indexOf(".") == -1) {
alert("Please Enter Your Email Address.");
$("#email").focus();
return false;
}
$('#divLoading').show();
$.ajax({
type: "POST",
url: serviceURL,
data: '{"name":"' + Name + '","address":"' + Email + '","telephone":"' + Telephone + '","comment":"' + Comment + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
// alert("Mail Sent!");
$('#divLoading').hide();
window.location = "contat-submit.php";
}
function errorFunc() {
// alert('error');
}
});
});
</script>
</head>
<body>
<form name="appointment" id="appointment" method="post" action="CaptchaValidation.php">
<div>
</div><div id="leftcolumn4"><div class="h2">Contact Form</div>
<form name="appointment" id="Form1" method="post" action="send_contact.php">
Full Name:
<br />
<label>
<input name="fname" type="text" class="form-input" id="fname" size="30" />
</label>
<br /><br />
Email Address:<br />
<label>
<input name="email" type="text" class="form-input" id="email" size="30" />
</label><br /><br />
Telephone:
<br />
<label>
<input name="phone" type="text" class="form-input" id="phone" size="30" />
</label>
<br /><br />
Your Comment:<br />
<label>
<textarea name="comment" cols="28" rows="4" class="form-input-box" id="comment"></textarea><br />
<br />
</label><input name="submit" type="submit" class="form-input-submit" value="Submit" id="btnMail"/>
</div>
</form>
</body>
</html>

Follow the steps:
Change the Submit button to a simple button so that on click of that button the form will not submit.
On Click of that button call a function which will have call e.preventDefault();
function callSubmit() {
// do ajax call
}
You are doing ajax call in e.preventDefault() function. So in AJAX response, you have to check if the AJAX response is correct then do a form submit using:
$('#appointment').submit()
Now just remove the e.preventDefault(); function from you form.submit function you have written. This will allow to AJAX submit and send email.

Related

How to download PDF after fadeout the success message?

I am using a form to submit email and name to the user. After submitting the form email triggered and success message displaying. Success message fade-out after 10 seconds i.e. fine. Now I want to download a pdf also after fadeout success message.
I am achieving this via action.
I am using below code:
<form class="brochure brochure_1" method="post" id="custom_contact_form" action="http://example.com/contact/index/contact" onsubmit="return validateForm();" name="myForm">
<div class="input-box">
<input type="hidden" readonly="readonly" class="input-text required-entry toname" value="" name="toname"/>
<input type="hidden" value="<?php echo $this->getFromUrl(); ?>" name="submiturl" class="submiturl" />
</div>
<input type="text" class="input-text required-entry" value="" name="name" placeholder="Name"/>
<input type="text" class="input-text required-entry" value="" name="email" placeholder="Email"/>
<span><input type="submit" value="Download" /></span>
</form>
<script>
function validateForm() {
var name = document.forms["myForm"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["myForm"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (email == "") {
alert("Email must be filled out");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
}
jQuery('.success-msg').insertBefore(jQuery( ".breadcrumbs" ));
jQuery(document).ready(function(){
setTimeout(function() {
jQuery('.success-msg').fadeOut('fast');
}, 10000); // <-- time in milliseconds
});
</script>
Replace the document ready like this,
jQuery(document).ready(function(){
setTimeout(function() {
jQuery('.success-msg').fadeOut('fast');
}, 10000); // <-- time in milliseconds
window.location.href = href; //causes the browser to refresh and load the requested url, Put the url to download pdf here.
});

Laravel 5.2 - ajax check if value exists in database

I am creating an employee hierarchy and while setting up the superior for new employee I would like to check if the employee already exists in database ... but :) I would like to do it with AJAX to know it realtime without sending the form ..
I have absolutely no idea how to do it, since I am a newbie to Laravel ..
***UPDATED BASED ON ADVICES:***
I have a form in add_emp.blade.php:
<form action="../create_employee" method="POST">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br />
</fieldset>
</form>
Here is a script in add_employee.blade.php
<script type="text/javascript">
$('#superior_list').blur(function(){
var first_name = $('#superior_list');
$.ajax({
method: "POST",
url: '/check_superior',
data: { superior: superior }
})
.done(function( msg ) {
if(msg == 'exist') {
//employee exists, do something...
alert( "good." );
} else {
//employee does not exist, do something...
alert( "bad." );
}
});
})
</script>
route for handling the superior:
Route::post('check_superior', 'EmployeeController#check_superior');
This is the Controller function check_superior:
public function check_superior(Request\AjaxUserExistsRequest $request){
if(Employee::where('superior','=',$request->input('superior'))->exists()){
return "exist";
}else{
return "not exist";
}
}
But still not working ... can you advice where could be the issue?
*** FINAL SOLUTION ***
Form:
<form action="../create_employee" method="POST">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><span id="check-superior-status"></span><br />
</fieldset>
</form>
Add to app.blade.php
meta name="csrf-token" content="{{ csrf_token() }}"
Controller
public function check_superior(Request $request){
if(Employee::where('first_name','=',$request->input('superior_fname'))
->where('last_name','=',$request->input('superior_lname'))
->exists()){
return "exist";
}else{
return "not exist";
}
}
final emp.blade.php AJAX script
// place data after SEPERIOR selection
$( "#superior_list" ).blur(function() {
var sup_list = $(this).val();
var sup_arr = sup_list.split(' ');
var superior_fname = sup_arr[0];
var superior_lname = sup_arr[1];
var superior = superior_fname+" "+superior_lname;
// control print out
//$('#check-superior-status').text(superior);
// get real data
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: "POST",
url: '/check_superior',
data: { superior_fname: superior_fname, superior_lname: superior_lname },
/* // debug only
error: function(xhr, status, error){
$('#check-superior-status').text(xhr.responseText);
},
*/
success: function(data){
$('#check-superior-status').text(data);
}
})
});
This works like a charm :) thank you guys .. hope this will help someone ..
First make the request.
php artisan make:request AjaxUserExistsRequest
Then open the request file (App\Http\Requests) and find the following:
public function validate(){
return [
//rules
];
}
This is where you would stick your validation rules so you can check against the form elements being submit.
Then you should use dependency injection to force your request into the first argument of the user_exists() function:
public function user_exists(Requests\AjaxUserExistsRequest $request){
return User::where('first_name', $request->first_name)->first();
}
This will return nullif no user exists, otherwise we don't care about the response.
Finally, of course we need our route.
Route::post('employee_exists', 'EmployeeController#user_exists');
Lastly, we'll go ahead and capture the form submit and check if the user exists with our jQuery.
$('#employee_form').submit(function(e){
e.preventDefault();
var first_name = $('#first_name').val(),
$this = this; //aliased so we can use in ajax success function
$.ajax({
type: 'POST',
url: '/employee_exists',
data: {first_name: first_name},
success: function(data){
if(data == null){
//then submit the form for real
$this.submit; //doesn't fire our jQuery's submit() function
} else {
//show some type of message to the user
alert('That user already exists!');
}
}
});
});
The below will give alert message the user already exists! if the first_name exists in your db or it will give alret nothing.(if you want to check with superior change the code vice versa)
first make sure you have jquery.min.js in your public folder.
Now in blade.php add id for first_name, last_name, and superior as below:
<form action="../create_employee" method="POST">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" id="first_name" class="add_emp required" name="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" id="last_name" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br />
</fieldset>
</form>
<script>
$(document).ready(function(){
$("#superior_list").blur(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var superior = $('#superior_list').val();
$.ajax({
type: 'POST',
url: '/check_superior',
data: {first_name: first_name, last_name: last_name, superior: superior},
success: function(data){
if(data == 0){
alert('nothing');
} else {
alert('the user already exists!');
}
}
});
});
});
</script>
and in your route.php
Route::post('/check_superior', array('as' => '', 'uses' => 'EmployeeController#check_superior'));
in EmployeeController.php
public function check_superior(){
// can get last_name, superior like first_name below
$first_name = Input::get('first_name');
$data = YourModel::where('first_name',$first_name)->get();
return count($data);
}
It should work. if it doesn't please show us your error
Give your form an id:
<form action="../create_employee" method="POST" id="employee_form">
<button class="button" type="submit" style="float:right"><span>Save</span></button>
<div style="clear:both"></div>
<fieldset>
<legend>Personal data</legend>
<label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" id="first_name" value="" /><br />
<label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
<label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br />
</fieldset>
</form>
your js will look like this
$('#employee_form').submit(function(e){
e.preventDefault();
var first_name = $('#first_name');
$.ajax({
method: "POST",
url: "checkUserExistence.php",
data: { first_name: first_name }
})
.done(function( msg ) {
if(msg == 'exist') {
//employee exists, do something...
} else {
//employee does not exist, do something...
}
});
})
also add csrf_field in your form to generate token, and use this token while sending request.
in your form:
{{ csrf_field() }}
in your ajax request:
$.ajax({
headers: {'X-CSRF-Token': $('input[name="_token"]').val()},
//other data....
})
you can also do it with meta teg. in your head teg
<meta name="csrf-token" content="{{ csrf_token() }}">
in your request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content');
//other data...
}
});

how to send changing value under a "hidden" tag on a form

I have 9 pictures on each page, and when someone clicks on a picture the picture is opened in a fancybox, then if a person wants more information about the piece the click on a link inside the fancybox and the form opens inside a modal box.
All of the code works and the form is send through ajax then php.
The problem that I have is that all 9 pictures open the same form and when I client fills out the request form with their contact information, there is no way of me knowing which photo they are looking at.
It would be nice to add a "Hidden" value that is sent with the form so I can know which photo they are requesting the information.
I have looked around SO but to no avail
basic form
<div id="inline">
<form id="contact" name="contact" action="sendmessage.php" method="post">
<label for="name">Your Name </label>
<input type="text" id="name" name="name" class="txt">
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send Request</button>
</form>
link to photo
<a class="fancybox" rel="gallery" href="inventory/inv_pictures/pic4.jpg"><img
src="inventory/inv_thumbs/thumb4.jpg" alt="Antique Furniture - Pic 4"
id="gallery"/></a>
I figured that maybe there is away to add a title tag or use the alt tag under the tag
that the form can pick up and send it as a "hidden" item. That way each photo can still access the same form but then I can know which item they are requesting for.
Sorry for not posting the whole code for fancy box.
but here it is:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>
<link rel="stylesheet" href="../js/source/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" />
<script type="text/javascript" src="../js/source/jquery.fancybox.pack.js?v=2.1.5"> </script>
<script type="text/javascript">
$(".fancybox").fancybox({
afterLoad: function() {
this.title = '<a class="modalbox" href= "#inline" >Request more information</a> ' + this.title;
},
helpers : {
title: {
type: 'inside'
}
}
});
</script>
<!-- Hidden inline form -->
<div id="inline">
<form id="contact" name="contact" action="sendmessage.php" method="post">
<label for="name">Your Name </label>
<input type="text" id="name" name="name" class="txt">
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<input type="hidden" id="link" name="link" value="">
<button id="send">Send Request</button>
</form>
</div>
<script type="text/javascript">
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\ [[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var nameval = $("#name").val();
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
var namelen = nameval.length;
if(namelen < 2) {
$("#name").addClass("error");
}
else if(namelen >= 2) {
$("#name").removeClass("error");
}
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4 && namelen >= 2) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p> <strong>Success! Your request has been sent. We will respond to it as soon as possible. </strong></p>");
setTimeout("$.fancybox.close()", 3000);
});
}
}
});
}
});
});
</script>
As I can see the link you are giving to fancybox is a direct link to a picture.
I am confused how you get a link to the form inside the modal as it doesn't seem to be coded here.
What I would suggest is, instead of giving direct picture link, create another page and code that page to collect a pic url/id from by GET/POST and display the corresponding pic and then embed this page into the fancybox.
So basically what I am saying is, pass the pic id/path from url that you pass to the fancybox, collect it and then further pass it to the form link

jQuery Ajax form not submitting on iPhone

I have a jQuery Ajax form that looks like this:
<form method="post" action="contact.php" class="contact-form">
<div class="contact-empty">
<input type="text" name="name" id="name" placeholder="Name *" class="txt-name" />
<input type="text" name="email" id="contact-email" placeholder="Email Address *" class="txt-email" />
<textarea rows="4" name="message" cols="60" id="message" placeholder="Message *" class="txt-message"></textarea>
<span class="btn-contact-container">
<button id="contact-submit" class="btn-contact">Submit</button>
<img src="images/loading.gif" alt="Loading..." width="62" height="62" id="contact-loading">
</span>
<span class="contact-error-field"></span>
</div>
<div class="contact-message"></div>
</form>
Here's my js that sends it:
$(document).ready(function () {
$('#contact-submit').click(function () {
$('.contact-error-field').hide();
var nameVal = $('input[name=name]').val();
var emailReg = /^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/;
var emailVal = $('#contact-email').val();
var messageVal = $('textarea[name=message]').val();
//validate
if (nameVal == '' || nameVal == 'Name *') {
$('.contact-error-field').html('Your name is required.').fadeIn();
return false;
}
if (emailVal == "" || emailVal == "Email Address *") {
$('.contact-error-field').html('Your email address is required.').fadeIn();
return false;
}
else if (!emailReg.test(emailVal)) {
$('.contact-error-field').html('Invalid email address.').fadeIn();
return false;
}
if (messageVal == '' || messageVal == 'Message *') {
$('.contact-error-field').html('Please provide a message.').fadeIn();
return false;
}
var data_string = $('.contact-form').serialize();
$('.btn-contact').hide();
$('#contact-loading').fadeIn();
$('.contact-error-field').fadeOut();
$.ajax({
type: "POST",
url: "contact.php",
data: data_string,
//success
success: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-check contact-success"></i>Your message has been sent.').fadeIn();
},
error: function (data) {
$('.btn-contact-container').hide();
$('.contact-message').html('<i class="fa fa-times contact-error"></i>Something went wrong, please try again later.').fadeIn();
}
}) //end ajax call
return false;
});
});
I have a subscribe form that uses the same code with just an email input and that submits fine on an iphone.
The contact form, however, gets stuck at 'Invalid email address.' when trying to submit from an iPhone even though the email you enter is correct. It works on desktop.
I've tried changing the button to a type="submit" input. Didn't change anything.
UPDATE: My regex was wrong, I replaced it with the following and it worked:
var emailReg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/igm;
Instead of using click() to submit your form, use submit():
Just change the top of your javascript code so it looks like this:
$(document).ready(function () {
$('form.contact-form').submit(function (e) {
e.preventDefault(); // <-- prevents normal submit behavior
And change your button to type=submit
<button type="submit" id="contact-submit" class="btn-contact">Submit</button>

SUBMIT FORM with mouse clicking and enter button

I am Submiting form through MOUSE CLICK and ENTER too.
Ajax Call is checking is there any designation which i already in DATABASE.. If not, user can submit form otherwise SUBMIT button will DISABLE
JQUERY
function check_designation(e){
text = $('#req1').val();
data = "data=" + text;
text_length = text.length
if(text_length == 0)
{
$('#result_span').html('');
}
if(text_length > 3 ){
$.ajax({
url: "designation_ajax.php",
type: "POST",
data: data,
cache: false,
success: function (response) {
if ($.trim(response) == "access") {
$("#result_span").html('<div class="green">' + text + ' is available '+'</div>');
$('#create_desg').removeAttr('disabled');
}
else if ($.trim(response) == "no access") {
$("#result_span").html('<div class="red">' + text + ' is already in use'+'</div>');
$('#create_desg').attr('disabled','disabled');
}
else {
alert('Sorry, unexpected error. Please try again later.');
}
}
});
}
else{
$("#result_span").html('');
}
return true;
}
HTML FORM
<form id="formID" class="formular" method="POST" action="" onsubmit="formSubmit()" >
<fieldset>
<legend>Create Desination</legend>
<label> Designation<br clear="all" />
<input autocomplete="off" onkeyup="check_designation(event)" value="" class="validate[required,minSize[4]] text-input float_left" type="text" name="name" id="req1" />
<span id="result_span"></span>
</label>
<br clear="all" />
<input id="create_desg" value="Submit" type="button" />
</fieldset>
</form>
PROBLEM::::
Now what happen DISABLE button is not a solution... if there is already a DESIGNATION in a table.. submit button will disable but By ENTER it will submitted and i dont want to reload the page. and AJAX is not working when i PRESS ENTER
You must return false from your onsubmit handler in order to cancel the default action. But I would probably clean your code a bit and subscribe to the submit event unobtrusively:
<form id="formID" class="formular" method="POST" action="">
<fieldset>
<legend>Create Desination</legend>
<label>
Designation<br clear="all" />
<input autocomplete="off" value="" class="validate[required,minSize[4]] text-input float_left" type="text" name="name" id="req1" />
<span id="result_span"></span>
</label>
<br clear="all" />
<input id="create_desg" value="Submit" type="button" />
</fieldset>
</form>
You will notice that I have intentionally removed the onkeyup event from the input field. Hammering your server with AJAX requests every time some user hits a key while inside this field won't do any good to your server. If you want to implement this I would recommend you waiting for some input to accumulate and throttle before sending the AJAX request.
and then:
$(function() {
$('#formID').submit(function() {
var text = $('#req1').val();
if(text.length == 0) {
$('#result_span').html('');
}
if(text.length > 3) {
$.ajax({
url: 'designation_ajax.php',
type: 'POST',
data: { data: text },
cache: false,
success: function (response) {
if ($.trim(response) == 'access') {
$('#result_span').html('<div class="green">' + text + ' is available '+'</div>');
$('#create_desg').removeAttr('disabled');
}
else if ($.trim(response) == 'no access') {
$("#result_span").html('<div class="red">' + text + ' is already in use'+'</div>');
$('#create_desg').attr('disabled', 'disabled');
} else {
alert('Sorry, unexpected error. Please try again later.');
}
}
});
} else {
$('#result_span').html('');
}
// return false to prevent the default action
return false;
});
});
Also I would have the designation_ajax.php script return JSON instead of some access and no access strings that you are parsing and trimming in your success callback.

Categories