jQuery.post not receiving errors from php script - php

I know this has been asked before and I have looked at every post I could find that deals with this. I still cannot get the jQuery.post function to correctly receive the error from a php script. Here are both.
PHP:
<?php
##CONFIGURATION
# LIST EMAIL ADDRESS
$toemail = "email here";
# SUBJECT (Subscribe/Remove)
$subject = "Someone has contacted International Designs";
# RESULT PAGE
$location = "../thank-you.php";
## FORM VALUES ##
$myname = $_REQUEST['myname'];
$myemail = $_REQUEST['myemail'];
$mymessage = $_REQUEST['mymessage'];
if ( empty($myname) || empty($myemail) || empty($mymessage) ) {
exit('{"error":"That value was invalid!"}')
} else {
# SENDER
$email = $myname . " <" . $myemail . ">";
# MAIL BODY
$body .= "Name: " . $myname . " \n\n";
$body .= "Email: " . $myemail . " \n\n";
$body .= "Message: " . $mymessage . " \n\n";
# add more fields here if required
## SEND MESSGAE ##
mail( $toemail, $subject, $body, "From: $email" ) or die ("Mail could not be sent.");
}
?>
JS:
if (verify(myname, myemail, mymessage, human, hash, patt)) {
$.post(myform.attr('action'), myform.serialize(), function() {
$('#email-success').fadeIn();
myform[0].reset();
setTimeout("$('#email-success').fadeOut();", 5000);
}, 'json')
.fail(function() {
alert('An error has occurred. Please try again later.')
});
}
I have tried about 5 different methods already, none of which have worked. When I put 'json' as the datatype in the .post function the .fail always fires, no matter what's in the php script. If I leave datatype out, then .fail never fires under any circumstance. I have a feeling the problem is with the php commands and datatype. Any help is appreciated.

Perhaps it's because you don't change the http header code of your response and don't specify your data type response.
You're php code response to front (jQuery) code with a "200 – OK" status in any case, but you expect an error in some case with an 'HTTP/1.0 400 – Bad Request' response Or a 'HTTP/1.0 500 Internal Server Error'.
And, like say Eggplant, you have to specify your response data type as 'Content-Type: application/json'.
So, the final code would be something like this :
<?php
...
header('HTTP/1.0 204 – No Content', true, 204);
header('Content-Type: application/json');
if ( empty($myname) || empty($myemail) || empty($mymessage) ) {
header('HTTP/1.0 400 – Bad Request', true, 400);
exit('{"error":"That value was invalid!"}')
} else {
...
$send = mail( $toemail, $subject, $body, "From: $email" );
if (!$send)
header('HTTP/1.0 500 – Internal Server Error', true, 500);
exit ('{"error":"Mail could not be sent."}');
}
}
return;
?>
For the Warning Cannot modify header information - headers already sent by (output started at /homepages/.../design/contact.php:1) you can examine this answer on the same problem.
Output can be:
Unintentional:
Whitespace before
UTF-8 Byte Order Mark
Previous error messages or notices
Intentional:
print, echo and other functions producing output (like var_dump)
Raw areas before
Update after chat session : it's was a UTF-8 BOM problem

try this
if (verify(myname, myemail, mymessage, human, hash, patt)) {
$.ajax({
type :'POST',
data :$("#myformid").serialize(),
beforeSend:function(){
},
success:function(res){
if(res=='ok'){
setTimeout("$('#email-success').fadeOut();", 5000);
}else{
//read respon from server
alert(res)
}
},
error:function(){
//error handler
}
});
}
and just example
$send = mail(....);//your mail function here
echo ($send) ? "ok" : "Error";

Although, yours is a valid JSON data, I always recommend to use json_encode() function to create JSON string.
exit(json_encode(array("error" => "That value was invalid!")));
Another is make sure you send correct headers to ensure the script knows its a json data. So
header('Content-Type: application/json');
exit(json_encode("error" => "That value was invalid!"));

Related

Broken links inside PHP emailer with AngularJS

