So I have a contact field which sends an email when submitted, I want to have the javascript alert when complete but am returning issues.
The javascript:
jQuery(document).ready(function() {
$.ajax({
url: './contactengine.php',
type: 'GET',
dataType: 'JSON',
success: function(response) {
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
});
The php:
<?php
$EmailFrom = "emailname#gmail.com";
$EmailTo = "emailto#gmail.com";
$Subject = "new contact from website";
$Name = Trim(stripslashes($_POST['Name']));
$company = Trim(stripslashes($_POST['company']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "company: ";
$Body .= $company;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success)
{
$result = array('success' => true);
}
else
{
$result = array('success' => false, 'message' => 'Something happened');
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
echo json_encode($result);
?>
When I submit the form I get redirected to a page which says the following:
{"success":true}
When I should be staying on the same page and just alerting good.
The problem here is in your script I think, from the behaviour you describe it sounds like your PHP is doing the job.
I've made a few corrections to the ajax call based on the PHP code, try this and see if it helps.
$.ajax({
url: 'contactengine.php', //removed ./ - that's wrong I think
type: 'POST', //you are accessing $_POST not $_GET in the PHP file
data: $('myform').serialize(), //you need to send some data atleast
dataType: 'JSON',
success: function(response) {
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
What I've done is removed ./ from the front of your URL - it should be either nothing, / for the root directory, or ../ for one directory up from the current directory. If the file is in the same directory as your page, keep it like I've done.
I've changed type from GET to POST - you are accessing the PHP $_POST global in your script, so the PHP would have been looking in the wrong place for variables.
Last but not least, I've put some data in. You need to pass in those variables that the PHP expects - so I've used a serialize() call. Replace the jQuery selector so that it will target your form, and it should pass in everything in your form to the PHP.
For more detail on the jQuery ajax function, see here: http://api.jquery.com/jQuery.ajax/
Hope this helps
Where is the data?
Plus You defined the request type as GET, but reading them as POST too. Send datas like this inside and change the request type to post
$.ajax({
url: './contactengine.php',
type: 'POST',
data: { variable1: "value1", .... }
dataType: 'JSON',
success: function(response) {
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Is your code that is calling the ajax function attached to a button on a form? It sounds like you are doing a regular non-ajax form submit right after the ajax call. You can try changing the onsubmit or onclick function that is running the ajax request to return false, and I think that should fix it.
Related
I'm trying to create a form to send mail using ajax and jquery, so I have a php and javascript script however when I try to send mail from my form nothing happens, Do you have a solution ? my ajax script initially allows not to reload the page when the email is sent my data variable retrieves each ID of my form ajax send data back to php script giving a positive or negative answer here it doesn't send any answer, the php script retrieves the data and transmits it directly to the host's email address (ovh)
here my ajax script
$('#send_email').click(function(e){
e.preventDefault();
var data = {
email: $('email').val(),
name: $('name').val(),
objet: $('firstname').val(),
message: $('message').val()
};
$.ajax({
url: "mail.php",
type:'POST',
data: data,
succes: function(data){
$('#js_alert_succes').css({'display' : 'block'});
setTimeout(function(){
$('#js_alert_succes').css({'display' : 'none'});
$('#email').val("");
$('#name').val("");
$('#object').val("");
$('#message').val("");
}, 3000);
},
error: function(data) {
$('#js_alert_danger').css({'display' :'block'});
setTimeout(function(){
$('#js_alert_danger').css({'display' : 'none'});
$('#email').val("");
$('#name').val("");
$('#object').val("");
$('#message').val("");
}, 3000);
}
});
});
and here my php script
<?php
if($_POST){
$firstname = $_POST['firstname'];
$email = $_POST['email'];
$name = $_POST['name'];
$object = $_POST['objet'];
$message = $_POST['message'];
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: $name <$email>\r\nReply-to : $name <$email>\nX-Mailer:PHP";
$subject="$objet";
$destinataire="postmaster#arrowsecurite.com";
$body="$message";
if(mail($destinataire,$subject,$body,$headers)) {
$response['status'] = 'success';
$response['msg'] = 'votre email est envoyé';
} else {
$response['status'] = 'error';
$response['msg'] = 'votre email na pas été envoyé';
}
echo json_encode($response);
}
?>
don't know if you solved your problem, but for debugging press F12 and open Network tab, to see what your PHP code returns after you submit your form. And in PHP code i would recommend return json_encode($response);
So I submit my form with Ajax like so
$("#submitform").click(function(e){
e.preventDefault();
var form_data = $("#contactfrm").serialize();
$.ajax({
type: "POST",
url: "/ltlcreation-new/wordpress/wp-content/themes/LTLCreation/includes/form-handler.php",
data: form_data,
error: function(){
alert("failed");
},
success: function(json_data){
console.log(json_data);
alert("success");
},
})
});
In my form-handler.php i catch the from errors
<?php
if(isset($_POST['submit'])) {
//include validation class
include 'validate.class.php';
//assign post data to variables
$name = #($_POST['name']);
$email = #($_POST['email']);
$message = #($_POST['message']);
$phone = #($_POST["phone"]);
//echo $name, $email, $message, $phone;
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($message, "message", 5, 1000);
$v->validateStr($phone, "phone", 11, 13);
if(!$v->hasErrors()) {
$to = "lukelangfield001#googlemail.com";
$subject = "Website contact form ";
$mailbody = $message . "\n" . "from " . $name . "\n" . $phone;
$headers = "From: $email";
mail($to, $subject, $mailbody, $headers);
echo "success";
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
//$nameErr = $v->getError("name");
//$emailErr = $v->getError("email");
//$messageErr = $v->getError("message");
//$phoneErr = $v->getError("phone");
echo $message_text; echo $errors;
$output = array($message_text);
echo json_encode($output);
}//end error check
}// end isset
These errors usually look like something like this
There were 4 errors sending your message!
Name must be at least 3 characters long.
Please enter an Email Address.
Message must be at least 5 characters long.
Phone must be at least 11 characters long.
["There were 4 errors sending your message!\n"]
I've tried to jSon encode the output and the in the success in ajax pull the json data out, however it just keeps returning an empty string like so
(an empty string)
My question is can you send data back from PHP to Ajax, if so I am doing this completely wrong?
You can output anything other than the json string so echo "success"; would make t. Use your debuggers Network response output tab to see that this is properly encoded.
Also don't use
$name = #($_POST['name']);
use instead
$name = isset($_POST['name']) ? $_POST['name'] : '';
If you still have a blank page make sure you have display errors set.
error_reporting(E_ALL);
ini_set('display_errors', 1);
I am an idiot I still had this in my PHP file which means the form wasn't firing or returning a response, silly me, glad i finally figured it out though
if(isset($_POST['submit'])) {
Thanks for the help guys
Here is an example of an Ajax contact form you can use:
Ajax.js
$(document).ready(function(){
$("#btn").click(function(){
var username=$("#name").val();
var email=$("#email").val();
var dis=$("#dis").val();
var process=true;
if(username=="")
process=false;
if(email=="")
process=false;
if(dis=="")
process=false;
if(process){
var dataString="name="+username + "&email="+email+ "&message="+dis;
$("#res").html('<span>Sending...</span><img src="a.gif">');
$.ajax({
url:"b.php",
type:"POST",
data:dataString,
success:function(data){
document.getElementById("name").value='';
document.getElementById("email").value='';
document.getElementById("dis").value='';
$("#res").html(data);
}
});
}else{
alert("fill all fields");
}
});
});
and b.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajax") || die("erro");
if(isset($_POST['name'])){
mysql_real_escape_string(htmlentities($name=$_POST['name']));
mysql_real_escape_string(htmlentities($email=$_POST['email']));
mysql_real_escape_string(htmlentities($message=$_POST['message']));
if(!empty($name) && !empty($email) && !empty($message)){
if(mysql_query("INSERT INTO `users` (name,email,message) VALUES('$name','$email','$message') ")){
echo 'The massage has been send';
}else{
echo mysql_error();
}
}
}
?>
enjoy that....
You have the following:
success: function(json_data){
While json_data is simply nothing. It should be
success: function(data){
I know I can use the form validation plugin with jQuery UI but for the sake of teaching myself some new tricks I'm taking this approach.
I have a jQuery script that posts a form to a PHP script via Ajax. The script then validates the input and sends a JSON encoded string back to the script. At this point, based on the status a validation message should be placed into a modal dialog and then opened to tell the user what happened.
Issue
It seems the script is returning a "null" status. In Chrome's JavaScript console the following line appears after clicking on the submit button of the form:
Uncaught TypeError: Cannot read property 'status' of null
Here's my validate_form.js
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.status > 0){
$("#response").dialog({
autoOpen: false,
modal: true,
height: 240,
width: 320
});
$("#response").dialog("open");
};
}
});
});
});
And here is contact.php
<?php
if(isset($_POST['contact_submit'])){
$name = trim($_POST['contact_name']);
$name = ucwords($name);
$email = trim($_POST['contact_email']);
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim($_POST['contact_notes']);
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("status"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("status"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$to = "info#mydomain.com";
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("status"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("status"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
}
echo json_encode($resp);
?>
UPDATE 1
Adding console.log(dataString); yields the following in the console:
contact_name=Test&contact_email=testaccount%40mydomain.com&contact_dept=general&contact_notes=this+is+a+test+
As you can see it should've failed on the notes not being between 25 and 500 characters and returned the proper error message. Instead I still see the "cannot read property 'status' of (null)"
UPDATE 2
Here is exactly what I see in the JavaScript Console
UPDATE 3
I decided to remove the prevent default and actually post directly to the contact page through a traditional <form> statement that includes the method="post" action="contact.php" to see if the script itself was properly generating the JSON string and it is; here's what it generated on my most recent test:
{"status":4,"message":"Comments must be between 25 and 500 characters"}
So either it's not sending it back to the ajax handler or something else is missing.
UPDATE 4
I modified the script to handle a null value and alert me if no value was passed. So it's obvious now that the script isn't passing a json string back to the ajax call even though in update 3 I've verified that it's echoing one to the screen. I'm at a loss... (Update script above)
UPDATE 5
So I've made some progress. It turns out that the null was being returned because in my PHP script I was checking if the submit button was set and part of the $_POST array. But, because I'm preventing the default action of the form through jQuery it's not being passed. Only the form values that are serialized are being sent in the dataString. So now I'm getting the errors back in the console that I expect but I'm not getting the modal dialog to show up. The drama continues.
Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
As noted you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.
Below i've mentioned some points try this to sort out your problem
1.change your method to get and try.
2.put die() after last echo and check what the exactly output.
So after more hours tweaking, testing, and pulling my hair out, here's the working script.
jQuery
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.err > 0){
var $response = $("<div></div>")
.dialog({
resizable: false,
autoOpen: false,
modal: true,
height: "auto",
width: "auto",
buttons: { "ok": function() { $(this).dialog("close"); } }
});
$response.html("Error:");
$response.html(data.message);
$response.dialog("open");
$(".ui-dialog-titlebar").hide();
};
}
});
});
});
And for the PHP script I had to tweak it slightly as well to process it properly.
<?php
$name = trim(urldecode($_POST['contact_name']));
$name = ucwords($name);
$email = trim(urldecode($_POST['contact_email']));
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim(urldecode($_POST['contact_notes']));
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("err"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($email_pattern, $email)){
$resp = array("err"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("err"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("err"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("err"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("err"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
echo json_encode($resp);
?>
Everything works perfectly, modal alerts and all to the user. Thanks to those who attempted to help!
I'm coding dynamic contact form. The code look like this:
jQuery:
$.ajax({
type: "POST",
url: "sendmail.php",
data: {email: email, message: message, captcha: captcha}
})
.done(function( result ) {
alert(result);
})
PHP:
<?php
session_start();
$email = $_POST['email'];
$message = $_POST['message'];
$captcha = $_POST['captcha'];
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&strtoupper($_SESSION["captcha_code"])==strtoupper($_POST["captcha"]))
{
#mail('mymail#gmail.com', 'Subject', $message, 'From:' . email);
echo "Message successfully sent.";
}
else
{
// change opacity of #error div
}
?>
The problem is how to change opacity of hidden div if wrong captcha code has been entered?
In that case I need to insert this code insid PHP script or somewhere else:
$('#error').css({opacity:'1'});
Remember, that I cannot inject code with echo, because I use alert for information coming back from PHP script.
Commonly I use a div like this:
<div id="error" style="display: none;">ERROR PUT HERE</div>
And with Jquery you can call...
$('#error').show();
To make it visible!
EDIT: I understand what you are doing. I would recommend you use JSON as your data type.
Try the following
PHP
<?php
session_start();
$email = $_POST['email'];
$message = $_POST['message'];
$captcha = $_POST['captcha'];
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&strtoupper($_SESSION["captcha_code"])==strtoupper($_POST["captcha"]))
{
#mail('mymail#gmail.com', 'Subject', $message, 'From:' . email);
echo json_encode(array('success' => true, 'message' => "Message successfully Sent"));
}
else
{
echo json_encode(array('success' => false, 'message' => "(PUT YOUR MESSAGE HERE!)"));
}
?>
Jquery
$.ajax({
type: "POST",
url: "sendmail.php",
dataType: "json"
data: {email: email, message: message, captcha: captcha}
})
.done(function( result ) {
if(result.success) {
alert(result.message);
} else {
$("#error").text(result.message);
$('#error').css({opacity:'1'});
}
})
Add a success part to your jQuery:
success: function(data) {
if(data == 'error'){
$('#error').css({opacity:'1'});
}
}
And in your PHP:
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&strtoupper($_SESSION["captcha_code"])==strtoupper($_POST["captcha"]))
{
#mail('mymail#gmail.com', 'Subject', $message, 'From:' . email);
echo "Message successfully sent.";
}
else
{
echo "error";
}
Suggestion: setting the error with ajax .fail()
$.ajax({
type: "POST",
url: "sendmail.php",
data: {email: email, message: message, captcha: captcha}
})
.done(function( result ) { alert(result); })
.fail(function() { alert("error");});
There a couple ways you can do this. One way is to respond from php with javascript code that can be executed upon load:
<?php
session_start();
$email = $_POST['email'];
$message = $_POST['message'];
$captcha = $_POST['captcha'];
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&strtoupper($_SESSION["captcha_code"])==strtoupper($_POST["captcha"]))
{
#mail('mymail#gmail.com', 'Subject', $message, 'From:' . email);
echo "Message successfully sent.";
}
else
{
// change opacity of #error div
echo "<script type='text/javascript'>";
echo " $('#error').css({opacity:'1'});";
echo "</script>";
}
?>
In this case, your response is some javascript code to be executed when you intend to change the opacity of the error div. However, if you alert the result of the ajax it will type out the entire javascript code in the alert message as well.
Another way is to actually return an error code other than 200 (success) and to check for that specific case:
<?php
session_start();
$email = $_POST['email'];
$message = $_POST['message'];
$captcha = $_POST['captcha'];
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&strtoupper($_SESSION["captcha_code"])==strtoupper($_POST["captcha"]))
{
#mail('mymail#gmail.com', 'Subject', $message, 'From:' . email);
echo "Message successfully sent.";
}
else
{
// change opacity of #error div
header('HTTP/1.1 500 Captcha not entered correctly');
exit();
}
?>
and when you retrieve the ajax error response, check if the error code matches the one you throw (in this case 500) and then set the opacity there.
I posted a similar question earlier, just I did not realize that the code I put had an obvious bug in it (not supplying the data) which I new existed. Now I am redoing it with that because I am still having the problem.
I have this AJAX:
function sendMail(){
$.ajax({
type: "POST",
url: "../prestige-auto/php/sendMail.php",
data: {"message" : $('#contactMessage').html(),
"email" : $('#contactEmail').val(),
"name" : $('#contactName').val()},
success: function(result){
if (result == 'success') {
alert(result);
} else {
alert(result);
}
}
});
};
$('#submitContact').click(function(){
sendMail();
})
and this PHP:
<?php
$trimmed = array_map('trim', $_POST);
$message = $trimmed['message'];
$email = $trimmed['email'];
$name = $trimmed['name'];
if (empty($message)) {
$message = FALSE;
}
if (empty($email)) {
$message = FALSE;
}
if (empty($name)) {
$message = FALSE;
}
if ($message && $email && $name){
$body = "From: $name.\n \n $message";
mail(/*some email*/, 'Website Contact Form Submission', $body, "From: $email");
echo ('success');
}
echo($message.' '.$email.' '.$name);
?>
All the html elements defined exist. When I run it all that returns is a blank alert box (meaning that the PHP script did not print out success). Any idea why it is not sending the mail?
You didn't exit after echoing out the 'success' - PHP hasn't stopped processing yet, so it just continues to the next line, and renders out echo($message.' '.$email.' '.$name); as well.
This means your JS test is comparing success with success$message $email $name, which is always false.
If you want to stop processing, you have two choices: either exit or die (don't do this), or wrap the rest of the code in an else tag, like this:
if ($message && $email && $name){
$body = "From: $name.\n \n $message";
mail(/*some email*/, 'Website Contact Form Submission', $body, "From: $email");
echo ('success');
} else {
echo($message.' '.$email.' '.$name);
}
Also, make sure you don't end your PHP scripts with ?> ! This almost always leads to problems later where the PHP script renders out some unwanted white space at the end, which would also fail.
Don't use array_map('trim', $_POST) http://www.php.net/manual/en/function.trim.php#96246
check ajax response first to see if there is any error occurs.