jQuery/Ajax contact form not working - php

I am new to jQuery. I am trying to submit a contact form, and the display a thank you message for feedback. I had a look at the tutorial at NetTuts+.My form is not being submitted. Here is my code:
jQuery
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$('.error').hide();
$("#submitButton").click(function() {
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var companyName = $("#usermessage").val();
if (companyName == "") {
$("label#message_error").show();
$("input#usermessage").focus();
return false;
}
var subject=$("#subject option:selected").text();
var dataString = 'name='+ name + '&email=' + email + '&message=' + companyName;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailer.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("Thank you");
});
}
});
return false;
});
});
</script>
PHP
<?php
$mailTo = 'varma.anirudh12#gmail.com';
$name = htmlspecialchars($_POST['name']);
$mailFrom = htmlspecialchars($_POST['email']);
$subjectNumber = htmlspecialchars($_POST['subject']);
$message_text = htmlspecialchars($_POST['msg']);
switch ($subjectNumber)
{
case 0:
$subject='Sales';
break;
case 1:
$subject='Careers';
break;
case 2:
$subject='Other';
break;
}
$dataString=htmlspecialchars($_POST['dataString']);
//$message = 'From: '.$name.'; Email: '.$mailFrom.' ; Message: '.$message_text;
$sendcon=mail($mailTo, $subject, $message);
if ( isset($_GET["ajax"]) ) {
echo $sendcon ? "success" : "error";
} else {
}
?>
The issue is that on pressing the submit button, nothing happens. There are no errors on the javascript console.
I think that my php is not correct and is not listening to the Ajax data, as the error log of apache says PHP Notice: Undefined index: dataString.
where am i going wrong?
thanks
EDIT: I Am running this on localhost on an ubuntu machine, I have set up the mail server and tested it with a test email

You should try the following:
$.post("mailer.php", { name: "John", email: "jsmith#xyz.com" } );

It would be useful if we could see your form code too. I've put together a tutorial here: http://blog.fraser-hart.co.uk/ajax-contact-form-tutorial/
You can download the files and compare them to what you have come up with. Have a read through and let me know if you've any questions about how anything works and I'll point you in the right direction

Related

retrieve database password from php file using ajax

I have a js file that creates a form to collect clients contact info. When the form is submitted it sends a url string to the database. However the string needs to include a token and password to login to the database. So i need to somehow hide the token and password in a php file and add it to the string when the client hits submit. so far ive been able to get the data from a php file using .get or .ajax, but the js file already uses an .ajax request and i'm not sure how to combine them together. Any ideas? Thank you!
function initPopup() {
// open on load
if (xanadu_settings['show_popup'] == 'open') {
openXanadu();
}
// open on mouse out
else {
$('html > body').mouseleave(function() {
if (!popup_visible) {
openXanadu();
}
});
}
}
// This gets the login string i need to add to the form subit string below
var dataString = 'login';
$.ajax({
type: 'GET',
url: "login.php",
data: {data : dataString},
success: function(data) {
returnedvalue = data;
console.log(data);
}
});
$("#xanadu_wrapper form").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please specify your name",
email: {
required: "We need your email address to contact you",
email: "Your email address must be valid"
}
},
submitHandler: function(form, data) {
var report_url = "http://myLinkToTheAPI";
var submit_data = {
// token: $(form).find('input.token').val(),
// pass: $(form).find('input.pass').val(),
campaignId: $(form).find('input.campaignId').val(),
ipAddress: $(form).find('input#ipAddress').val(),
source: $(form).find('input.source').val(),
name: $(form).find('input.name').val(),
email: $(form).find('input.email').val(),
phone: $(form).find('input.phone').val(),
}
var form_submitted = false;
var submit_data = $(form).serialize();
$.ajax({
type: 'GET',
url: report_url,
data: submit_data,
complete: function() {
if ( ($(form).attr('action') != '') && (form_submitted == false) ) {
$(form)[0].submit();
form_submitted = true;
}
$(form).find('input, button').attr('disabled', '');
//Thank you! We will contact you shortly.
$(form).after('<p class="success-alert">' + xanadu_settings['success_message'] + '</p>');
$(form).next('.success-alert').fadeIn();
console.log(form);
console.log(form_submitted);
if (xanadu_settings['prevent_after_submission'] == 'true') {
setBlockCookie();
}
}
});
setTimeout(function(){
if ( ($(form).attr('action') != '') && (form_submitted == false) ) {
$(form)[0].submit();
form_submitted = true;
}
}, 500);
}
});
Just do your updates / inserts in the AJAX call?
When they hit submit, serializeArray() the form, pass your form data to the receiving page, and handle all database interaction on the server. You should never store database information on the client.