I have an AngularJS app that sends emails using a PHP document.
The email body includes two links to images that are populated with a JS variables.
Most of the emails arrive good and the links work, but in some of them, the links (both or one of them) will come out broken, looking like this:
https://blabla.com/register/uploads/Frankfurt2018-22-03-2018-16-07-52.!
Or like this:
https://blabla.com/register/uploads/KoelnerListe2%21
Or like this:
https://blabla.com/register/upload!
It's weird cause sometimes is both links, sometimes is only one, and most of the times are correct.
The link variable comes from the Angular app and looks like this:
$scope.sendapplication = function(){
$scope.photoor = "https://blabla.com/register/uploads/"+$scope.photoor;
$scope.photosmall = "https://blabla.com/register/uploads/"+$scope.photo;
$scope.exhibitor = {
'img':$scope.photosmall,
'imgoriginal':$scope.photoor,
};
var $promise=$http.post('emailtest.php',$scope.exhibitor);
$promise.then(function (data) {
...
});
};
And in the php file I do this:
$contentType = explode(';', $_SERVER['CONTENT_TYPE']); // Check all available Content-Type
$rawBody = file_get_contents("php://input"); // Read body
$data = array(); // Initialize default data array
if(in_array('application/json', $contentType)) {
$data = json_decode($rawBody); // Then decode it
$photo = $data->img;
$photooriginal = $data->imgoriginal;
} else {
parse_str($data, $data); // If not JSON, just do same as PHP default method
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array( // Return data
'data' => $data
));
$sabine = 'blabla#gmail.com';
$headerss = "From: ".$galleryname."<".$email.">\r\nReturn-path: ".$email."";
$headerss .= "Reply-To: ".$galleryname."<".$email.">";
$headerss .= "MIME-Version: 1.0\r\n";
$headerss .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$recipient = $sabine;
$subjects = "Registration for ".$fairumlaut." - ".$galleryname."";
$bodys .= "<p><strong>Original photo</strong>: Link</p>";
$bodys .= "<p><strong>Web resized photo</strong>: Link</p>";
$bodys .= "<p></p>";
mail($recipient, $subjects, $bodys, $headerss);
What could cause such weird behaviour?
wrap the link in urlencode function. This will solve your issue.
update: or if I read your code I would have seen that the links are coming from JS. Try encodeURI().. ;)

