I have a PHP script that is creating my JSON needed for my web app. I am using jQuery's Ajax capabilities to fetch the JSON from my PHP page that is creating the JSON. I am finding a weird quirk though. If I simply run my PHP file in the web browser and output the JSON and then I copy that JSON into a file named myJSON.json
which is linked to my Ajax URL call, my code works. However, If I link directly to my PHP file in the Ajax URL call, I get the following error: Requested JSON parse failed
. So here is my relevant PHP Code:
<?php
$groupArray = array();
// Setup the beginning of the json file
$json = '
{
"emails": [';
// Loop through the request results
foreach ($contextIORequest->getData() as $message) {
// `date_received` is in Unix time. Begin converting this to a readable date and convert it to the users timezone
$newTZ = new DateTimeZone("America/Chicago"); // This will be based on the users location during production
$currentTime = new DateTime();
$currentTime = DateTime::createFromFormat('U', $message['date_received']);
$currentTime->setTimezone($newTZ);
$formattedDateReceived = $currentTime->format('F j, Y');
// The JSON structure is organized by date (group). Each unique date will be placed in its own group in the JSON file. So we need to check if a date is already in the $groupArray. If it is, then we simply add the email data to the current date group. If the date is not already in the $groupArray, then we will need to create a new group and add the email data to the new group.
if (!in_array($formattedDateReceived, $groupArray)) {
// This date is not yet in the $groupArray
// Check if this is the first group being added to the $groupArray. If it is, the first group added requires different formatting than all other groups that will be added
if (count($groupArray) == 0) {
// This is the first group being added
$json .= '{
"group": "'.$formattedDateReceived.'",
"list": [';
} else {
// This is not the first group being added. Close the previous "group" and "list" objects and then create new "group" and "list" objects.
// Before closing the previous "group" and "list" objects, we need to remove the trailing comma ',' from the last "list" item in the previous "group"
$json = rtrim($json, ',');
// ']' is closing the previous "list" object. '},' is closing the previous "group" object
$json .= ']
},{
"group": "'.$formattedDateReceived.'",
"list": [';
}
// Now we need to add this date to the $groupArray
$groupArray[] = $formattedDateReceived;
// The body of the email cannot have unescaped quotes or apostrophies. It also cannot have line breaks or multiple spaces between words.
$body = addslashes($message['body'][0]['content']); // Escapes quotes and apostrophies
$body = str_replace(array("
","
"),"", $body); // Removes all line breaks causing the body string to be all on one line
$newBody = preg_replace('!\s+!', ' ', $body); // Remove any multiple spaces between words
// Add the email to the JSON structure
$json .= '
{
"id": "'.$message['message_id'].'",
"subject": "'.addslashes($message['subject']).'",
"to": ["David Nester", "Jane Smith"],
"body": "'.$newBody.'",
"time": "'.$formattedDateReceived.'",
"datetime" : "'.$formattedDateReceived.'",
"from": "'.$message['addresses']['from']['name'].'",
"dp": "assets/img/profiles/avatar.jpg",
"dpRetina": "assets/img/profiles/avatar2x.jpg"
},';
// echo "<h1>New Group</h1>";
// echo "Date: ".$message['date_received']." ($formattedString)
<br>";
// echo "From: ".$message['addresses']['from']['email']."
<br>";
// echo "Subject: ".$message['subject']."
<br>";
// echo "Thread Size: ".$message['thread_size']."
<br>";
// echo "Message ID: ".$message['message_id']."
<br>";
// echo "Flags: ".$message['flags'][0]."
<br>";
} else {
// This date is already in the $groupArray
// The body of the email cannot have unescaped quotes or apostrophies. It also cannot have line breaks or multiple spaces between words.
$body = addslashes($message['body'][0]['content']); // Escapes quotes and apostrophies
$body = str_replace(array("
","
"),"", $body); // Removes all line breaks causing the body string to be all on one line
$newBody = preg_replace('!\s+!', ' ', $body); // Remove any multiple spaces between words
// Add the email to the JSON structure
$json .= '
{
"id": "'.$message['message_id'].'",
"subject": "'.addslashes($message['subject']).'",
"to": ["David Nester", "Jane Smith"],
"body": "'.$newBody.'",
"time": "'.$formattedDateReceived.'",
"datetime" : "'.$formattedDateReceived.'",
"from": "'.$message['addresses']['from']['name'].'",
"dp": "assets/img/profiles/avatar.jpg",
"dpRetina": "assets/img/profiles/avatar2x.jpg"
},';
}
} // end foreach loop
// Before closing the very last "group" and "list" objects, we need to remove the trailing comma ',' from the last "list" item in the last "group"
$json = rtrim($json, ',');
// Complete the JSON structure
$json .= ']
}
]
}';
// Output the JSON
file_put_contents('emails.json', $json);
header('Content-type: application/json; charset=utf-8');
echo $json;
?>
So if I run this PHP file in my web browser, it outputs the JSON. I then copied and pasted the JSON into a JSON file. I then link my AJAX call to the JSON file and everything is parsed correctly. But I need to link to the PHP file that creates the JSON in my AJAX call. However, when I do this, I get a parse error even though it is the exact same code I copied and pasted in my JSON file that works perfectly. I am really stumped on this one. Here is my relevant AJAX code as well:
$.ajax({
dataType: "json",
url: "create-json.php",
success: function(data) {
$.each(data.emails, function(i) {
var obj = data.emails[i];
var list = obj.list;
$.each(list, function(j) {
var $this = list[j];
var id = $this.id;
});
});
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.
Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.
' + jqXHR.responseText);
}
}
}