Ajax form not working (jQuery - PHP) - php

jQuery:
$("#contact-us-form").submit(function () {
var nameVal = $("input[name=name]").val();
var companyVal = $("input[name=company]").val();
var titleVal = $("input[name=title]").val();
var emailVal = $("input[name=email]").val();
var phoneVal = $("input[name=phone]").val();
var messageVal = $("input[name=message]").val();
$.post("mailer.php", {
name: nameVal,
company: companyVal,
title: titleVal,
email: emailVal,
phone: phoneVal,
message: messageVal
}, function (data) {
alert("Data Loaded: " + data);
$('#thanks').show();
});
return false;
});
mailer.php:
<?php
if(isset($_POST['submit'])) {
$to = "admin#domain.com";
$subject = "Inquiry";
$name = $_POST['name'];
$company = $_POST['company'];
$title = $_POST['title'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$body = <<<HEREDOC
From: $name
Company: $company
Title: $title
E-Mail: $email
Phone: $phone \n
Message: $message
HEREDOC;
echo 'success';
mail($to, $subject, $body);
} else {
echo "failure";
}
?>
The data alert on the page returns failure, I don't understand why!
Thanks for your help!

Two things, first the main issue is there is no submit variable you're passing (if there's a submit button it is not serialized like it would be in a normal post), so you have to add it. Also, you can really shorten you code by using .serialize() to serialize the <form> here, like this:
$("#contact-us-form").submit(function () {
$.post("mailer.php", $(this).serialize(), function (data) {
alert("Data Loaded: " + data);
$('#thanks').show();
});
return false;
});
To add your submit variable in there just use .serializeArray() and add it in, do this:
$("#contact-us-form").submit(function () {
var fdata = $(this).serializeArray();
fdata.push({ name: 'submit', value: true });
$.post("mailer.php", fdata, function (data) {
alert("Data Loaded: " + data);
$('#thanks').show();
});
return false;
});

It looks to me as if you're not sending a value for "submit" to mailer.php, so your condition is failing.

Looking at the data you are passing into your mail.php via JS, you have not passed in "submit" which is where you are basing your condition.
I would suggest that you pass in something like:
$.post("mailer.php", {
name: nameVal,
company: companyVal,
title: titleVal,
email: emailVal,
phone: phoneVal,
message: messageVal,
action: "send-email"
}, function (data) {
alert("Data Loaded: " + data);
$('#thanks').show();
});
and in your PHP change the condition to:
if($_POST['action'] == "send-email") {

Related

no response ajax request

I am trying to make a simple login with ajax. The problem i have is that i do not get any response from my request. When I try to use
myurl.com/login.php is_ajax=1&username=test&password=test
I get a succes message back.
$(document).ready(function(){
$("#submit").click(function(){
var form_data = {
usernm: $("#username").val(),
passwd: $("#password").val(),
is_ajax: 1
};
$.ajax({
type:"POST",
url: "myurl.php" ,
data: form_data,
succes: function (response)
{
if (response == 'succes'){
window.location="myurl.html";
}
else{
alert("wrong username password combination")
}
}
});
return false;
});
});
my php:
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$uName = $_REQUEST ['username'];
$pWord = $_REQUEST ['password'];
if($uName == 'test' && $pWord == 'test'){
echo 'succes';
}
else{
echo 'false';
}
}
you should use
$uName = $_REQUEST ['usernm'];
$pWord = $_REQUEST ['passwd'];
INSTEAD of
$uName = $_REQUEST ['username'];
$pWord = $_REQUEST ['password'];
in your php file and change succes to success
Replace succes with success
$.ajax({
type:"POST",
url: "myurl.php" ,
data: form_data,
success: function (response){
if (response == 'success'){
window.location="myurl.html";
}else{
alert("wrong username password combination");
}
}
});
also change the data attribute names
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
If you are doing it with $.ajax, then your datatype is wrong. It must be application/x-www-form-urlencoded.
So please change your JS part to this:
$(document).ready(function(){
$("#submit").click(function(){
var form_data = {
usernm: $("#username").val(),
passwd: $("#password").val(),
is_ajax: 1
};
$.ajax({
type:"application/x-www-form-urlencoded",
url: "myurl.php" ,
data: form_data,
success: function (response)
{
if (response == 'success'){
window.location="myurl.html";
}
else{
alert("wrong username password combination")
}
}
});
return false;
});
});
Or, if you are not sure about the correct MIME type, then just use this jQuery command:
$(document).ready(function(){
$("#submit").click(function(){
var form_data = {
usernm: $("#username").val(),
passwd: $("#password").val(),
is_ajax: 1
};
$.post("myurl.php",
form_data,
function (response)
{
if (response == 'success'){
window.location="myurl.html";
}
else{
alert("wrong username password combination")
}
});
return false;
});
});
And please change also the following lines of your PHP code
$uName = $_REQUEST ['username'];
$pWord = $_REQUEST ['password'];
To this:
$uName = $_REQUEST ['usernm'];
$pWord = $_REQUEST ['passwd'];
Because these are the correct keys, wich you send to your php server file. Also, thereĀ“s no need for defining an "is_ajax" key, because every XMLHttpRequest has set the "X_REQUESTED_WITH" header to "XMLHttpRequest". So, you can request it in your php server part e. g. with:
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
// it was an ajax XHR request!
}

jQuery/Ajax contact form not working

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

Problem with Jquery AJAX and more than 2 variables

