Strange jQuery AJAX success function behaviour - php

I have a PHP contact form that I'm using with jQuery's AJAX method, but I'm getting very strange results with the "success:" function.
Here's the PHP contact form:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$message = $_POST['message'];
$msg = "Name: $name\n";
$msg .= "Email: $email\n";
$msg .= "Number: $number\n\n";
$msg .= "$message\n";
$recipient = "[recipients here]";
$subject = "Contact Us - $name";
$mailheaders = "From:$email";
$success = mail($recipient, $subject, $msg, $mailheaders);
if ($success) {
echo ('Correct');
} else {
echo ('Failed');
}
header("Location: [website address here]");
?>
Here's the jQuery AJAX method:
$("#contact-form").submit(function (event) {
$.ajax({
type: "POST",
url: '/lib/mailer.php',
data: {
name: $("#name").val(),
email: $("#email").val(),
number: $("#number").val(),
message: $("#message").val()
},
success: function (data) {
//$("#contact-form")[0].reset();
alert(data);
if(data === 'Correct') {
alert('Data is correct');
}
else if (data !== 'Correct') {
alert('Data is not equal to correct');
}
else {
alert('Else statement');
}
}
});
event.preventDefault();
return false;
});
Now, when I fill in the form and click submit, the PHP receives the right data and successfully sends the email, and echo's "Correct". An alert pops up saying "Correct". But then, instead of the next alert being "Data is correct", it is "Data is not equal to correct".
I have no idea what's going on here for that to happen. I'm assuming I must be making a really stupid mistake somewhere but can't seem to figure it out.

It is not matching the word.
Use
if($.trim(data) == 'Correct')
Hope it will help.

You can not redirect from ajax call. If you are using header function it will print many header data in ajax success.
Header data is the Strange Result you are getting ...
remove header("Location: [website address here]");
And if you want to redirect after success, do it like this in ajax success block
if (data == "Correct") {
window.location = '[website addresss here]';
}

Remove header("Location: [website address here]") from your mailer.php page
And
$.ajax({
type: "POST",
url: '/lib/mailer.php',
data: {
name: $("#name").val(),
email: $("#email").val(),
number: $("#number").val(),
message: $("#message").val()
},
async:false, // <---- Add this fella here
success: function (data) {
//$("#contact-form")[0].reset();
alert(data);
if(data === 'Correct') {
alert('Data is correct');
}
else if (data != 'Correct') {
alert('Data is not equal to correct');
}
else {
alert('Else statement');
}
}
});

Related

jquery ajax returning true but not display proper message in php

