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.
Related
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;
}
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';
}
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:
{data: [{IdProduct: "1", Name: "Name here..........",…}]}
For example I want to select only Name, I tried doing this:
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
success: function (data) {
var aRC = JSON.parse(data);
for (var i = 0; i < aRC.length; i++) {
console.log(aRC[i].Name);
}
}
});
}
But this doesn't shows anything, how can I do this? This is my PHP code:
while($row = mysqli_fetch_array($registros)) {
$table.='{
"IdProduct":"'.$row['IdProduct'].'",
"Name":"'.$row['Name'].'",
"Description":"'.$row['Description'].'",
"ImagePath":"'.$row['ImagePath'].'"
},';
$table = substr($table, 0, strlen($table) -1);
echo '{"data":['.$table.']}';
}
There are couple of things you need to change in your code, such as:
That's not how you should create a json string. Create an empty array before the while() loop and append the row details to this array in each iteration of the loop. And after coming out of the loop, simply apply json_encode() function to the resultant array to get the final json string.
$table = array();
while($row = mysqli_fetch_array($registros)) {
$table[]= array(
'IdProduct' => $row['IdProduct'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
);
}
echo json_encode($table);
Since you're expecting a json string from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, simply loop through the json result to get the relevant data.
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].Name);
}
}
});
}
First off, your shouldn't echo the json data in the loop. It should be outside the loop.
You shouldn't build your own json data either.
Let's build an array that looks like the json response you want. Then we'll use the function json_encode() to encode it as a proper json-string:
// Define the response array
$response = [
'data' => []
];
while($row = mysqli_fetch_array($registros)) {
// Push a new array to 'data' array
$response['data'][] = [
'IdProduct' => $row['IdProduct'],
'Name' =>.$row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
];
}
// Now, let's encode the data:
echo json_encode($response);
In you PHP file make changes according to this:-
$outp = array();
$outp = $res->fetch_all(MYSQLI_ASSOC);
For make sure that json_encode don't return null
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
echo json_encode(utf8ize($outp));
You JavaScript is okay You just need to change code in PHP.
How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.
JavaScript code:
$.ajax({
method:"POST",
url:'php.php',
data:"",
dataType:'json',
success:function(data){
var y1=data;
console.log(data.name);
}
});
PHP code:
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//assign vars after formatting to avoid a wrong login with correct
//username and password
$username = trim($_POST["user"]);
$customer_array = array();
$customer1 = array(
'name' => '3',
'city' => 'Houston'
);
$customer_array[] = $customer1;
$customer2 = array(
'name' => '2',
'city' => 'Boston'
);
$customer_array[] = $customer2;
$customer3 = array(
'name' => "1",
'city' => "Bossier City"
);
echo json_encode($customer_array);
}
I am just going to summarize my comments into an answer, first I would just turn off the json return for trouble shooting. You can parse the json after fact anyway:
$.ajax({
// Do "type" here
type:"POST",
url:'php.php',
// Send something to check in the script
// This is optional, but I like to do it...
data: {
"action":"get_name_city"
},
success:function(data){
// Do a try, just incase your parse fails
try {
// Parse the json here
var getJson = JSON.parse(data);
console.log(getJson);
console.log(data);
}
catch(Exception) {
// Show any errors that might get thrown
console.log(Exception.message);
}
}
});
PHP:
# Check the action is set and is named
if(isset($_POST["action"]) && $_POST["action"] == "get_name_city") {
$username = trim($_POST["user"]);
$customer_array = array();
$customer1 = array(
'name' => '3',
'city' => 'Houston'
);
$customer2 = array(
'name' => '2',
'city' => 'Boston'
);
$customer3 = array(
'name' => "1",
'city' => "Bossier City"
);
$customer_array[] = $customer1;
$customer_array[] = $customer2;
$customer_array[] = $customer3;
# Just die here
die(json_encode($customer_array));
}
# Die with error so there is some feedback to your ajax
die(json_encode(array('error'=>'No data was sent.')));
As has been mentioned, there are multiple options for passing the data from PHP:
add the Content-Type header with value application/json before sending the return from json_encode() to echo():
header('Content-Type: application/json');
echo json_encode($customer_array);
Parse the return from the PHP using JSON.parse()
success:function(data){
var y1=data;
var data = JSON.parse(data);
So pick one of those approaches. One might argue that the first is more semantically correct, since JSON data is being sent.
Additionally, the success callback of the AJAX request is attempting to access the property name of the data returned. However, the data returned should be an array of objects, each which has a property name. One approach to logging the name of each property is to use Array.forEach() and send the name of each element in the array to console.log().
data.forEach(function(dataItem) {
console.log(dataItem.name);
});
See a demonstration of this in this phpfiddle.
You where almost there. Your AJAX requests accepts JSON but your PHP does not output JSON (it does but not in the correct way), you'll have to set the appropriate Content-Type header:
header('Content-Type: application/json');
echo json_encode($customer_array);
Your AJAX request should now be able to use the properly formatted JSON as the data variable (and console.log it).
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.