AJAX: return true or false on 'success:'

I have the following AJAX script, but for some reason the var ok it's not returning true or false so the form can continue:
function ajax_call(email,title,url){
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
var ok = true;
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if(response == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
}
});
return ok;
}
HTML:
<form onsubmit="return ajax_call();">
...
</form>
PHP:
<?php
//////....
if(!empty($errors)) {
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
} else { echo 'bien'; }
?>
Everything works good, except for the return value.
Thanks in advance.
Prevent the submit completely, send the ajax request, then if it's good, submit the form.
HTML:
<form id="myform">
...
</form>
JavaScript:
$("#myform").submit(function(e){
// prevent submit
e.preventDefault();
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
context: this,
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if($.trim(response) == 'bien') {
this.submit(); // submit, bypassing jquery bound event
}
else {
$("#ajax_call").html(response);
}
}
});
});
You are returning ok at the end of your function. This is returned before your ajax request is sent and completed.
You cannot rely on the return value of your function, you should do something inside your "success" part. It basically depends on what you want to do with your return value
I'm a complete newbie to jquery but in some of the scripts I've been working on I've had to prefix the 'response' you have.
For instance...
if(response.tiitle == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
Also be aware you have double letters in your "parametros" but I'm sure that was intentional (i.e. tiitle and not title etc).

why does jquery ajax go to the url rather than load it?

What the heck is up with this code?
$(".submit").click(function(){
alert("clicked");
var name = $(".name").val();
var email = $(".email").val();
var comment = $(".comment").val();
var articleId = $(".articleId").val();
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment+ '&articleId=' + articleId;
if(name=='' || comment==''){
alert('Please Give Valid Details');
}
else{
alert('so far so good');
$.ajax({
type: "POST",
url: "../_includes/process.php",
data: dataString,
cache: false,
success: function(){
alert("succes");
$(".updating").fadeIn(400);
}
});
}
});
Everything works until $.ajax finds process.php and instead of reading and executing the code it actually goes to that page in the browser. I tried using return false after the ajax call but then the code in process.php never happens.
here is process.php
<?php
// code to establish connection first
if($_POST){
$name=$_POST['name'];
$name=mysql_real_escape_string($name);
$email=$_POST['email'];
$email=mysql_real_escape_string($email);
$comment=$_POST['comment'];
$comment=mysql_real_escape_string($comment);
$articleId=$_POST['articleId'];
$articleId=mysql_real_escape_string($articleId);
if(!empty($email)){
$lowercase = strtolower($email);
}
$result = mysql_query("INSERT INTO comments(name,email,comment,articleId) VALUES ('$name','$email','$comment','$articleId')");
if($result){
echo "success";
} else {
echo "there were erros" . mysql_error();
}
exit;
?>
Any help would be appreciated.
You have to prevent the default action of your submit button:
$(".submit").click(function(e) {
e.preventDefault();
alert("clicked");
...
});
You need to echo something out from process.php if you want to know it worked ok.
e.g
echo 'success';
exit; // just incase
then in your ajax request
success: function(response){
if (response == 'success') {
alert("success");
$(".updating").fadeIn(400);
}
else {
alert('error');
}
}
even if you aren't echoing out, process.php should still work.
try turning on error reporting if it still isn't working:
error_reporting(E_ALL);
ini_set('display_errors', 'On');

Submitting form via ajax in jquery

i am having some problems with getting my form to submit. It doesnt seem like anything is being send, is their anything wrong with this code as javascripting isn't my strong point...
$("#send").click(function() {
var complete = true;
$('input#name, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#ffffff").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#ffffff");
complete = false;
}
});
if (complete == true){
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = '{"name":"'+name+'","sender":"'+email+'","subject":"'+subject+'","message":"'+message+'"}';
$.ajax({
type:"POST",
url:"contact.php",
data:$.base64.encode(data),
success:function(data){
data = $.parseJSON(data);
if (data.status == "success") {
$.fancybox.close();
}
}
});
}
});
There is also a live version of this in action which can be viewed over at: http://idify.co.uk, thanks :)
You can do it better.
$('form')
.submit(function(event) {
var form = $(this);
$.ajax({
url: '[url here]',
type: 'post',
data: $.base64.encode(form.serialize()), // $.serialize() - it gets all data from your form
dataType: 'json', // function in success callback knows how to parse returned data
success: function(data) {
if (data['status'] == true) {
// your code here
// e.g.
$.fancybox.close();
}
}
});
event.preventDefault();
});
Enjoy! :)
I got an error after submitting:
data is null http://idify.co.uk/javascripts/landing.js Line 25
It looks like the data was sent successfully and there was a response:
{"status":"error","responce":"No token parameter was specified."}
This should help you ensure you've got data in your success callback:
success:function(response) {
if (response) {
var data = $.parseJSON(response);
if (data && data.status == "success") {
$.fancybox.close();
}
} else {
// handle errors
}
}
Haha, thanks guys. I was silly enough not to include the variable that needs to be passed via the php file, got it sorted and it works like a dream, i ended up using the first solution as the form submission one wasnt working for me.

