Send data from php back to Ajax - php

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

Related

no response from my contact form script ajax php jquery

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

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")
}
});
});

jQuery Post via Ajax to PHP Validation Script

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!

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.

Strange jQuery AJAX success function behaviour

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');
}
}
});

Categories