jQuery Ajax PHP Array Blank Response No Errors - javascript

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

Related

FullCalendar.io not displaying events fed from JSON

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.

PHP Cannot access property value of an object using json_decode

So I have 2 php files, let's call it UploadImages.php and Caller.php
so in the UploadImages.php I have a function like so
<?php
function UploadImages(){
$result = [
"UploadOk" => 0,
"UploadMsg" => "Upload successful" ];
echo(json_encode($result));
}
?>
and this is how I handle it in the Caller.php
<?php
include "UploadImages.php";
$uploadResult = json_decode(UploadImages(), true);
if($uploadResult["UploadOk"] == 1) {
// do something else
}
else {
echo $uploadResult["UploadMsg"];
}
?>
using ajax from javascript, I have this result:
"{"UploadOk":1,"UploadMsg":"Upload successful"}"
what i expected is only UploadMsg property instead it returns an object, note that I actually need to process the UploadOk in the Caller.php instead of just dumping a whole object to javascript, so the JSON.parse method in javascript would not be the correct way to handle this situation.
echo inside UploadImages returns the object, As PHP echo send response headers, thus calling via ajax you get the response from this method.
Change the method with following and then try:
function UploadImages(){
$result = [
"UploadOk" => 0,
"UploadMsg" => "Upload successful" ];
return json_encode($result);
}
Note: Also you don't need to use json_encode inside UploadImages just return the the array as follow:
function UploadImages(){
$result = [
"UploadOk" => 0,
"UploadMsg" => "Upload successful" ];
return $result;
}
and in Caller.php
<?php
include "UploadImages.php";
$uploadResult = UploadImages();
if($uploadResult["UploadOk"] == 1) {
// do something else
}
else {
echo $uploadResult["UploadMsg"];
}
?>

PHP + JS + AJAX: Unexpected token { in JSON

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';
}

Can't return array from php function to ajax request

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.

jQuery post callback function set variable returning nothing

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.

Categories