I am trying to add a tell a friend section to a website I am making but I am having difficulty trying to send more than 2 variables through a URL with AJAX. This is the code I have at the moment:
jQuery("#tellafriendsubmit").click(function() {
var email = jQuery('#tellafriendemail').val();
var name = jQuery('#tellafriendname').val();
jQuery.ajax({
type: "POST",
url: "http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>&name=name&email="+email,
success: function(msg){
alert('Your tell a friend recommendation has been sent. Thank you for recommending us.');
}
});
});
If I remove the '&name=name' part so that I'm only sending the postname and email address, it works fine but I need to send the name as well so I can write 'Dear $name....'
How can I send the extra 3rd variable? Thanks for any help
Edit:
The part I'm using in the tellafriendprocessor page looks like this:
$email = $_POST['email'];
$post_name = $_GET['postname'];
$name = $_POST['name'];
$to = $email;
$subject = "Example - Tell a friend";
$body = "Dear $name http://www.example.co.uk/ads/$post_name";
if (mail($to, $subject, $body, $headers)) {
} else {
}
You could try sending them as part of the POST request body (using the data property) which will ensure that those values are properly encoded:
var email = jQuery('#tellafriendemail').val();
var name = jQuery('#tellafriendname').val();
jQuery.ajax({
type: 'POST',
url: 'http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>',
data: { name: name, email: email },
success: function(msg) {
alert('Your tell a friend recommendation has been sent. Thank you for recommending us.');
}
});
On the server side make sure you are reading them from the $_POST hash ($_POST["name"] and $_POST["email"]).
you can send your parameters to a page with AJAX by GET and POST method with this piece of code
data: { id : 'id', name : 'name' }, // multiple data sent using ajax
Here is an example
$.ajax({
type:"GET",
cache:false,
url:"welcome.php",
data: { id : 'id', name : 'name' }, // multiple data sent using ajax
success: function (html) {
$('#add').val('data sent sent');
$('#msg').html(html);
}
});
You will need to move name outside the string. And to add more key-value-pairs you just append them to the query string: &key=value
url: "http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>&name="+name+"&email="+email
Try to use object of params like this:
$.post("/tell-a-friend-processor-page/", { name: "John", email: "<?php echo $post_email; ?>", post_name: "<?php echo $post_name; ?>" },
function(data) {
alert("Data Loaded: " + data);
});

How to get the values from a $.ajax using php

I'm trying to use $.ajax to send some values to a php page which then sends an email,
I can't figure out how to get the values from $.ajax in my php file,
any help would be appreciated,
$(function() {
$('form#email input[type=image]').click(function() {
var name = $('form#email #name').val();
var enq = $('form#email #enq').val();
var dataString = 'name=' + name + '&enq=' + enq;
$.ajax({
type:'POST',
url:'email.php',
data:dataString,
success:function() {
$('form#email').fadeOut();
}
});
$('form#email')[0].reset();
return false;
});
});
php file
if (isset($_POST['submit_x'])) {
$name = $_POST['name'];
$enq = $_POST['enq'];
$name = htmlentities($name);
$enq = htmlentities($enq);
//echo $name,$enq;
$to = 'amirkarimian#hotmail.co.uk';
//$to = 'tutor#inspiretuition.co.uk'
$subject = 'Enquiry';
$message = $enq;
mail($to,$subject,$message);
if(!mail) {
echo 'failed to send mail';
}
}
the email doesn't get sent.
if I dont use $.ajax and submit the form normally the email get sent.
thanks
You're checking for a variable you're not submitting, submit_x, you'll need to remove that outer if check. Also, it's better to let jQuery serialize your strings properly (what if there's a & in there?) like this:
$(function() {
$('#email input[type=image]').click(function() {
$.ajax({
type:'POST',
url:'email.php',
data: { name: $('#name').val(), enq: $('#enq').val() }
success:function() {
$('form#email').fadeOut();
}
});
$('#email')[0].reset();
return false;
});
});
Or if the <form> elements have proper name attributes (they should, for graceful degradation) , you can replace data: { name: $('#name').val(), enq: $('#enq').val() }
with data: $('#email').serialize().
try sending 'submit_x' to php :)
You can use a data map to define your data:
var name = $('form#email #name').val();
var enq = $('form#email #enq').val();
$.ajax({
type: 'POST',
url: 'email.php',
dataType: 'html',
data: {
submit_x : 1,
name : name,
enq : enq
},
success: function(html){
$('form#email').fadeOut();
},
error: function(e, xhr) { alert('__a Error: e: ' + e + ', xhr:' + xhr); }
});

Passing a Value from PHP to the SimpleModal Contact Form

What is the simplest way to pass a value from the "index" page to the SimpleModal Demo Contact Form? For example, if a user is logged in and their email address is stored in the variable $email, what is the most straightforward way to have that info available in the Demo Contact Form?
Thank you.
Assuming the values you want are NOT in the form, here's a way to do it.
Update contact.js in the onShow: function:
...
}, function () {
$('#contact-container .contact-loading').fadeIn(200, function () {
var pt = PAGE_TITLE,
aid = ARTILE_ID;
$.ajax({
url: 'data/contact.php',
data: $('#contact-container form').serialize() + '&action=send&page_title=' + pt + '&article_id=' + aid,
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#contact-container .contact-loading').fadeOut(200, function () {
$('#contact-container .contact-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
error: contact.error
});
});
});
...
Then update contact.php in the function smcf_send() function
...
// Set and wordwrap message body
$pt = isset($_POST["page_title"]) ? $_POST["page_title"] : "";
$aid = isset($_POST["article_id"]) ? $_POST["article_id"] : "";
$body = "From: $name\n\n";
$body .= "Page Title: $pt\n";
$body .= "Article ID: $aid\n\n";
$body .= "Message: $message";
$body = wordwrap($body, 70);
...
Obviously you can play around with the details, but that should get you going.
-Eric

Categories