we're using WordPress for our Website. I was asked to add a function to our newsletter subscription that automatically sends an E-Mail to a specific address that is depending on the selected value of the form. Working fine from code side and on my local host, but when implementing it into the live wordpress system i ran across an error. The Situation :
jQuery.AJAX script posts form data to a file "mail.php" in the wp-content folder. the AJAX success function then submits the original form (because the data also needs to be posted to a provider that manages our newsletter subscriptions). This worked fine on a non-wordpress local host.
After searching through javascript console and firebug i realized that after the script tries to post data to the email.php the server returns a 500 Error as if it didnt allow the post to this file.
I did not register the mail.php or the script in any way but added it to the html code behind the e-mail form. Did i miss something here?
Thanks!
<script>
jQuery(document).ready(function() {
jQuery( "#subscribeform" ).one( "submit", function(event) {
event.preventDefault();
var pFirstName = jQuery("#firstname").val();
var pLastName = jQuery("#name").val();
var pSalutation = jQuery("#salutation").val();
var peMail = jQuery("#email").val();
var pDOB = jQuery("#dob").val();
var pMailTo = jQuery("#shop").val();
var data = {
firstname: pFirstName,
name: pLastName,
salutation: pSalutation,
email: peMail,
dob: pDOB,
mailto: pMailTo
};
$.ajax({
type: "POST",
url: "/cms/mail.php",
data: data,
success: function(){
jQuery('#subscribeform').attr('action', "theExternalProviderURL").submit();
}
});
});
});
</script>
mail.php
<?php
include_once '/cms/phpmailer/PHPMailerAutoload.php';
if($_POST){
$shopname = $_POST['mailto'];
$salutation = $_POST['salutation'];
$firstname = $_POST['firstname'];
$name = $_POST['name'];
$email = $_POST['email'];
$dateofbirth = $_POST['dob'];
$recipient = $_POST['mailto'];
switch ($recipient) {
case "Value1":
$recipient = "mail1#mail.com";
break;
case "Value2":
$recipient = "mail2#mail.com";
break;
default:
$recipient = "admin#mail.com";
}
$oMailer = new PHPMailer;
$oMailer->CharSet = 'UTF-8';
$oMailer->isSMTP();
$oMailer->Host = 'mail.host.com';
$oMailer->Username = 'xxx';
$oMailer->Password = 'xxx';
$oMailer->SMTPAuth = true;
$oMailer->SMTPSecure = 'tls';
$oMailer->Port = 587;
$oMailer->From = 'email#email.com';
$oMailer->FromName = 'From Email';
$oMailer->addAddress('adress#adress.com');
$oMailer->isHTML( true );
$oMailer->Subject = 'E-Mail Subject';
$oMailer->Body = 'Text Text Text';
$oMailer->AltBody = strip_tags( $oMailer->Body );
$oMailer->SMTPDebug = 2;
if ( !$oMailer->send() ) {
echo "Error sending Mail: " . $oMailer->ErrorInfo;
exit;
}
echo 'Successfully sent mail to ' . $recipient . ' Shop';
}
?>
As mentioned earlier, HTTP 500 comes from problem in your server/mail.php code. Moreover, there is a special hook to work with ajax requests in WP, see here: https://codex.wordpress.org/AJAX_in_Plugins
What you need is something like:
var data = {data:yourdata, action: "yourajaxaction"};
$.post(ajaxurl,{data: data});
and
add_action( 'wp_ajax_yourajaxaction', 'your_action' );
function your_action() {
include "mail.php";
}
Related
I got a login script (not yet encrypted and all) which posts to a PHP script, this script then returns a result, either that the credentials are correct, that they are wrong or that a user needs to fill in 1 or both of the fields when empty.
After this I want to redirect to a page according to the result (if the credentials are correct). But not of course when it is wrong or when 1 or both of the fields are empty.
How can I check for that in ajax?
This is what I have now in my PHP script:
$conn = new Connection;
$username = $_POST['username'];
$userpassword = $_POST['userpassword'];
if(empty($username) && empty($userpassword)){
echo 'Vul een gebruikersnaam en wachtwoord in';
}else if(empty($username)){
echo 'Vul een gebruikersnaam in';
}else if(empty($userpassword)){
echo 'Vul een wachtwoord in';
}else{
//Both filled in, begin logincode:
$getuser = "SELECT * FROM users WHERE username = '".$conn->real_escape_string($username)."'";
$getusercon = $conn->query($getuser);
$getuser = $getusercon->fetch_assoc();
if($userpassword == $getuser['password']){
if($getuser['rights'] == '1'){
$_SESSION['user'] = 'admin';
$userdata = array(
'userdata' => $_SESSION['user'],
);
echo json_encode($userdata);
}else{
$_SESSION['user'] = 'user';
$userdata = array(
'userdata' => $_SESSION['user'],
);
echo json_encode($userdata);
}
}else{
echo 'Wachtwoord en gebruikersnaam komen niet overeen';
}
}
This is my ajax:
// Login Ajax Code
$( "#content" ).on("submit", "#loginform", function( event ) {
// Stop normal form behaviour
event.preventDefault();
// Retrieve input fields and their values
var $form = $( this ),
$username = $form.find( "input[name='username']" ).val(),
$userpassword = $form.find( "input[name='userpassword']" ).val(),
url = $form.attr( "action" );
// Post above values to the action of the form
var posting = $.post( url, { username: $username, userpassword: $userpassword} );
// Show result in a div
posting.done(function( data ) {
$( "#loginresult" ).empty().slideDown('fast').append( data );
}, "json");
});
I added the last , "json" part to try and get the session content back, which kind of works.
I see this in my loginresult box when I login correctly with an admin account: {"userdata":"admin"}
How can I decode that to use in my ajax code? The problem is I only need to decode it when it's json of course, not when it's a normal message that shows one or both fields are empty. Maybe all responses need to be json?
How can I for example redirect to a certain page when userdata contains admin ?
All the responses must have the same format, JSON in this case.
So, in Javascript, you can do something like:
obj = JSON.parse(data);
Currently I' am setting up a email verification system for my personal site. I (try) to handle this with jQuery and AJAX (code follows). But the problem is that it does not return to the echo 2; in my signup.inc.php so that I can continue working in the AJAX call.
As I understand it the compiler should return to/continue from the point where it was redirected, in this case the send_ver_email($user_email) below and echo 2. What did I get wrong? This is pretty new to me and I don't have so much experience , but I don't not what else to try. Tried moving and merging documents, but nothing works.
The AJAX call in JS:
$.ajax({
type: 'POST',
url: 'include/signup.inc.php',
data: 'user_name=' + user_name +
'&user_email=' + user_email +
'&user_pw=' + user_pw,
dataType: 'html',
success: function (data) {
if (data == 0) { // invalid email
... do something
} else if (data == 1) { // account already exists
... do something
} else if (data == 2) {
**This is where it should land after the successful sign up**
return false;
}
}
});
signup.inc.php works great and stores the data in database, so this is not the problem:
include_once "dbc.inc.php";
include_once "verification.inc.php";
if (isset($_POST)) {
//get posted data;
//select $statement
// error handlers
if (filter_var($user_email, FILTER_VALIDATE_EMAIL) === false) {
echo 0;
exit();
} else if ($statement->rowCount() > 0) {
echo 1;
exit();
} else {
// db entry (works great no problems there)
send_ver_email($user_email);
echo 2;
exit();
}
}
the AJAX receives the 2 and reacts as intended if send_ver_email($user_email) is disabled, so I'am very sure that it has something to do with the structure or the way send() handles things. This function is included in verification.inc.php which includes the whole PHPMailer package. And the Email works too! I get every single mail
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
include_once "../PHPMailer/src/Exception.php";
include_once "../PHPMailer/src/PHPMailer.php";
include_once "../PHPMailer/src/SMTP.php";
function generate_ver_code() {
// ...
}
function send_ver_email ($user_mail) {
$verCode = generate_ver_code();
$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = '.......';
$mail->Password = '........';
$mail->setFrom('........', '.......');
$mail->addAddress('.........', '..........');
$mail->Subject = '...........';
$mail->Body = "......................";
$mail->isHTML(true);
$mail->AltBody = '.........';
$mail->send()
}
I am also very grateful for tips about code style and layout :)
EDIT 1: A different approach:
if($mail->send()) {
echo 2;
exit();
} else {
// some error handling
}
This does not crash, I logged everywhere around it, but the ajax still does not register the echo 2
And another try showed:
if($mail->send()) {
} else {
// some error handling
}
and in signup.inc.php:
send_ver_email($user_email);
--------LOGGED HERE---------
echo 2;
exit();
}
This works fine too... this weirds me out the most. Either I got a really dumb typo somewhere or another newbie mistake (hopefully) or ajax handles this echo calls in a very confusing way.
dataType - delete this one.
Add console.log and open console in Your browser
success: function (data) {
console.log( data );
show Your console, and then You will see why. Maybe an unwanted char or php error
Second thing - there should be if stament like this (I supposed)
if (data == "1") // it is returning string, not integer.
You can also try to use switch case in success.
I'm trying to write a page to make a POST request to a php script and I feel like I've done it right, it's worked everywhere else so it seems but I keep getting a "unidentified error" and it won't work, how can I get this to work?
Javascript:
$(document).ready(function() {
$("#x").click(function() {
var email = $("email").val();
var pass = $("password").val();
var confirmPass = $("confirmPassword").val();
var name = $("name").val();
var question = $("question").val();
var answer = $("answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "*********";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$email = $_POST["email"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$question = $_POST["question"];
$answer = $_POST["answer"];
$sql = "INSERT INTO accounts (accountEmail, accountPassword, accountName, accountQuestion, accountRecover) VALUES ('$email', '$pass', '$name', '$question', '$answer')";
$conn->close();
if(mysql_affected_rows() > 0) {
$response = "Account added successfully!";
}
else {
$response = "Couldn't add account!";
}
$pre = array("Response" => $response);
echo json_encode($pre);
?>
You need to properly use jquery.
For example
var email = $("email").val(); //IS WRONG
Should be (if you have input id="email")
var email = $("#email").val();
If you have only name you can use
var email = $("[name='email']").val();
A bit offtopic:
If you are using form ajax submit consider jquery method serialize https://api.jquery.com/serialize/ for getting all form values (or some jquery ajaxform plugin).
And please! don't make insecure mysql statements. For gods sake use prepared statements.
If you need very basic stuff just use prepared statements or consider https://phpdelusions.net/pdo/pdo_wrapper
Also a small tip: before echo json make json header
<?php
header('Content-type:application/json;charset=utf-8');
I think you are mistaken with your jquery data, they should have identifier like id denoted by '#' and classes denoted by '.', do it this is you have id="name of the field" among the input parameters:
$(document).ready(function() {
$("#x").click(function() {
var email = $("#email").val();
var pass = $("#password").val();
var confirmPass = $("#confirmPassword").val();
var name = $("#name").val();
var question = $("#question").val();
var answer = $("#answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
OR like this is you have class="name of the field" among the input parameters:
$(document).ready(function() {
$("#x").click(function() {
var email = $(".email").val();
var pass = $(".password").val();
var confirmPass = $(".confirmPassword").val();
var name = $(".name").val();
var question = $(".question").val();
var answer = $(".answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
OR if you want to use the name directly follow this:
$(document).ready(function() {
$("#x").click(function() {
var email = $("input[name='email']").val();
var pass = $("input[name='pasword']").val();
var confirmPass = $("input[name='confirmPassword']").val();
var name = $("input[name='name']").val();
var question = $("input[name='question']").val();
var answer = $("input[name='answer']").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
I hope this helps you
There are lots of reasons your code is not working. #AucT and #gentle have addressed your Javascript side issues so I'll focus on PHP. Your query code is:
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "...";
$conn->close();
Notice that:
you never execute you query. $sql is just a string held in memory.
you're mixing mysqli function with mysql_ function (mysql_affected_rows); that won't work
You're inserting POST data directly into your queries, so you are very vulnerable to SQL injection
At the end, you echo JSON, but you haven't told the browser to expect this format
Do this instead:
$conn = new mysqli(...);
//SQL with ? in place of values is safe against SQL injection attacks
$sql = "INSERT INTO accounts (accountEmail, accountPassword,
accountName, accountQuestion, accountRecover) VALUES (?, ?, ?, ?, ?)";
$error = null;
//prepare query and bind params. save any error
$stmt = $conn->prepare($sql);
$stmt->bind_param('sssss',$email,$pass,$name,$question,$answer)
or $error = $stmt->error;
//run query. save any error
if(!$error) $stmt->execute() or $error = $stmt->error;
//error details are in $error
if($error) $response = "Error creating new account";
else $response = "Successfully created new account";
//set content-type header to tell the browser to expect JSON
header('Content-type: application/json');
$pre = ['Response' => $response];
echo json_encode($pre);
I'm having trouble with seemingly simple problem.
Using JQuery i want to POST an array containing 2 items, an email address and email content, to a simple PHP script that mails the customer's concern back to my own server email.
I am receiving the email, but it is blank because either im not encoding or decoding the JSON object correctly or something else.
Javascript:
...
var JSONEmailRequest = new Object();
JSONEmailRequest.emailaddress = $("#emailInput").val();
JSONEmailRequest.content = $("#contentInput").val();
$.post("/email.php", JSON.stringify(JSONEmailRequest), function (data) {
//do stuff
});
...
PHP:
<?php
$POSTJSONObj = json_decode($POST['JSONEmailRequest']);
$email_to = "shawnandrews#saportfolio.ca";
$email_subject = "User enquiry from ".$POSTJSONObj['emailaddress'];
$email_body = $POSTJSONOb j['content'];
$result = mail($email_to,$email_subject,$email_body,"From: ".$email_to);
if(!$result) {
echo false;
} else {
echo true;
}
?>
Don't convert the JSONEmailRequest to JSON. $.post expects the data argument to be either an object or a string in www-form-urlencoded format. So do:
$.post("/email.php", JSONEmailRequest, function(data) {
...
}, "json");
And in the PHP code, use $_POST to get the parameters, and json_encode to send the result back.
<?php
$email_to = "shawnandrews#saportfolio.ca";
$email_subject = "User enquiry from ".$_POST['emailaddress'];
$email_body = $_POST['content'];
$result = mail($email_to,$email_subject,$email_body,"From: ".$email_to);
echo json_encode($result);
I'm having a problem when I'm doing a web-chat page with php and ajax. The problem is that when see the webpage in my browser, in the console apears this mesage:
POST http://subdomain.domain.com/ajax/sms.php 500 (Internal Server Error)
x.ajaxTransport.send # jquery.min.js:6
x.extend.ajax #jquery.min.js:6
doAjax # funcionesChat.js:22onclick # chat:50
And I have no idea why apears that and what I've done wrong in the page...
In my html I have the folowing code:
<button type="button" onclick="doAjax(2)">a</button>
<div class="chat">
<div class="boxChat" id = "sms">
</div>
</div>
In my ajaxfunction.js is the following code:
function doAjax(idOne, idTwo) {
$.ajax({
type: 'POST',
url: 'ajax/sms.php',
data: {idOne: idOne, idTwo: idTwo},
dataType: 'text',
success: function (data) {
$('#sms').html(data);
}
}
And the sms.php contains the following code:
<?php
$db = new PDO('mysql:host=localhost;dbname=XXXX;charset=utf8',
'user', 'password');
stmt = $db->query("SELECT * FROM sms WHERE sender = ".idOne."
AND reciver = ".idTwo.")");
$smss = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($smss as $sms) {
if ($sms["sender"] == idOne){
echo "<p style='text-align: right;'>".$sms["mesage"]."</p>";
}else{
echo "<p style='color: green;''>".$sms["mesage"]."</p>";
}
}
?>
Some one can give me a hand? Thanks a lot in advance.
You mixed JS and PHP syntax up, in sms.php file you have syntax errors.
dollar sign before smtp
idOne instead of $_POST['idOne']
idTwo instead of $_POST['idTwo']
additional bracket at the end of SQL query
line 11, again, idOne instead of $_POST['idOne']
$stmt = $db->query("SELECT * FROM sms WHERE sender = ".$_POST['idOne']."
AND reciver = ".$_POST['idTwo']);
And line 11
if ($sms["sender"] == $_POST['idOne']){ // $_POST['idOne'] instead of idOne
I see a couple of typos here:
stmt = $db->query("SELECT * FROM sms WHERE sender = ".idOne."
AND reciver = ".idTwo.")");
should be:
$stmt = $db->query("SELECT * FROM sms WHERE sender = ".$idOne."
AND reciver = ".$idTwo.")");
And where is $idOne and $idTwo defined?
Maybe you are missing something like:
$idOne = $_POST['idOne'];
$idTwo = $_POST['idTwo'];
A 500 is a server error. It means something broke badly on the server, so it's probably not your ajax, unless you are sending completely invalid data. One question - is "reciver" the correct field name in the DB? It's misspelled. If that is an incorrect column name in the database, that'll be your error right there.
Use like this
<?php
if(!isset($_POST['idOne'])){
echo "Error! missing idOne";
} else if(!isset($_POST['idTwo'])) {
echo "Error! missing idTwo";
} else {
$idOne = $_POST['idOne'];
$idTwo = $_POST['idTwo'];
$db = new PDO('mysql:host=localhost;dbname=XXXX;charset=utf8',
'user', 'password');
$stmt = $db->query("SELECT * FROM sms WHERE sender = ".$idOne."
AND reciver = ".$idTwo);
$smss = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($smss as $sms) {
if ($sms["sender"] == $idOne){
echo "<p style='text-align: right;'>".$sms["mesage"]."</p>";
}else{
echo "<p style='color: green;''>".$sms["mesage"]."</p>";
}
}
}
?>