I have the following code writing in ajax which sent a request to the back-end
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
//alert(msg);
if (msg == 'sent') {
alert("success");
$('#errormessage').html('<div class="alert alert-success">Email sent successfully.</div>');
$('.contactForm').find("input, textarea").val("");
}else if (msg == 'saved') {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html('<div class="alert alert-warning">Email couldn\'t be sent but not too worry we got it in our database. We will get back to you.</div>');
$('.contactForm').find("input, textarea").val("");
}
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
php code
$to_email = $set['Email'];
$headers = "From: ". $email;
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($email);
if ($secure_check == false) {
echo "Invalid input";
} else { //send email
$query = mysqli_query($mysqli,"INSERT INTO emails(name,email,subject,message)VALUES('$name','$email','$sub','$msg')");
$mail = mail($to_email,$sub,$msg,$headers);
if($query and $mail){
echo 'sent';
}else if($query and !$mail){
echo 'saved';
}else{
echo $mysqli->error;
}
}
If I send an email it successfully executed with the insertion. The issue I am facing is that ajax is not printing out the right message. It only execute the else part which displayed sent
This part of the code is not exected:
if (msg == 'sent') {
alert("success");
$('#errormessage').html('<div class="alert alert-success">Email sent successfully.
</div>');
$('.contactForm').find("input, textarea").val("");
}
instead, this is displayed with just sent message
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
The issue is most likely because you're returning a text-based response and there is whitespace around the value so msg == 'sent' is never true.
To fix this you could simply call trim() to remove the whitespace:
if (msg.trim() == 'sent') {
// your code...
}
Alternatively you can change your PHP to return a serialised data structure, such as JSON or XML, to avoid this problem. I would suggest doing this.

how to exact output in ajax

My code is working well but problem in output. I don't get exact output that i want.
$("#search_traveller_button").click(function(){
$.ajax({
url: "index.php?act=checkSessionUser",
type: "POST",
cache: false,
success: function(data){
console.log(data);
},
error:function(){
console.log("Error: Unknown Error");
}
});
});
PHP code:
<?php
if(isset($_SESSION['userId'])) {
echo "1";
} else {
echo "0";
}
?>
output in success gives also html code, why?
0 </div>
<footer class="nav navbar-inverse">
...........
</footer>
</body>
</html>
I want in my output only 0 in a variable, not html code.
The problem is with your php code here's an example php code. You need to encode as JSON this lets jQuery .success or .fail have a JSON response as a callback.
What I am doing is I have a php file and a js file.
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$nospace_name = trim($_POST['name']);
$nospace_email = trim($_POST['email']);
$nospace_message = trim($_POST['message']);
if (empty($nospace_name))
$errors['name'] = "Name field is required.";
if (empty($nospace_email))
$errors['email'] = "Email field is required.";
if (empty($nospace_message))
$errors['message'] = "I would love to see your message.";
if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
$errors['bad_email'] = "Please enter a valid email address";
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// if there are no errors process our form, then return a message
// prepare message to be sent
$to = "me#example.com";
$subject = "Website Contact Form: ".$name;
// build the message
$message = "Name: ".$name."\n\n";
$message .= "Email: ".$email."\n\n";
$message .= "Message: ".$msg;
// send it
$mailSent = mail($to, $subject, $message, $headers);
// check if mail was sent successfully
if (!$mailSent) {
$errors['unknown_error'] = "Something went wrong...Please try again later";
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
}
}
// return all our data to an AJAX call
echo json_encode($data);
?>
JS
$(function() {
$("#contactForm").submit(function(e) {
$.ajax({
type: 'POST',
url: 'contact.php',
data: $(this).serialize(),
dataType: "json"
})
.done(function(msg) {
if (msg.success == true) {
response = '<div class="success">' + msg.message + '</div>';
$contactform.hide();
}
else {
response = '<div class="error">' + msg.errors + '</div>';
}
// Show response message.
$("#contactForm").prepend(response);
})
e.preventDefault();
});
});
Because the php is successful in returning a result.
The error would be triggered if the php failed to return.
If you want your Ajax handler to do something different if not logged in either specify in the Ajax handler (not recommended) or do it on the server side (in the php) returning what you want if they are not authenticated.
$("#search_traveller_button").click(function(){
$.ajax({
url: "index.php?act=checkSessionUser",
type: "POST",
cache: false,
success: function(data){
if (data==1){
console.log ("yeah it worked")
}else {
console.log ("error")
}
});
});

Send data from php back to Ajax

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){

Checking captcha with jQuery and PHP

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.

How to hide a email form when it gets response from JSON

I am trying to create an email form with the fields validation, but I'm having trouble with my jQuery script. The script gets message response from a PHP script where I use json_encode(). When PHP response appears, the email form should disappear and reappear in the case that the it gets an error or definitely disappear in the case that email is sent.
Can someone help me please? I don't understand where I made a mistake. Thank you.
p.s. Sorry for my English, it's a bit rusty.
JavaScript:
jQuery(document).ready(function(){
jQuery("#contactform").submit(function(){
jQuery.ajax({
type: "POST",
url: "email.php",
data: jQuery("#contactform").serialize(),
dataType: "json",
success: function(msg){
jQuery("#load").fadeIn();
jQuery("#contactform").hide();
jQuery("#result").removeClass('error');
jQuery("#result").addClass('success');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
},
error: function(){
jQuery("#result").removeClass('success');
jQuery("#result").addClass('error');
jQuery("#result").html("There was an error submitting the form. Please try again.");
}
});
return false;
}); });
PHP:
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
include ('lang.php');
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['message'];
if ((isset($_POST['name']) && !empty($_POST['name'])) &&
(isset($_POST['email']) && !empty($_POST['email'])) &&
(isset($_POST['message']) && !empty($_POST['message']))) {
$email_exp = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
if(preg_match($email_exp,$email)) {
// Send Email
$to = ' ';
$subject = ' ';
$message = " $comment ";
$headers = "From: " . $email . "\r\n";
'Reply-To: noreply# localhost' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
$lang['status'] = 'success';
$lang['message'] = $lang['sendmail'];
$lang['message'];
} else {
$lang['status'] = 'error';
$lang['message'] = $lang['errormail'];
$lang['message'];
}
} else {
$lang['error'] = 'error';
$lang['message'] = $lang['errorform'];
$lang['message'];
}
//send the response back
echo json_encode($lang);
?>
Maybe something like this?
jQuery.ajax({
type: "POST",
url: "email.php",
data: jQuery("#contactform").serialize(),
dataType: "json",
success: function(msg){
if (msg == success) {
jQuery("#load").fadeIn();
jQuery("#contactform").hide();
jQuery("#result").removeClass('error');
jQuery("#result").addClass('success');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
} else {
jQuery("#load").fadeIn();
jQuery("#contactform").show();
jQuery("#result").removeClass('error');
jQuery("#result").addClass('success');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
}
}
)};
Hi, thank you for your reply. I just solved my problem for myself!
It works, but I'm sure that my code might be improved. Please let me know if you see any mistake or if you have advices to give me. Thank you!
jQuery(document).ready(function(){
jQuery("#contactform").submit(function(){
jQuery(this).fadeOut();
jQuery("#load").fadeIn();
jQuery.ajax({
type: "POST",
url: "email.php",
data: jQuery("#contactform").serialize(),
dataType: "json",
success: function(msg){
if (msg.status == 'success') {
jQuery("#load").hide();
jQuery("#result").removeClass('error');
jQuery("#result").addClass('success');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
} else {
jQuery("#load").hide();
jQuery("#contactform").fadeIn();
jQuery("#result").removeClass('success');
jQuery("#result").addClass('error');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
}
},
error: function(){
jQuery("#result").removeClass('success');
jQuery("#result").addClass('error');
jQuery("#result").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
I would imagine that you could call a jQuery getJSON() call.
This might work, though you'll probably have to update your version of jQuery if you're still using the jQuery(selector) nomenclature.
$(document).ready(function(){
$.getJSON('email.php', $('#contactform').serialize(), function(data){
// This part completely depends on the format of your returned data.
// I personally would return error codes.
// Maybe something like this.
if(data.status==='error'){
$('#contactform').hide();
setTimeout(function(){$('#contactform').show()}, 1000);
}else if(data.status==='success'){
$('#contactform').hide();
}
});
});

Categories