I have a nice looking slideup/slidedown jquery form on my website. It sends the data to the same file to send the email. This works fine:
$(document).ready(function(){
$('div.contact a.submit').click(function() {
var name = $('div.contact input.name').val();
var email = $('div.contact input.email').val();
var message = $('div.contact textarea.message').val();
$('div.contact').slideUp('slow', function() {
$.ajax({
type: "POST",
url: "test.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success: function(msg)
{
$('div.contact').html('<h1>Contact</h1><div class="comment">Success!</div><div class="clear"></div><p class="indent">Thank you, we will be in contact shortly.</p>');
$('div.contact').slideDown('slow');
}//end of success
});//end of ajax
});
});
});
The php at the top of test.php to send the email:
include("expander-b1.0.php");
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
sendmail("admin#site.co.uk", $message, "Contact message from $name", $email);
This is getting my simple mail function from a external file. However, I would like some way to validate the form entry (including email validation), then display the error(s) in the contact dive. I am not that experienced with jQuery or ajax but an unable to get it working with using if statements in my php and echoing the variables in the "success" part of the ajax.
$(document).ready(function(){
$('div.contact a.submit').click(function() {
var name = $('div.contact input.name').val();
var email = $('div.contact input.email').val();
var message = $('div.contact textarea.message').val();
//Email Validation
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(email) == false) {
alert('Invalid Email Address');
return false;
}
//Name and message VALIDATION
//-------- goes here ------------//
$('div.contact').slideUp('slow', function() {
$.ajax({
type: "POST",
url: "test.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success: function(msg)
{
$('div.contact').html('<h1>Contact</h1><div class="comment">Success!</div><div class="clear"></div><p class="indent">Thank you, we will be in contact shortly.</p>');
$('div.contact').slideDown('slow');
}//end of success
});//end of ajax
});
});
});
you need to use mysql_real_escape() to filter evil code in the post and you can use regular expression to check for a valid email. if you google for it you will find a lot of documentation and tutorials about that.
you can also make it easy on yourself and buy (or find a free one) a ready to use validation class -> Codecanyon validation class
and about the success part have a look at this question -> how can i create a success back function?
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
A JQuery-based validation script that works very well to validate and automatically insert error messages if a section of your code fails validation. Simply include files, add jquery (see source of examples for best methods) and add the "required" element to your class names. Should be a perfect solution to your problem....with no crazy math or individual selectors required.
Related
I have a web form, simple HTML / PHP that works by itself but when it is passed onto the template page via the below AJAX call -- the post data is missing on submission. This HAS got to be a param I'm missing below.
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
The request is sent. And upon submission I receive email, everything but the selected post data via form is sent. Below is the PHP.
<?php
$backwheel = $_POST['backwheel'];
$frontwheel = $_POST['frontwheel'];
$form_message = "backwheel:".$backwheel." frontwheel:".$frontwheel." \nMessage: ". " You just recieved a new custom order via your Customizer!"."\nFullCustomURL: ".$_SERVER['HTTP_REFERER'];
mail("email#gmail.com", "Your Website Something", $form_message, "From: Capn Ron (New Order!)" );
if (isset($_POST['submit']))
{
echo "<script>
alert('Thanks for your Order!');
window.location.href='http://www.website.com';
</script>";
}
?>
You're not missing a param. From your code, #toggle3 appears to be button since the click event is bound to it. So, if you try to serialize it, it will certainly return nothing. You have to serialize the surrounding form which is easily achieved by using jQuery's closest() function; i.e.:
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
data: $(this).closest('form').serialize(),
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
I'm getting a weird result from a jQuery ajax request sending form details to a PHP script. The same scripts are used elsewhere problem free. Basically the form is submitted using jQuery.ajax like this:
//if submit button is clicked
$('#form1').submit(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var con_email = $('input[name=con_email]');
var comments = $('textarea[name=comments]');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&con_email=' + con_email.val() + '&comments=' + encodeURIComponent(comments.val());
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process-email/process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function () {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
$('.done').delay(1000).fadeIn('slow');
}
}
});
//cancel the submit button default behaviours
return false;
});
The PHP script works fine, the email is sent and 1 is returned (email sent) but the script stops at: if(html==1). I get this error
html is not defined
As said above exactly the same script works fine somewhere else, but here I get that error and the script is stopped. Can someone please help to understand where there might be the problem?
You have to add the parameter reference:
success: function (html) {
//if process.php returned 1/true (send mail success)
//.....
}
Then you can use this parameter, which will be the response from server.
Check your success funcion, should be like:
success: function (response) {
//if process.php returned 1/true (send mail success)
if (response == "1") {
//hide the form
$('.form').fadeOut('slow');
$('.done').delay(1000).fadeIn('slow');
}
}
It looks like you are not returning the response from the PHP script to the JavaScript function. If you do something like the following for your success function it should get you on the right track:
success: function( html )
{
if(html=='1')
{
[...]
}
}
I trying to use contact form using J Query ,PHP AJAX but here in the below code the form information is gathered and send it to the server using for LOOP and Array of inouts of ofrm is created . i am new to this kind of coding please help me to extract this value in PHP so that i can use this element to add in to my database or send mail contain form inputs .
function signUpClick(){
var form = $("#form_main")[0];
var objData = {};
for(var i=0;i<form.length;i++){
var input = form[i];
objData[input.name] = "";
if(input.className == "writable")
objData[input.name] = input.value;
}
$("#loader").show();
$("#error_message").hide();
//send contact form using ajax
$.ajax({
url: "contact.php",
global: false,
type: "POST",
data:objData,
success: function(response){
$("#loader").hide();
if(response == "__ok__")
showSentMessage();
else
showErrorMessage(response);
},
error:function(){
$("#loader").hide();
showErrorMessage("Can't get the contact form");
}
});
}
On the PHP side you can manage the information as an array:
$objData = json_decode(file_get_contents('php://input'));
$objData will be the PHP array equivalent to the $objData on Javascript
I have a form that requires a physical address. Once the user enters the full address, I have a button that says "Verify address". I want to be able to click that button, trigger an ajax call that will call a file in the server which will get the longitude and latitude of that address, then return to the form with those coordinates, and display a div with them. Dont worry about figuring out the coordinates. Im just trying to figure out the whole ajax call and jquery display upon response from the server. Thanks
So, I did this to have things working:
$(document).ready(function() {
//if verify button is clicked
$('#verify').click(function () {
var address = $('input[name=address]');
var city = $('input[name=city]');
var state = $('input[name=state]');
var zip = $('input[name=zip]');
var country = $('select[name=country]');
//organize the data for the call
var data = 'address=' + address.val() + '&city=' + city.val() + '&state=' + state.val() + '&zip=' + zip.val() + '&country=' + country.val();
//start the ajax
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//alert (html);
if (html!='error') {
//show the pin long and lat form
$('.form2').fadeIn('slow');
} else alert('Error: Your location cannot be found');
}
});
//cancel the submit button default behaviours
return false;
});
});
process.php returns the longitude and latitude back in a variable as: "longitude,latitude". How do I access that data back in the front end so I can populate the form fields with it? Thanks a lot for the great responses.
I hope this is helpful. This would be a generic AJAX call to a php page:
$.ajax({
type: "POST",
url: "scripts/process.php",
data: "type=query¶meter=" + parameter,
success: function (data) { //Called when the information returns
if(data == "success"){
//Success
} else {
//Fail
}
},
error: function () {
//Complete failure
}
});
The jQuery function you need is jQuery.get().
You can find other details here: http://api.jquery.com/category/ajax/
Sorry for the scarce details but you haven't provided source code.
This php/ajax/jquery thing is new to me, but I do have a much better understanding of HTML/CSS.
I'm developing a site [http://vgdesign.net/thc/] and one of the things left to do is program the form to do exactly what I want. To my knowledge it's functioning fine- except I want it to do just one more thing. When the submit button is pressed, and the code passes validation, I would like for a "Thank You" message to be displayed like below and also without refreshing the page.
[http://i.stack.imgur.com/GkMAI.png]
I found a code that should essentially do just that:
$(function() {
$("#send").click(function() {
var name = $("#name");
var email = $("#email");
var comments = $("#comments");
var dataString = 'name='+ name + '&email=' + email + '&comments=' + comments;
if(name=='' || email=='' || comments=='')
{
$('.success').fadeOut(200).hide();
}
else
{
$.ajax({
type: "POST",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
}
});
}
return false;
});
});
This code was taken from http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html
Now I should mention since this doesn't work, this could be disregarded..maybe there's a different way of achieving what I want. I'm just showing where my research has taken me. I have .success defined in my stylesheet and it's at {display:none} but I can't get it to work due to my limited knowledge of the language.
I'm assuming I need to figure out a way to integrate the code above into my validation code so that the message displays right after a validation has succeeded. I used http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/ for the validation tool.
Any help on this would be appreciated. I hope I wasn't too confusing.
Please let me know if I can clarify anything else.
Thanks!
You will want to take a look at http://api.jquery.com/jQuery.post/ which tells you how to use the jQuery API to POST requests and handle the response. It also has some nice examples.
If you are using jQuery 1.5 you can make it really clear to read:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("example.php", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
change this
var name = $("#name");
var email = $("#email");
var comments = $("#comments");
to this
var name = $("#name").val();
var email = $("#email").val();
var comments = $("#comments").val();
you were saving what I am assuming was a form element, not the value entered into the form element.
you can also use the $.post() function instead of the $.ajax() which takes a first value of the remote base url, a second value of an object with your dataString as key, values and the callback function as the third value.
$.post(
'example.html',
{ 'name' : name, 'email' : email, 'comments' : comments},
function(data){
$('.success').fadeIn(200).show();
}
);
the data variable will hold your response from the ajax call which it seems like you don't need right now. But for next time ;)