Accessing JSON object via PHP - php

I have the following code..
if (config.sendResultsURL !== null)
{
console.log("Send Results");
var collate =[];
for (r=0;r<userAnswers.length;r++)
{
collate.push('{"questionNumber'+parseInt(r+1)+ '"' + ': [{"UserAnswer":"'+userAnswers[r]+'", "actualAnswer":"'+answers[r]+'"}]}');
}
$.ajax({
type: 'POST',
url: config.sendResultsURL,
data: '[' + collate.join(",") + ']',
complete: function()
{
console.log("Results sent");
}
});
}
Using Firebug I get this from the console.
[{"questionNumber1": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber2": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber3": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber4": [{"UserAnswer":"3", "actualAnswer":"1"}]},{"questionNumber5": [{"UserAnswer":"3", "actualAnswer":"1"}]}]
From here the script sends data to emailData.php which reads...
$json = json_decode($_POST, TRUE);
$body = "$json";
$to = "myemail#email.com";
$email = 'Diesel John';
$subject = 'Results';
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// Send the email:
$sendMail = mail($to, $subject, $body, $headers);
Now I do get the email however it is blank.
My question is how do I pass the data to emailData.php and from there access it?

Create an object that you want to pass to PHP
Use JSON.stringify() to make a JSON string for that object.
Pass it to PHP script using POST or GET and with a name.
Depending on your request capture it from $_GET['name'] OR $_POST['name'].
Apply json_decode in php to get the JSON as native object.
In your case you can just pass userAnswers[r] and answers[r]. Array sequence are preserved.
In for loop use,
collate.push({"UserAnswer":userAnswers[r], "actualAnswer":answers[r]});
In ajax request use,
data: {"data" : JSON.stringify(collate)}
In the PHP end,
$json = json_decode($_POST['data'], TRUE); // the result will be an array.

json_decode converting string to object.
just do bellow code and check the values.
print_r($json)
Directly assign json object to string this is very bad.

If you decode your json, you will have a hash and not a string. If you want to be mailed the same as what you printed on the console, simply do this:
$body = $_POST['data'];
Another option would be to parse json into a php hash and var_dump that:
$json = json_decode($_POST['data'], TRUE);
$body = var_export($json, TRUE);

Using below JavaScript code
var collate =[], key, value;
for (r=0;r<userAnswers.length;r++) {
key = questionNumber + parseInt(r+1);
value = { "UserAnswer": userAnswers[r], "actualAnswer": answers[r] };
collate.push({ key : value });
}
$.post( config.sendResultsURL, { data: collate }, function(data) {
console.log("Results sent");
});
And do this in PHP
$data = json_decode( $_POST['data'], true );
and you will have all your data with array.

$jsonData = file_get_contents('php://input');
$json = json_decode($jsonData, 1);
mail('email', 'subject', print_r($json, 1));

Related

how to fix json_encode return empty array or empty object

I need help of some advanced users of PHP, JSON, AJAX and jQuery. I need to use json_encode in foreach loop between two if statemnts, so I'm reading a lot on google and I was find somewhere that $jsonData=[]; need be declared before first if statement, but in this case when a form is submitted var_dump of jsonData return empty array or empty object if I add echo json_encode($jsonData, JSON_FORCE_OBJECT); Also, without JS file form is submitted correctly and all data is inserted into the database as well. However, this is my JSON returned when I comment JS file when a form is submitted: {"0":{"response":"success","content":"Hvala Vam Testing! Va\u0161a poruka je uspje\u0161no poslata vlasniku objekta Brod Ivana! Odgovor \u0107ete dobiti ubrzo!"}} or if I use just echo json_encode($jsonData) I get seguent JSON [{"response":"success","content":"Hvala Vam John Doe! Va\u0161a poruka je uspje\u0161no poslata vlasniku objekta Brod Ivana! Odgovor \u0107ete dobiti ubrzo!"}] However on https://jsonlint.com/ all twoo JSON it's valid JSON, but I can not figure out how to process it in jQuery for get this data on web page.
Hier it's PHP file with part of json_encode
$query_m = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.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_m);
$dbstmt->bindParam(1,$pages_id);
$dbstmt->execute();
$emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
$jsonData=[];
if(is_array($emails_other) && count($emails_other) > 0){
foreach ($emails_other as $email_other){
//var_dump($email_other['email_address']);
$mailOwner->addAddress($email_other['email_address']);
$body_other = "<p>Poštovani {$email_other['owner_name']}, <br>" . "Upravo ste primili poruku sa sajta <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Detalji Vaše poruke se nalaze ispod:</p><p><strong>Od: </strong>" . ucwords($fname) . "<br><strong>Telefon: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Poruka: </strong>" . $userMessage . "<br><br><strong>Napomena: </strong>Molimo Vas da na ovu poruku ne odgovarate. Vaš odgovor pošaljite na: " . strtoupper($userMail) . "</p>";
$mailOwner->Body = $body_other;
try {
$mailOwner->send();
$mailOwner = "INSERT INTO visitneum.contact_owner (fname, tel, userMail, userMessage, email_address_id) VALUES (:fname, :tel, :userMail, :userMessage, :email_address_id)";
$stmt = $pdo->prepare($mailOwner);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);
$rez['response']="success";
$rez['content']="Hvala Vam ".ucwords($fname)."! Vaša poruka je uspješno poslata vlasniku objekta {$email_other['owner_property']}! Odgovor ćete dobiti ubrzo!";
$jsonData[] = $rez;
}//end try mail send
catch (Exception $e) {
$rez['response'] = "error";
$rez['content'] = "Došlo je do greške! Pokušajte ponovo..." . $mailOwner->ErrorInfo;
$jsonData[] = $rez;
}
}//end foreach for email addresses (man owners of other properties(restaurants, ships etc.))
}//end if for array of emails
//echo str_replace("[]", "{}", json_encode($jsonData));
echo json_encode($jsonData);
//var_dump($jsonData);
And this is part of my JS file after submitHandler
submitHandler: function (form) {
//Your code for AJAX starts
var formData = jQuery("#contactOwner").serialize();
console.log(formData);
jQuery.ajax({
url: '/inc/Form_process.php',
type: 'post',
data: formData,
dataType: 'json',
//async: true,
cache: false,
success: function (rez) {
jQuery("#responseOwner").text(rez[0].content);
console.log(rez[0].response);
console.log(rez[0].content);
}, error: function (rez) {
jQuery("#responseOwner").text("An error occurred");
console.log(rez[1].response);
console.log(rez[1].content);
}
}); //Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} //submitHandler
I hope that somebody understand why json_encode return just empty array or empty object with JSON_FORCE_OBJECT, so thanks in advance for any kind of your help. Any help will be highly appreciated.
You really should include the actual JSON in your question; without it we are working blind, but I can guess what the problem is. You are not constructing your JSON properly when there are multiple records. When you have a single recipient, your JSON might look like this:
{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
That is fine, and perfectly valid JSON – and there is no issue having an empty string as a value. The problem arises when you have more than one record, when it will append them immediately after the first:
{"readyState":4,"responseText":"","status":200,"statusText":"OK"}{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
This is not valid JSON.
I suggest you accumulate your JSON responses inside the loop and then output them afterwards, in the correct format. Something like:
$jsonData = [];
foreach ($emails_room_f as $email_room_f){
//set your content in $data as you are now, then:
$jsonData[] = $data;
}
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($jsonData);
This way you will end up with data like this:
[
{"readyState":4,"responseText":"","status":200,"statusText":"OK"},
{"readyState":4,"responseText":"","status":200,"statusText":"OK"}
]
Which is valid JSON. It will also work if there is no data as it will return an empty array, which is also valid JSON.
Separately from this, I am extremely suspicious of you having a utf8ize function – that is a sign you're doing other UTF-8 stuff wrong, but that's a subject for another question.

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

500 Internal Server Error - when assigning data from json_decode to variables

I am sending some form data form an AngularJs app to my php script. So far I've been unable to get Angular to send a "regular" POST request (it sends JSON data instead), so I figured I'd just decode it with php, then use the results
I am now having trouble referencing the results. I get "NetworkError: 500 Internal Server Error upon sending data to my script.
Here's my php code:
<?php
$data = file_get_contents("php://input");
$data = json_decode($data);
var_dump($data);
$fromName = $data["fromName"];
$fromEmail = $data["fromEmail"];
$msg = $data["inputMsg"];
The var_dump($data) returns this:
object(stdClass)#1 (3) {
["fromName"]=>
string(4) "djea"
["fromEmail"]=>
string(13) "djea#djea.com"
["inputMsg"]=>
string(7) "testMsg"
}
can someone please point out what I'm doing wrong? Thanks
Pass true as a second variable to json_decode to get associative array.
$data = json_decode($data, true);
$fromName = $data["fromName"];
$fromEmail = $data["fromEmail"];
$msg = $data["inputMsg"];
json_decode returns object if you do not pass second variable as a true.
$data = json_decode($data);
$fromName = $data->fromName;
$fromEmail = $data->fromEmail;
$msg = $data->inputMsg;
Well since it's an object and not an array, you need to access the elements like this:
$fromName = $data->fromName;
$fromEmail = $data->fromEmail;
$msg = $data->inputMsg;
Don't treat object as an array
$fromName = $data->fromName;
$fromEmail = $data->fromEmail;
$msg = $data->inputMsg;

decoding php not working

i want to post a json object to php.
var user = {username:"test", password:"test", name:"test",
email:"test#hotmail.com"};
var str_json = JSON.stringify(user);
$.ajax({
url: '/register_API.php',
type: 'post',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log('success');
},
data: user
});
}
In php i want to insert it into mysql:
$data = file_get_contents('php://input');
$json = json_decode($data,true);
$username = $json['username'];
$password = $json["password"];
$email = $json['email'];
$insertSql = "INSERT INTO users (username, password, email)
VALUES ('$username', '$password', '$email');";
The $data string contains: username=test&password=test&name=test&email=test%40hotmail.com, but i can't get the variable by decoding...
Thanks in advance!
Change data: user to data: str_json and then
change $data = file_get_contents('php://input');
to $data = $_POST['data']
You're not sending a JSON string, you're sending a Javascript object which jQuery is translating to a set of parameters in the outgoing POST request. Your data will be available to PHP in $_POST - no need to decode it first.
Look for it like this:
$username = $_POST['username'];
$password = $_POST["password"];
$email = $_POST['email'];
I think you want to send raw JSON as text and have that be in the post body and not treated as an encoded form.
In this case I think your PHP code is right. Send the stringified JSON as you are, but set the data type to dataType: "text".
I think you will be able to read it with
$data = file_get_contents('php://input');
I think you can use
//works like explode, but splits your data where finds "=" and "&" too.
$output = preg_split( "/ (=|&) /", $data);
This will return an array of your data. where:
$output[0]="Username";
$output[1]="test";
This can be useful if you have fixed data.

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

Categories