On trying to return some data from a GET request via AJAX, I'm continuously greeted with this nasty error message ...Unexpected token { in JSON... and I can clearly see where it's coming from. Note that this only happens if I have more than one(1) item being returned from the database. If I only have one(1) item I am able to access it data.id, data.user_name, so on and so forth.
{
"id":"39",
"user_id":"19",
"user_name":"Brandon",
"content":"Second Post",
"date_created":"2018-01-24 21:41:15"
}/* NEEDS TO BE A ',' RIGHT HERE */ {
"id":"37",
"user_id":"19",
"user_name":"Brandon",
"content":"First",
"date_created":"2018-01-24 15:19:28"
}
But I can't figure out how to fix it. Working with data, arrays, and objects is an artform I have yet to master.
JAVASCRIPT (AJAX)
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost/mouthblog/test.php');
xhr.onload = () => {
if (xhr.status == 200) {
const data = xhr.responseText;
const jsonPrs = JSON.parse(data);
console.log(jsonPrs);
} else {
console.log('ERROR');
}
};
xhr.send();
PHP (this is where the data is coming from)
<?php
class BlogRoll extends Connection {
public function __construct() {
$this->connect();
$sql = "SELECT `id`, `user_id`, `user_name`, `content`, `date_created`
FROM `posts`
ORDER BY `date_created` DESC";
$query = $this->connect()->prepare($sql);
$result = $query->execute();
if ($result) {
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
header('Content-Type: application/json;charset=UTF-8');
echo json_encode($row);
}
} else {
echo 'NO POSTS TO DISPLAY';
}
}
}
I've been at this for a couple of hours now, everything similar to my problem on SO seems to be something different and I can't really find a decent plain JavaScript tutorial on returning real data. Everyone wants to use jQuery.
The reason why your code is failing is because you are using
echo json_encode($row);
This will echo an array for every row, but it is not valid JSON. I have corrected your PHP code (note: it has not been tested)
<?php
class BlogRoll extends Connection {
public function __construct() {
$this->connect();
$sql = "SELECT `id`, `user_id`, `user_name`, `content`, `date_created`
FROM `posts`
ORDER BY `date_created` DESC";
$query = $this->connect()->prepare($sql);
$result = $query->execute();
$returnArray = array(); // Create a blank array to put our rows into
if ($result) {
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
array_push($returnArray, $row); // For every row, put that into our array
}
} else {
// Send the JSON back that we didn't find any data using 'message'
$returnArray = array(
"message" => "No data was found"
);
}
header('Content-Type: application/json;charset=UTF-8'); // Setting headers is good :)
exit(json_encode($returnArray)); // Exit with our JSON. This makes sure nothing else is sent and messes up our response.
}
}
Also, you stated this:
If I only have one(1) item I am able to access it data.id, data.user_name, so on and so forth.
That is correct because the array only contains that one item. The example you would access it via data.0.id, data.1.id, data.2.id, etc as each row is in its own array.
You must print only once, e.g. a data "package" from which you will reference the items on the client-side correspondingly. But in your code you're actually printing for each row a data "package".
The solution is to create an array and save the whole fetched data into it. After that the array should be json-encoded and printed.
if ($result) {
// Save the fetched data into an array (all at once).
$fetchedData = $query->fetchAll(PDO::FETCH_ASSOC);
// Json-encode the whole array - once.
// header('Content-Type: application/json;charset=UTF-8');
echo json_encode($fetchedData);
} else {
echo 'NO POSTS TO DISPLAY';
}
Related
I have some PHP and JavaScript that works by PHP updating a MySQL database, and then outputting the updated code back onto the page without a hard refresh using the JavaScript fetch() method. This code works, but there is a part I don't understand — why is it when the json_encode() PHP method is used, which converts the data to a JSON string, when it is then used in the JavaScript it is automatically being converted into a JavaScript object without JSON.parse() being used?
In the Javascript when I use JSON.parse() it understandly throws an error, because the data isn't a string (which initially caused some confusion), when I console log the json variable being used in the JavaScript it does indeed return a JavaScript object where I can access its properties and methods etc.
There is no other JSON or json_encode() being used on the page (or indeed the site).
Also in the PHP script it echoes the JSON with echo json_encode($board_row); when the data is fetched from the database, before any HTML content is outputted. When I try and echo this in the HTML to see the value of json_encode($board_row); it just outputs the word false. I don't understand what is going on there either?
If I manually add a simply array into the HTML such as $arr = array('a' => 1, 'b' => "hello", 'c' => null); and then echo that in the HTML with echo json_encode($arr); as excepted it outputs a JSON string.
If someone could kindly explain why this is happening, that would be wonderful.
PHP
if (isset($_POST['submit-board-name'])) {
$create_board_name = $_POST['create-board-name'];
try {
// insert into database
$createBoardSQL = "
INSERT INTO boards (board_name, user_id)
VALUES (:board_name, :user_id )
";
$bstmt = $connection->prepare($createBoardSQL);
$bstmt->execute([
':board_name' => $create_board_name,
':user_id' => $db_id
]);
// ----- fetch as JSON
if(isset($_POST['json_response'])) {
$board_stmt = $connection->prepare("
SELECT * FROM `boards` WHERE `user_id` = :user_id
AND `board_name` = :board_name
ORDER BY `board_id` DESC");
$board_stmt -> execute([
':user_id' => $db_id,
':board_name' => $create_board_name
]);
$board_row = $board_stmt->fetch();
header('Content-type: application/json');
echo json_encode($board_row);
exit;
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
JavaScript
let boardModuleForm = document.querySelector('.board-module-form');
// URL details
let myURL = new URL(window.location.href),
pagePath = myURL.pathname;
if (boardModuleForm) {
boardModuleForm.addEventListener('submit', function (e) {
if (e.submitter && e.submitter.classList.contains('js-fetch-button')) {
e.preventDefault();
var formData = new FormData(this);
formData.set(e.submitter.name, e.submitter.value);
formData.set('json_response', 'yes');
fetch (pagePath, {
method: 'post',
body: formData
})
.then(function(response) {
if (response.status === 200) {
response.json().then(function(json){
const newBoardName = json.board_name,
boardId = json.board_id;
const newButton = `
<button name="board-name" type="submit">
<span>${newBoardName}</span>
<span style="margin:0" class="add-icon flex">+</span>
</button>
<input class="board-id-value" type="hidden" value="${boardId}">
`
// add new button from above onto page
document.querySelector('.board-list').insertAdjacentHTML('afterbegin', newButton);
});
}
})
.catch(function(error) {
console.error(error);
})
}
})
}
In the handler for your fetch response, you call response.json().then(...). This is already doing the JSON parsing for you without needing to call JSON.parse manually.
I have tried numerous ways to feed the events of the calendar. I have tried putting the JSON data into a variable and doing events = result and I have tried AJAX like I have now. The data is being fetched from a php function and it is the right syntax, i console log the data and here is what is returned: {title: 1, start: "2020-07-23"}. So I'm not sure why this is happening.
$('#calendar').fullCalendar({
events:
{
url: '/modules/ajax/ajax_handler.php',
method: 'POST',
data: data,
success: function(response) {
console.log(response);
},
failure: function() {
alert('there was an error while fetching events!');
},
}
});
Ajax Handler:
elseif($_POST['action'] == 'getPeopleCountOnDate') {
$date = $_POST['date'];
$count = getPeopleCountOnDate($connection, $date);
echo $count;
}
PHP Script
function getBookingEventInfo($connection) {
$dates;
$query = "SELECT reservation_date, count(*) FROM bookings GROUP BY reservation_date";
if($stmt = $connection->prepare($query)){
$stmt->execute();
$stmt->bind_result($date, $count);
while($stmt->fetch()){
$dates = array(
"title" => $count,
"start" => formatDate($date, 14)
);
}
$stmt->close();
}
return json_encode($dates);
}
If response contains only {title: 1, start: "2020-07-23"} as you've mentioned in the question then you have a problem because it's not an array.
FullCalendar requires an array of events, not a single object. Even if that array will only contain 1 event, it must still be an array. Your server would need to return [{title: 1, start: "2020-07-23"}] as the JSON in order for it to work.
To achieve that in your PHP code you can write it like this:
function getBookingEventInfo($connection) {
$dates = array(); //declare an array to contain all the results
$query = "SELECT reservation_date, count(*) FROM bookings GROUP BY reservation_date";
if($stmt = $connection->prepare($query)){
$stmt->execute();
$stmt->bind_result($date, $count);
while($stmt->fetch()){
//push the query result into the main array
$dates[] = array(
"title" => $count,
"start" => formatDate($date, 14)
);
}
$stmt->close();
}
return json_encode($dates);
}
Update 2: Just in case, I would delete the success callback, maybe it is preventing your calendar component to get the data because it may be a sort of interceptor.
Update: I think the event you are returning in json may not be in the right format. In the docs they say start should be a complete timestamp. I think YYYY-MM-DD may not be enough, but add also the missing parts (ex: 2009-11-05T13:15:30Z)
Did you read the docs?
One think that is obscure in your answer is, what did you pass as data?
And look at the docs, they use eventSources as an array.
I have the weird Problem that I get no response from my Ajax Call. I get the data but when im trying to return it I only get an blank screen. There are 3 Files in my project which are needed because my project has so many DB calls and functions so its easier to read.
So this one of many functions which calls my ajaxCall function
$.when(ajaxCall("getOutlets", '', null)).done(function(res) {
if(res) {
console.log(res);
this is my global ajaxCall Function for the whole project:
function ajaxCall(functionName, params, answers) {
return jQuery.ajax({
type: "POST",
url: '/ajax/ajax.php',
dataType: 'json',
data: {
functionIdentifier: functionName,
functionParams: params,
},
my Ajax.php file then calls based on the functionName Param the function in my database.php file. Ajax.php:
$response = array();
switch ($functionIdentifier) {
case 'getOutlets':
$response = $database->getSearchOutletsFromDatabase($functionParams);
break;
.... many switch cases
}
echo json_encode($response);
die();
?>
and finally in my database.php It calls the mysqli functions which looks like this:
public function getSearchOutletsFromDatabase() {
$result = mysqli_query($this->conn, "CALL `sp_outlets_get`()") or die(mysqli_error($this->conn));
while($row = $result->fetch_assoc()) {
$response[] = $row;
}
#mysqli_next_result($this->conn);
return $response;
}
and here is the weird part. If im returning only one Object from $result like return $result->fetch_object() I return the first Object successfull. BUT when I just save the row in an array and want to return my array the whole response is empty. No errors. Nothing.
If you need more information just say it Ill try to add more.
Edit:
If Im putting this on top of my ajax.php file where the response gets returned I get following error on Developers Network Tab:
header('Content-Type: application/json');
$response = array();
switch ($functionIdentifier) {
case 'getOutlets':
$response = $database->getSearchOutletsFromDatabase($functionParams);
break;
.... many switch cases
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
I found what caused the error (and sometimes it is one of the easiest things). Well it was ö,ä,ü etc in my response.
Adding a utf8_encode before I return my data to ajax solved the problem.
public function getSearchOutletsFromDatabase() {
$result = mysqli_query($this->conn, "CALL `sp_data_get`()") or die(mysqli_error($this->conn));
$response = array();
while($row = $result->fetch_assoc()) {
$res['ID'] = $row['ID'];
$res['Name'] = utf8_encode($row['Name']);
array_push($response, $res);
}
#mysqli_next_result($this->conn);
return $response;
}
I have a javascript file in which I am doing an ajax request to foo.php
in order to get an array of mysql results.
Here is my javascript file.
//foo.js
$(document).ready(function(){
$.ajax({
url:"foo.php",
type:"POST",
data:{
action:"test",
remail:"foo"
},
success:function(data){
var messages = data;
console.log("Ext req");
try{
console.log(JSON.parse(data));
}catch(e){
console.log(data);
}
},
failure:function(){
}
})
});
In order to receive my array of results from php I do the following:
//foo.php
<?php
if(isset($_POST)){
$action = $_POST['action'];
if(empty($action)){
return;
}
switch($action){
case "test":
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
echo json_encode($ar);
break;
}
}
?>
This returns an array of objects to my ajax request which then I can handle according to my needs.
However if I try to move the php code inside the switch statement into a function and return the encoded result of the function I only get an empty array as response.
Here is how I am trying to do it:
<?php
function test(){
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
if(isset($_POST)){
$action = $_POST['action'];
if(empty($action)){
return;
}
switch($action){
case "test":
$result = test();
echo json_encode($result);
break;
}
}
?>
Any ideas why this happening?
UPDATE
$con is a variable that comes from another file which I include
When you moved your query logic into a function, $con, MySQL's connection object is not available. Use GLOBAL $con; inside your function.
Read this to understand Variable Scope
Method 1
Using GLOBAL keyword
function test(){
GLOBAL $con;
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
Method 2
Pass an argument to a function
function test($con){
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
Call it like this:
test($con);
Global variables if not used carefully can make problems harder to find as other solution suggested. Pass $con as argument to your function:
function test($con){
$query = "select * from message where seen";
$ar = [];
$res = mysqli_query($con,$query);
while($row = mysqli_fetch_array($res)){
$ar[] = $row;
}
return $ar;
}
Let us talk about the problems you have:
You pass a failure function to $.ajax. You surely wanted to use error instead of failure. See here.
You have a messages variable initialized, but unused inside success. Get rid of it.
You check for isset($_POST), but that will always be true. You wanted to check isset($_POST["action"]) instead, or you wanted to check whether it is a POST request.
$con is not available inside the function. You will need to either initialize it inside the function or pass it to it and use it as a parameter.
I am trying to use a localStorage variable in a php function so I decided to use jquery post() to do so. Afterwards, I want to echo back data to my original file and set it inside a global variable. I have 3 files that connect to each other (its just a bit complicated).
quick_match.php
dataString = "";
$.post("ajaxCtrl.php", {action: "doQuickMatch", numCard: localStorage['numCard'], UI: "<?php echo $_REQUEST['UI']; ?>"}, function(data){ dataString = data; });
ajaxCtrl.php
if($action == "doQuickMatch")
{
//Start Quick Match
$result = $user->getQuickMatch($numCard);
echo $result;
}
User.php
(A big query here but I guarantee it works)
// Perform Query
$result = mysql_query($query);
//Hold the array objects in a string
$string = "";
// Iterate through results and print
while ($row = mysql_fetch_assoc($result)) {
$string .= '{ image: \'http://personals.poz.com'.$row['my_photo'].'\', user_id: \''.$row['id'].'\', user_prof: \'http://127.0.0.1/personalz.poz/v2/member.php?username='.$row['id'].'\'};';
}
return $string;
After all of this, I'm supposed to use the string and split it so I can get an array and continue on with what I was doing. However, the callback keeps on returning nothing so I am not sure what I did wrong. Can anyone offer insight to this please? Thank you in advance.