This has probably been answered already, but I can't seem to find a solution. I'm pretty sure I've been all over the internet.
I'm trying to send a mail from a form using AJAX. The AJAX script seems to be working fine. Here's the code:
$("#order").submit(function(e) {
e.preventDefault();
$(".loading-text").fadeIn("500");
var title = $("input#title").val();
var price = $("input#price").val();
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var address = $("input#address").val();
var urgency = $("input#urgency").val();
$.ajax({
url: "assets/order.php",
type: "POST",
dataType: "json",
data: {
title: title,
price: price,
name: name,
email: email,
phone: phone,
address: address,
urgency: urgency
},
cache: false,
processData: false,
success: function(data) {
$(".loading-text").fadeOut("300");
$(".success-text").fadeIn("500").append(data);
},
error: function(data) {
$(".loading-text").fadeOut("300");
$(".failure-text").fadeIn("500").append(data);
}
});
});
It returns undefined_index for all the variables however. Here's the PHP script:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$title = htmlspecialchars($_POST['title']);
$price = htmlspecialchars($_POST['price']);
$phone = htmlspecialchars($_POST['phone']);
$address = htmlspecialchars($_POST['address']);
$urgency = htmlspecialchars($_POST['urgency']);
$to1 = "jerryasih#gmail.com";
$to2 = "shalomdickson#yahoo.com";
$subject = "New order received!";
$msg_stalker = "Hello STALKER! New order received.\n\n"."Here are the details:\n"."Name: $name\n\nAddress: $address\n\nEmail: $email\n\nPhone number: $phone\n\nItem: $title\n\nPrice: $price\n\nThis customer needs their service/product in $urgency hours.";
$msg_owner = "Hello! Your store on STALKER! has a new order.\n\n"."Details:\n"."Item: $title\n\nPrice: $price\n\nThis customer needs their service/product in $urgency hours."."You may contact us on hoodstalker#yahoo.com if item is unavailable or for any other query.\n\nExpect us soon.\n\nWe've got your back! ;)";
$from = "Order form at (stores.neighbourhoodstalker.com)";
if (empty($name) || empty($address) || empty($phone)) {
http_response_code(400);
echo "Error! Please check that all required fields have been filled and try again.";
exit;
}
if(mail($to1, $subject, $msg_stalker, 'From: '.$from) && mail($to2, $subject, $msg_owner, 'From: '.$from)) {
http_response_code(200);
echo "Order placed successfully.";
}
else {
http_response_code(500);
echo "Something went wrong. Check your internet connection and try again.";
}
}
else {
http_response_code(403);
echo "There was a problem with your submission. Please try again.";
}
?>
I'm not sure where the problem is now because I used a similar code for a file uploader and it worked perfectly.
The problem is because of this setting in AJAX,
processData: false,
From the documentation,
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
Since you're not sending any DOMDocument or non-processed data, remove this setting processData: false from your AJAX request.
You're using wrong dataType. Use dataType: "json".
http://api.jquery.com/jquery.ajax/
Related
I'm having problems figuring out what is wrong with my json. I used php's json_encode.So, on every page I have the some form which need be sent on each page to different email address. However, if I comment jQuery file, then the form is submitted correctly, all data inserted into database correctly, and in place of jQuery AJAX response I get valid JSON, like
{"response":"success","content":{"3":"Thanks John Doe! Your message is successfully sent to owner of property Hotel Milano!"}}
If I want to read and process this data with jQuery instead of get valid response I get just empty [] I was try a lot of options and so if I add JSON_FORCE_OBJECT instead of get empty [] I get empty {}. However if I write json data which need to encode after closing tag for if (is_array($emails) && count($emails) > 0) { just then json data it's encoded correctly and when a form is submitted I get valid response, but in this case form isn't sent and data isn't inserted into db. Bellow is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// define variables and set to empty values
$fname = $tel = $email_address_id = "";
$error = false;
$response = [];
//Load the config file
$dbHost = "localhost";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "booking";
$dbCharset = "utf8";
try {
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$response['response'] = 'error';
$response['errors'][] = $e->getMessage();
echo json_encode($response);
die();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['submit'])) {
//print_r($_POST);
$fname = $_POST['fname'];
$tel = $_POST['tel'];
if (empty($fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can not be empty!';
} else {
if (!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can contain just letters and white space!';
}
}
if (empty($tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can not be empty!";
} else {
if (!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can contain from 9 to 15 numbers!";
}
}
if (!$error) {
// Instantiate a NEW email
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret.com';
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Username = 'booking#secret.com';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->setFrom('booking#secret.com');
$mail->clearAddresses();
$mail->Subject = "New message from secret.com";
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM booking.owners_email INNER JOIN booking.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1, $pages_id);
$dbstmt->execute();
//var_dump($dbstmt);
$emails = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
if (is_array($emails) && count($emails) > 0) {
foreach ($emails as $email) {
//var_dump($email['email_address']);
$mail->addAddress($email['email_address']);
$body = "<p>Dear {$email['owner_name']}, <br>" . "You just received a message from <a href='https://www.secret-booking.com'>secret-booking.com</a><br>The details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "</p>";
$mail->Body = $body;
if ($mail->send()) {
$mail = "INSERT INTO booking.contact_owner (fname, tel, email_address_id) VALUES (:fname, :tel, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'email_address_id' => $email['email_address_id']]);
$response['response'] = "success";
$response['content'][$email['email_address_id']] = "Thanks " . ucwords($fname) . "! Your message is successfully sent to owner of property {$email['owner_property']}!";
}//end if mail send
else {
$response['response'] = "error";
$response['content'][$email['email_address_id']] = "Something went wrong! Try again..." . $mail->ErrorInfo;
}
}//end foreach for email addresses
} //end if for array of emails
/* If use this else for response I allways get this response. Even, if I write JSON for success hier I get it but data isn't sent and isn't inserted into db
else {
$response['response'] = 'error';
$response['error'][] = '$emails is either not an array or is empty'; // jQuery just read this
}//end if else for array of emails
*/
}//end if validation
}//end submit
echo json_encode($response);
}//end REQUEST METHOD = POST
And this is jQuery for submitHanfdler
submitHandler: function (form) {
//Your code for AJAX starts
var formData = jQuery("#contactOwner").serialize();
console.log(formData); //this work
jQuery.ajax({
url: '/classes/Form_process.class.php',
type: 'post',
data: formData,
dataType: 'json',
cache: false,
success: function (response) {
jQuery("#response").text(response['content']);
// debbuger;
console.log(response);
//console.log(response.hasOwnProperty('content'));
},
error: function (response) {
// alert("error");
jQuery("#responseOwner").text("An error occurred");
console.dir("Response: " + response);
}
}); //Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} //submitHandler
Thanks in advance for any kind of your help, any help will be highly appreciated!
I suspect the issue is the dataType: 'json' attribute. This is because the serialize function does not provide json data. See if this works:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: jQuery("#contactOwner").serialize()
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
Alternatively, if you want to use dataType: 'json', you will need to send in json data:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: {
firstName: jQuery("#contactOwner .first-name").val(),
lastName: jQuery("#contactOwner .last-name").val(),
...
}
dataType: 'json',
cache: false,
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
If you add you data using an object as shown above this should work with dataType: 'json'.
I created a simple registration form in php and made validations for user inputs. I gave to each $error[] array a string index. Well in example its like: $error['fn'] I did this because I want to show each validation error next to/below to user input with Ajax json data type. But for some reason only one of the arrays output displays, the other output not.
It should be show the other output below the username input.
How can I display the other output and where am I making a mistake?
<?php
require('../includes/config.php');
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (empty($_POST['fullname'])) {
$error['fn'] = "Please fill this field";
echo json_encode($error);
}
if (! $user->isValidFullname($fullname)){
$error['fn'] = 'Your name must be alphabetical characters';
echo json_encode($error);
}
}
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (empty($_POST['username'])) {
$error['un'] = "Please fill this field";
echo json_encode($error);
}
if (! $user->isValidUsername($username)){
$error['un'] = 'Your username must be at least 3 alphanumeric characters';
echo json_encode($error);
}
if (! $user->isUsernameAlreadyinUse($username)){
$error['un'] = 'This username already in use';
echo json_encode($error);
}
}
?>
<script type="text/javascript">
$(document).ready(function() {
$("#register-form").on("submit", function(e) {
e.preventDefault();
var fullname = $("#fullname").val();
var username = $("#username").val();
$.ajax({
type: "POST",
url: "registercontrol.php",
data: {
fullname: fullname,
username: username
},
dataType: "json",
success: function(result) {
$("#vfullname").html(result['fn']);
$("#vusername").html(result['un']);
}
});
});
});
</script>
Thank you.
after success function kindly add
data = JSON.parse(result);
$("#vfullname").html(data.fn);
$("#vusername").html(data.un);
I'm trying to upload an image with some other variables and on the form submit, do my php code to save the image to the users profile_picture table.
I want to make my image upload in the same form as saving my data changes.
This is a picture of what it looks like so you can have a better understanding :
I did it before where I used the POST method, but for AJAX i'm not sure how to do it.
My Javascript code is (note that this doesn't work, I just tried having a go - It returns Illegal invocation in the console.log) :
<script>
function updateMyAccount() {
var fd = new FormData($("#fileinfo"));
var password = document.getElementById("myAccountNewPassword").value;
var profilePicture = document.getElementById("myAccountNewProfilePic").value;
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
SaveAccountChanges: true,
securePassword_Val: password,
fd
},
success: function(msg){
if(msg == 1) {
update_myAccount_success();
} else {
general_error_forms();
}
},
});
return false;
}
</script>
My PHP code is :
//My account AJAX POST
if(($_POST['SaveAccountChanges']) == true & isset($_POST['securePassword_Val']))
{
$member_config->doUpdateAccountInfo($con);
}
Then my function to upload the image and save it to the database :
function doUpdateAccountInfo($con)
{
//Upload users image to our /uploads directory
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
$save_to_database = ("uploads/" . $_FILES["fileToUpload"]["name"]);
$normalPassword = mysqli_real_escape_string($con, $_POST["securePassword_Val"]);
$pwd = password_hash($normalPassword, PASSWORD_DEFAULT);
$username = $_SESSION["username"];
if(!empty($_FILES['fileToUpload']) & !empty($_POST['securePassword_Val']))
{
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {} else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
$query = "UPDATE users SET password = '$pwd', profile_picture = '$save_to_database' WHERE username='$username'";
$result = mysqli_query($con, $query) or die('error');
echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>password and profile picture</i></b>!</p></div>';
//echo '1';
}
else if (empty($_FILES['fileToUpload']) & empty($_POST['securePassword_Val']))
{
$query = "UPDATE users SET password = '$pwd' WHERE username='$username'";
$result = mysqli_query($con, $query) or die('error');
echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>profile picture</i></b>!</p></div>';
//echo '1';
}
else if (empty($_POST['securePassword_Val']) & !(empty($_FILES['fileToUpload'])))
{
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) { echo 'Successfully uploaded image'; } else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
$query = "UPDATE users SET profile_picture = '$save_to_database' WHERE username='$username'";
$result = mysqli_query($con, $query) or die('error');
echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>password</i></b>!</p></div>';
//echo '1';
}
else if (empty($_POST['securePassword_Val']) & empty($_FILES['fileToUpload']))
{
$result = mysqli_query($con, $query) or die('error');
//echo '<div class="panel -danger"><div class="panel-body"><p>You have failed to update your <b><i>password and profile picture</i></b>!</p></div>';
echo '0';
}
else
{
//echo '<div class="panel -danger"><div class="panel-body"><p>An error occured!</p></div>';
echo '0';
}
}
I have looked a the link that was posted and now have this code :
<script>
function updateMyAccount() {
var fdata = new FormData($("#data"));
fdata.append("securePassword_Val",$("#myAccountNewPassword").val());
fdata.append("SaveAccountChanges",true);
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data:
//SaveAccountChanges: true,
//securePassword_Val: password,
fdata
,
async: false,
success: function(msg){
if(msg == 1) {
update_myAccount_success();
} else {
general_error_forms();
}
},
cache: false,
contentType: false,
processData: false
});
return false;
}
</script>
How would I go about making the image upload through this method ?
Normally, I wouldn't answer this question because it gets asked many times. But I see few issues in your code, so I'm going to make an attempt.
JavaScript
(1) Ensure that you have included jQuery script
(2) Ensure that you have a form element (preferrably give it an ID attribute e.g. myform for referencing) and all your inputs have name attributes.
(3) Pass the native form element (not jQuery object) into FormData constructor. This will allow you to pass all the input elements with name attributes from your form -- so you don't need to manually add them. Exception is your SaveAccountChanges field that you want to pass, here you need to use FormData.append().
(4) Set $.ajax data option to only the FormData object. Set contentType and processData options to false.
function updateMyAccount() {
// document.getElementById('myform') === $("#myform")[0] === myform
var fd = new FormData($("#myform")[0]);
fd.append('SaveAccountChanges', true);
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: fd,
contentType: false,
processData: false,
success: function(msg){
if(msg == 1) {
update_myAccount_success();
} else {
general_error_forms();
}
},
});
return false;
}
And this should be the minimum that you need on the client-side. When debugging, use your browser's web tools.
PHP
(6) Turn on your PHP error reporting.
(7) Learn the difference between && and & -- they are not the same.
(8) Because you are uploading using FormData, you need a stronger validation for your upload fields. $_FILES['fileToUpload'] will not be empty even when you don't select a file.
I'm submitting a form using MySQL command inside a PHP file. I'm able to insert the data without any problem.
However, I also, at the same time, want to display the user a "Thank you message" on the same page so that he/she knows that the data has been successfully registered. On the other hand I could also display a sorry message in case of any error.
Therein lies my problem. I've written some lines in Javascript to display the message in the same page. However, I'm stuck on what (and how) should I check for success and failure.
I'm attaching my code below.
Can you please help me on this with your ideas?
Thanks
AB
HTML Form tag:
<form id="info-form" method="POST" action="form-submit.php">
form-submit.php:
<?php
require("database-connect.php");
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
return false;
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
submit-logic.js:
$(function ()
{
$('form').submit(function (e)
{
e.preventDefault();
if(e.target === document.getElementById("info-form"))
{
$.ajax(
{
type:this.method,
url:this.action,
data: $('#info-form').serialize(),
dataType: 'json',
success: function(response)
{
console.log(response);
if(response.result == 'true')
{
document.getElementById("thankyou_info").style.display = "inline";
$('#please_wait_info').hide();
document.getElementById("info-form").reset();
}
else
{
document.getElementById("thankyou_info").style.display = "none";
document.getElementById("sorry_info").style.display = "inline";
$('#please_wait_info').hide();
}
}
}
)};
});
}
Per documentation: http://api.jquery.com/jquery.ajax/
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
You are explicitly setting this to json but then returning a string. You should be returning json like you are telling the ajax script to expect.
<?php
require("database-connect.php");
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die(json_encode(array('result' => false, 'message' => 'Could not enter data: ' . mysql_error()));
}
echo json_encode(array('result' => true, 'message' => 'Entered data successfully'));
mysql_close($conn);
?>
I also added code to sanitize your strings, although mysql_* is deprecated and it would be better to upgrade to mysqli or PDO. Without sanitization, users can hack your database..
Nevertheless, returning json properly will ensure that your response in success: function(response) is an object, and response.result will be returned as expected, and you can use response.message to display the message where you want.
Why is PHP adding a line break to my simple AJAX result? This couldn't be much easier. Am I missing something?
Here is my JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
alert(data);
if(data === "exists"){
alert(data);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is my php:
<?php
include_once("db_connect.php");
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
if($rowCnt == 0){
echo trim('new');
}else{
echo trim('exists');
}
For whatever reason, my result data string is returned as /r/nexists, rather than just exists, and thus never gets into my if block, even if I only use == to evaluate the condition. I tried adding the trim() function as you can see without result. Your help is much appreciated as this has taken me hours of time for a stupid if condition.
Check if there is an "empty" space after or before the php question marks, those line-breaks are also represented as part of the response.
I mean here
<?php?>
And here
I found a solution but I still do not like or understand what is happening. You should be able to return a simple string for a result. Anyway, what I did was to just echo the number of rows returned from the DB to my ajax success function. I then checked if the result was > 0 on the client and am finally in my IF block. Here is what I did:
JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
console.log(data);
if(data > 0){
console.log("HURRAY! I'm in my IF");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is the PHP:
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
echo $rowCnt;
?>
This works, and is actually maybe alittle more elegant, but you should be able to return a string without issue.
John