how to exact output in ajax - php

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

Related

Jquery ajax setTimeout after form succes not redirecting?

I tried questions showing up before asking a question didnt have chance to make it work.
it works fine when I add it to mail send success alert, But I dont want to add script in php part.
I am trying to redirect contact page to an another page after form
success and delay a few seconds.
Here is my Jquery ajax :
$(document).ready(function(){
$('#ContactForm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"modules/contact.inc.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html(data.error);
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
$('#ContactForm')[0].reset();
}
}
});
});
});
I tried the folowing setTimeout(); in success function but didnt work:
setTimeout(function() {
window.location.replace("index.php");
},1000);
Then I tried : window.location.replace("index.php"); without setTimeout function didnt work too.
window.location.href
window.location.hostname
window.location
This one works for modal in another page
setTimeout(function() {
window.location.reload();
}, 3000);
These are my tries didnt have a chance, Thanks for any advice and help.
EDIT: Here is php part for data.error contain:
$error = "";
// Validate user name
if(empty($_POST["fname"])){
$error .= "<p class='error'>İsim girmediniz.</p>";
} else {
$name = test_input($_POST["fname"]);
}
// Validate email address
if(empty($_POST["email"])){
$error .= "<p class='error'>E-Posta girmediniz.</p>";
} else{
$email = $_POST["email"];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error .= "<p class='error'>E-Posta doğru formatta değil.</p>";
}
}
// Validate user subject
if(empty($_POST["subject"])){
$error .= "<p class='error'>Konu girmediniz.</p>";
} else {
$subject = test_input($_POST["subject"]);
}
// Validate user message
if(empty($_POST["message"])){
$error .= "<p class='error'>Mesaj girmediniz.</p>";
} else {
$message = test_input($_POST["message"]);
}
// Validate user departman
if(empty($_POST["departmant"])){
$error .= "<p class='error'>departman Seçin.</p>";
} else {
$departman = test_input($_POST["departmant"]);
}
if($error === ''){
require "../PHPMailer/mailer.php";
$mail = new mailSend();
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$name = test_input($_POST["fname"]);
$subject = test_input($_POST["subject"]);
$departman = test_input($_POST["departmant"]);
$message = test_input($_POST["message"]);
$error = $mail->sendMail($email,$name,$subject,$departman,$message);
}else{
$error .= "<p class='error'>Formda bir hata oluştu.</p>";
}
$data = array(
'error' => $error
);
echo json_encode($data);
EDIT : Got it work thanks for answers,
Displaying error causing the problem, $('#result').html(data.error); I changed it to text message instead of success message from php:
$('#result').html('Form successfuly');
$('#ContactForm')[0].reset();
setTimeout(function() {
window.location = 'index.php';
}, 1000);
it works fine.
String.replace() requires two parameters. As written, it will look for the string "index.php" and replace it with nothing. Try adding a regex to match everything and replace with your new URL.
setTimeout(function() {
window.location.replace( /.*/, "index.php");
},1000);
Use the full URL (i.e. https://yourdomain.com/index.php) or write a better regex. For instance, if your domain ends with .com, you could do something like:
setTimeout(function() {
window.location.replace( /\.com\/.*/, ".com/index.php");
},1000);

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.

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.

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