PHP Mail attechment dont work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a problem because my file attechment via a php doesn't work. I tried different tutorials. My last try was the code here:
if($isValid === true) {
// Submit Mail
$mail = new SimpleMail();
$mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
->setSubject('Neue Mietanfrage')
->setFrom(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
->setMessage(createMessage($_POST))
->setWrap(100);
$mail->send();
// Submit Client Mail
$mailClient = new SimpleMail();
$mailClient->setTo(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
->setSubject('Ihre Mietanfrage bei '.YOUR_COMPANY_NAME)
->setFrom(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
->setMessage(createClientMessage($_POST))
->setWrap(100);
$mailClient->send();
$result = array(
'result' => 'success',
'msg' => array('Ihre Reservierung wurde erfolgreich übermittelt.')
);
echo json_encode($result);
} else {
$result = array(
'result' => 'error',
'msg' => $isValid
);
echo json_encode($result);
}
//*** Attachment ***//
if($_FILES["fileAttach"]["name"] != "")
{
$strFilesName = $_FILES["fileAttach"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$strHeader .= "--".$strSid."\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"".$strFilesName."\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"".$strFilesName."\"\n\n";
$strHeader .= $strContent."\n\n";
}
<input type="file" name="fileAttach" id="fileAttach" hidden>
Why doesnt that worked for me? I just followed the tutorial but nothing helped. Do you have any idea what I have to do? The other informations like the text fields are sending without problems.
I get the informations from that form with javascript. Does that script pay any role why the email doesnt send with the attachment?
$( "#umzug-form" ).submit(function() {
$('#umzug-form-msg').addClass('hidden');
$('#umzug-form-msg').removeClass('alert-success');
$('#umzug-form-msg').removeClass('alert-danger');
$('#umzug-form input[type=submit]').attr('disabled', 'disabled');
$.ajax({
type: "POST",
url: "php/umzug.php",
data: $("#umzug-form").serialize(),
dataType: "json",
success: function(data) {
if('success' == data.result)
{
$('#umzug-form-msg').css('visibility','visible').hide().fadeIn().removeClass('hidden').addClass('alert-success');
$('#umzug-form-msg').html(data.msg[0]);
$('#umzug-form input[type=submit]').removeAttr('disabled');
$('#umzug-form')[0].reset();
}
if('error' == data.result)
{
$('#umzug-form-msg').css('visibility','visible').hide().fadeIn().removeClass('hidden').addClass('alert-danger');
$('#umzug-form-msg').html(data.msg[0]);
$('#umzug-form input[type=submit]').removeAttr('disabled');
}
}
});
return false;
});
You aren't adding the file to the mail object anywhere.
SimpleMail provides the method addAttachment to add attachments to your email.
I'm extending your code with the needed lines:
// Submit Mail
$mail = new SimpleMail();
$mail->setTo(YOUR_EMAIL_ADDRESS, YOUR_COMPANY_NAME)
->setSubject('Neue Mietanfrage')
->setFrom(htmlspecialchars($_POST['email-address']), htmlspecialchars($_POST['first-name'].' '.$_POST['last-name']))
->addGenericHeader('X-Mailer', 'PHP/' . phpversion())
->addGenericHeader('Content-Type', 'text/html; charset="utf-8"')
->setMessage(createMessage($_POST))
->setWrap(100);
// add the following lines to your code
if (isset($_FILES['fileAttach']['tmp_name'])) {
$mail->addAttachment(
$_FILES['fileAttach']['tmp_name'],
$_FILES['fileAttach']['name']
);
}
$mail->send();
SimpleMail will load the contents of the file by itself.

AJAX - PHP & XML - POST request is directing to the PHP file instead of staying at the original page

I have been trying recently to use AJAX in a form I posses in order to prevent the page from reloading. I learned AJAX through thenewboston's videos and I've tried to match it to my form.
HTML:
<label for="f_name">Name:</label>
<input type="text" name="f_name" id="f_name" />
<label for="f_email">E-Mail:</label>
<input type="text" name="f_email" id="f_email" />
<label for="f_subj">Subject:</label>
<input type="text" name="f_subj" id="f_subj" /><br />
<div id="status"></div>
<button id="b_send" onClick="process()">Send</button>
JavaScript
function process() {
var name = encodeURIComponent(document.getElementById("f_name").value);
var email = encodeURIComponent(document.getElementById("f_email").value);
var sbj = encodeURIComponent(document.getElementById("f_subj").value);
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
xmlHttp.open("POST", "send.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send("name="+name+"&email="+email+"&subj="+sbj);
} else {
setTimeout('process()', 1000);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4) { // AJAX is ready!
if (xmlHttp.status == 200) { // 200 = Comms went OK!
var xmlResponse = xmlHttp.responseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.data;
document.getElementById("status").innerHTML = '<span style="color:blue">' + message + '</span>';
} else {
alert('Something went wrong!');
}
}
PHP:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
$name = $_POST['name'];
$email = $_POST['email'];
$sbj = $_POST['subj'];
$src = 'BETA';
$to = "someone#somewhere.com";
$subject = "CONTACT | From: " . $name . " , " . $email . " | '" . $sbj . "' | " . $src . "";
$body = "
<html><body>
<h4>From: ".$name." , ".$email."</h4>
<h4>Subject: ".$sbj."</h4>
<h5>Source: BETA</h5>
</body></html>";
$headers = "From: someone#somewhere.com\r\n";
$headers .= "Reply-To: \r\n";
$headers .= "CC: \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$response = 'Error!';
if (mail($to, $subject, $body, $headers)) {
$response = 'Sent!';
} else {
$response = 'Error 202!';
}
echo '<response>';
echo strip_tags($response);
echo '</response>';
exit(); // I had to use exit() due to my hosting adding up code after every PHP page.
?>
After I click on the button, it shows me the PHP page with the following saying:
This XML file does not appear to have any style information associated
with it. The document tree is shown below.
and the XML code below it:
<response>Sent!</response>
So what now?
The message is a warning. An XML document is a data structure but does not contain any presentation/style information internally. Normally an XML document is used in inter-application communication or as a pure data structure that is then used with additional presentation/style information to display to users.
You are outputing your data in xml format using following lines,
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
If you are trying to get the response from your ajax call, remove xml header and simply echo proper response or use JSON to get your data.
or if you want to display xml file without the warning, you can attach a stylesheet to your xml document like this:
<?xml-stylesheet type="text/css" href="your_stylesheet.css"?>
XML-Stylesheet Reference: http://www.w3.org/TR/xml-stylesheet/

Ajax Array to PHP issue

Im having difficulties when parsing an array using Ajax to PHP to send an email with the values from the array.
Ajax code:
$(document).ready(function(){
$("#submit-button").click(function(){
var countryArray = ['Location Zero', 'Location One', 'Location Two'];
dataString = countryArray;
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "sendmail.php",
data: {countries: jsonString},
success: function (msg) {
$("#errors").text("Thank you for getting in touch, we will get back to you!");
},
error: function (msg) {
$("#errors").text("Error sending email, please try again.");
alert("error");
}
});
});
});
PHP code:
<?php
$to = "abc#abc.com";
$countries = json_decode($_POST['countries']);
$header = "Content-Type: text/html\r\nReply-To: \r\nFrom: <>";
$subject = "Email from the Lister customer";
$body = #"$countries";
if(mail($to, $subject, $body, $header)) {
die("true");
} else {
die("There was an error sending the email.");
}
?>
But all I'm getting with in the email from $countries is word "Array" instead of the values.
Can anyone help please?
$countries is an array. If you want it to be displayed as a list in your $body, you can do:
$body = implode(', ', $countries);
Please also try not to suppress (#) PHP errors, it'll cause you more headaches in the future.
<?php
$to = "abc#abc.com";
$countries = json_decode($_POST['countries']);
$header = "Content-Type: text/html\r\nReply-To: \r\nFrom: <>";
$subject = "Email from the Lister customer";
$body = implode(", ", $countries);
if(mail($to, $subject, $body, $header)) {
die("true");
} else {
die("There was an error sending the email.");
}
?>
If you're using jquery, try using .serializeArray() instead of stringify.
Also, when receiving the $_POST['contries'] variables, you need to implode it. Try this:
$(document).ready(function(){
$("#submit-button").click(function(){
var countryArray = ['Location Zero', 'Location One', 'Location Two'];
$.ajax({
type: "POST",
url: "sendmail.php",
data: {countries: countryArray.serializeArray()},
success: function (msg) {
$("#errors").text("Thank you for getting in touch, we will get back to you!");
},
error: function (msg) {
$("#errors").text("Error sending email, please try again.");
alert("error");
}
});
});
});
And then in PHP use this to properly grab the countries values:
implode(', '.$countries);

Why is Easyuniv REST API not Handling Errors?

I am writing a REST API and currently testing some things. I am trying to make it send an error response when it does not find anything in the database.
The part that is running (because i am testing currently by just entering the url into my browser) is below:
else if ($request->getHttpAccept() === 'xml')
{
if(isset($data['s']) && isset($data['n'])) {
$id = $db->getAlcoholIDByNameSize($data['n'], $data['s']);
$prices = $db->pricesByAlcohol($id);
}
if(isset($id)) {
$resData = array();
if(!empty($prices)) {
foreach($prices as $p) {
$store = $db->store($p['store']);
array_push($resData, array('storeID' => $p['store'], 'store_name' => $store['name'], 'store_gps' => $store['gps'], 'price' => round($p['price'], 2)));
}
RestUtils::sendResponse(200, json_encode($resData), 'application/json');
} else {
RestUtils::sendResponse(204, 'error', 'application/json');
}
} else {
RestUtils::sendResponse(204, 'error', 'application/json');
}
//RestUtils::sendResponse(501, "xml response not implemented", 'application/xml');
}
everything works fine if the queries return something to be stored in $id and $prices. If they do not exist in the database, however, it tries to load the page, and then goes back to the previous page you were on. You can see the behavior by going to:
http://easyuniv.com/API/alc/coorsa/2 <-- works
http://easyuniv.com/API/alc/coors/3 <-- works
http://easyuniv.com/API/alc/coorsa/5 <-- doesn't work(or anything else, the two above are the only ones)
here is my sendResponse function:
public static function sendResponse($status = 200, $body = '', $content_type = 'text/html')
{
$status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status);
// set the status
header($status_header);
// set the content type
header('Content-type: ' . $content_type);
// pages with body are easy
if($body !== '')
{
$temp = json_decode($body);
$body = json_encode(array('result' => array('status' => $status, 'message' => RestUtils::getStatusCodeMessage($status)), 'data' => $temp));
// send the body
echo $body;
exit;
}
// we need to create the body if none is passed
else
{
$body = "else".json_encode(array('result' => array('status' => $status, 'message' => RestUtils::getStatusCodeMessage($status))));
echo $body;
exit;
}
}
I have tried debugging using echos but I cant seem to narrow down what the issue is. Any help would be appreciated, thanks.
The problem is that when there is no appropriate data found in the data base you are returning HTTP 204 which is telling the browser there is absolutely nothing for it to display. This is not true in your case.
You still want to output the message that there was nothing found.
To fix you need to replace the two instances of 204 in your code with 200.
I modified tested your code using: Note, nothing will display as is. To get the message to display change 204 to 200 in the $status_header variable.
<?php
$status_header = 'HTTP/1.1 204';
// set the status
header($status_header);
// set the content type
header('Content-type: text/html');
echo "Can you see me???";
?>
Note: When testing this always close the tab and use a fresh tab for each call or else it will look like it is loading data from the previous call, like you have explained.

Categories