Problem sending data to PHP on an AJAX-driven register form

I'm new to AJAX and I'm creating a register form which sends the data using AJAX.
I followed a tutorial which validates that the input fields are not empty and then sends the values to a PHP file and saves them to a database... and it works. But I'm also trying to integrate an extra script to check if the username is taken.
If I use -only- the script to check the availability of the username, without the tutorial one, it works like a charm. But the problem is when I try to combine both scripts.
Can someone help me out by pointing out my mistake(s)? I've tried many things and they make work only parts of the whole script, but not all of it.
Here's the tutorial working script model:
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phone_error").show();
$("input#phone").focus();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
});
Here's my username check working code:
$(function() {
$('.error').hide();
$(".button").click(function() {
$('.error').hide();
// validate and process form here
var checkdata = username ['value'];
//alert ("usuario guardado =" + checkdata);
$.get("usernameCheck.php", { username: checkdata },
function(data){
//alert("Data Loaded: " + data);
if ( data == 0 )
{
$("label#misuser_error").show();
$("input#username").focus();
return false;
}
});
return false;
});
});
And here's my attempt to combine both:
$(function () {
$('.error').hide();
$(".button").click(function () {
$('.error').hide();
// validate and process form here
var flag = 1;
var username = $("#username").val();
var password = $(" #password").val();
var passwordC = $(" #password_confirm").val();
var type = $(" #type").val();
var name = $("#firstname").val();
var lastname = $(" #lastname").val();
var day = $(" #bdate_day").val();
var month = $(" #bdate_month").val();
var year = $(" #bdate_year").val();
var email = $(" #email").val();
var country = $(" #country").val();
var state = $(" #state").val();
var city = $(" #city").val();
var payment_email = $(" #payment_email").val();
if (username == "") {
$("#username_error").show();
$("#username").focus();
return false;
}
else {
if (password == "") {
$(" #password_error").show();
$(" #password").focus();
return false;
}
else {
if (passwordC == "") {
$(" #password_confirm_error").show();
$(" #password_confirm").focus();
return false;
}
else {
if ( password != passwordC ) {
$(" #password_mismatch_error").show();
$("#password_confirm").focus();
return false;
}
else {
if (type == "") {
$(" #type_error").show();
$(" #type").focus();
return false;
}
else {
if (name == "") {
$("#firstname_error").show();
$("#firstname").focus();
return false;
}
else {
if (lastname == "") {
$(" #lastname_error").show();
$(" #lastname").focus();
return false;
}
else {
if (day == "") {
$(" #bdate_day_error").show();
$(" #bdate_day").focus();
return false;
}
else {
if (month == "") {
$(" #bdate_month_error").show();
$(" #bdate_month").focus();
return false;
}
else {
if (year == "") {
$(" #bdate_year_error").show();
$(" #bdate_year").focus();
return false;
}
else {
if (email == "") {
$(" #email_error").show();
$(" #email").focus();
return false;
}
else {
if (state == "") {
$("#state_error").show();
$(" #state").focus();
return false;
}
else {
if (city == "") {
$("#city_error").show();
$(" #city").focus();
return false;
}
else {
if (payment_email == "") {
$("#payment_email_error").show();
$(" #payment_email").focus();
return false;
}
else {
var flag = 1;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (flag === 1) {
var checkdata = document.getElementById('username').value;
//alert ("usuario guardado =" + checkdata);
$.get("usernameCheck.php", { username: checkdata },
function(data){
//alert("Data Loaded: " + data);
if (data === 0) {
$("label#misuser_error").show();
$("input#username").focus();
return false;
}
});
}
(function (save) {
//alert ("usuario guardado: " + checkdata);
$.get("insert_user.php", { username: checkdata },
function(sent){
('#userForm').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
});
return false;
});
});
});
Any thoughts, anyone?
I know i might be doing it all the wrong way, but I'm learning PHP/Javascript and AJAX only by taking tutorials. So have some mercy on me.
Thank you so much in advance for your help.
Okay I'll be honest - I did not read every line of your code. But I've done this kind of thing over and over, and I can tell you a few things that will prevent you from going wrong.
when creating your "datastring" try and use jquery's serialize method. Also know that you can send your data as an object, not necessarily as a string. jquery will convert the object into "?a=b&c=d" for for you.
when validating, dont do this sort of "if else if". Do it the jquery way - use a plugin, or write your own. It will make your code much easier to read
use firebug. on ajax return, console.log your returned data to see what your PHP has to say about your request.
when doing a separate "username available" check, dont for get the same check in "insert user" - race conditions happen, plan for them.
check your syntax, and check if your methods are getting called. Firebug will help you there as well.
Uh. Not talking about your AJAX request, but best practices usually say that more than 3 nested 'if' is no good. Use something like this instead :
var fields = ['username', 'password', 'password_confirm', ... ];
var length = fields.length;
for (var i=0; i<length; i++) {
if ($('#' + fields[i]).val() == "") {
$('#' + fields[i] + '_error').show();
$('#' + fields[i]).focus();
}
}
Also, your $(".error").hide() at your third line is useless.
Finally, I guess the not working part is your anonymous (function (save).... This function is never executed. Add (); at the end to have it executed.
Edit : the answer below shows a better way for your AJAX part.
First, I think you're creating an unnecessary headache for yourself by structuring your validation code the way that you are. Remember, return false makes execution leave the function, so you don't need the deeply-nested if-else structure you've got.
Rather than this:
if(test) {
// fail
} else {
// second test
}
Use something like this
if(test) {
// fail
}
if(test2) {
// fail
}
// success
This is safe to do because the "fail" code, by returning false, will prevent execution from reaching the "success" code later on.
Here's a modified version of your script. NOTE: I removed a lot of your validation checks, and then added just two checks back so you could see the kind of pattern I'm recommending; you will want to add back in all the other necessary tests.
$(function () {
$('.error').hide();
$(".button").click(function () {
$('.error').hide();
// validate and process form here
var flag = 1;
var username = $("#username").val();
var password = $(" #password").val();
var passwordC = $(" #password_confirm").val();
var type = $(" #type").val();
var name = $("#firstname").val();
var lastname = $(" #lastname").val();
var day = $(" #bdate_day").val();
var month = $(" #bdate_month").val();
var year = $(" #bdate_year").val();
var email = $(" #email").val();
var country = $(" #country").val();
var state = $(" #state").val();
var city = $(" #city").val();
var payment_email = $(" #payment_email").val();
if(!username.length) {
$("username_error").show();
$("username").focus();
return false;
}
if(!password.length) {
$("#password_error").show();
$("#password").focus();
return false;
}
// ... other checks
var checkdata = $("username").val();
$.get("usernameCheck.php", { username: checkdata }, function(data) {
if(data === 0) {
$("label#misuser_error").show();
$("#username").focus();
return false;
}
// DO SAVE HERE
$.post("insert_user.php", { username: checkdata }, function(sent){
('#userForm').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
});
});
});
});
One more note: requests that change state on the server are supposed to be POSTs, not GETs. My sample code above indicates that.

Categories