I am trying to use a PHP page hosted on a MySQL server that generates a JSON feed that I want to use as in the "eventSources" array of Fullcalendar in my Ionic application. The calendar is rendering, but it isn't displaying the dates in the feed. I have been working at this for a couple of days and none of the documents on the Fullcalendar site aren't working.
Here's the JSON String:
{"success":1,"message":"Details Available!","events":[
{"ID":"1","title":"Example Class","start":"2014-08-29 09:00:00","end":"2014-08-29 17:00:00","all_day":"0"},
{"ID":"2","title":"Example Class 2","start":"2014-08-13 00:00:00","end":"2014-08-13 00:00:00","all_day":"0"},
{"ID":"3","title":"Example Event with Time","start":"2014-08-13 12:00:00","end":"2014-08-13 13:00:00","all_day":"0"},
{"ID":"11","title":"Testing 123","start":"2014-08-13 00:00:00","end":"2014-08-13 23:59:00","all_day":"1"}]}
Here is the PHP Page generating the JSON above:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
header("Content-Type:application/json");
header("Access-Control-Allow-Origin: *");
$user="user";
$pass="password";
$table="database";
$db=new PDO("mysql:host=localhost;dbname=$table", $user,$pass);
//initial query
$query = "Select * FROM table";
//execute query
try {
$stmt = $db->query($query);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Details Available!";
$response["events"] = array();
foreach ($rows as $row) {
$post = array();
$post["ID"] = $row["ID"];
$post["title"] = $row["title"];
$post["start"] = $row["start"];
$post["end"] = $row["end"];
$post["all_day"] = $row["all_day"];
//update our repsonse JSON data
array_push($response["events"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Events Available!";
die(json_encode($response));
}
?>
Here is the the controller for the calendar:
App.controller('LogHomeCtrl', function($scope, $log, $state)
{
$scope.TimeTabl = function()
{
$state.go('timetable');
}
});
App.controller('calCtrl', function ($scope, $log, $state)
{
$scope.eventSources = [
{
events: {
url: 'url/calendarConnect.php',
type: 'POST',
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
}
];
});
I have tried using different methods of calling the PHP page, but none of it is working. If someone could point out where I am going wrong that would be great.
Exists few ways how you can set events for calendar:
1.as array:
events: [
{
title: 'Example Class',
start: '2014-08-29 09:00:00',
end: '2014-08-29 17:00:00'
},
{
title: 'Example Class 2',
start: '2014-08-13 00:00:00',
end: '2014-08-13 00:00:00'
}
]
2.as json object:
events: 'url/calendarConnect.php' //must to return json similar to previous example
3.as function:
events: function(start, end, timezone, callback) {
$.ajax({
url: 'url/calendarConnect.php',
dataType: 'json',
success: function(response) {
//get your events from response.events
console.log(response);
}
});
}
4.as custom function:
$.ajax({
url: 'url/calendarConnect.php',
dataType: 'json',
success: function(response) {
//just example
$('.calendar').fullCalendar({
events: response.events
});
}
});
In your case 3-rd way is more appropriate. For more details, please, see official Fullcalendar documentation about events.
Try changing this (add [] after ["events"]):
array_push($response["events"][], $post);
Related
I have a favourites button calling an ajax request to update a MySQL database.
I would like to have a alert if there are duplicate additions or too many additions.
Can anybody see a way that I could show an alert if there is a duplicate addition? My code is below:
AJAX REQUEST
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
success: function () {
alert('Added To Favourites');
}
});
PHP
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1="SELECT * FROM `$email` ";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe
//Check if fave adds >9
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die(); exit();} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1;}
Just return the text to alert to your javascript:
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1="Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1=$db->prepare($query1);
$stat1->execute();// IMPORTANT add PDO variables here to make safe
//Check if fave adds >9
$count = $stat1->rowCount();
$fave=$count;
if ($fave>9) {die("Here is a message");} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {$fave=$fave+1; die("Here is another message"); }
Ajax request:
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
success: function (message) {
alert(message);
}
});
Additionally, you should consider using JSON, to pass back entire objects to your javascript, and parse it there:
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1 = "Query here ($email/similar should NOT BE HERE! Add them via execute/prepare.";
$stat1 = $db->prepare($query1);
$result = $stat1->execute();// IMPORTANT add PDO variables here to make safe
// Tell javascript we're giving json.
header('Content-Type: application/json');
if (!$result) {
echo json_encode(['error' => true, 'message' => 'A database error has occurred. Please try again later']);
exit;
}
//Check if fave adds >9
$count = $stat1->rowCount();
$fave = $count;
if ($fave > 9) {
echo json_encode(['error' => false, 'fave' => $fave, 'message' => 'Fave > 9!']);
} // HERE I WISH TO RUN AN ALERT OR SEND BACK A MESSAGE TO DISPLAY
else {
$fave = $fave+1;
echo json_encode([
'error' => false,
'fave' => $fave,
'message' => 'Current fave count: ' . $fave
]);
}
And in your ajax, make sure you set dataType: 'json', which will automatically parse it into an object:
$.ajax({
type: 'post',
url: 'favaddDB.php',
data: $('#addfaveform').serialize(),
dataType: 'JSON',
success: function (res) {
if (res.error) {
//Display an alert or edit a div with an error message
alert(res.message);
} else {
//Maybe update a div with the fave count
document.getElementById('#favcount').value = res.fave;
alert(res.message);
}
}
});
Simple is better, in most cases.
By returning messages, you can do whatever you want on the frontend side, depending on the message.
PHP:
<?php
$db = new PDO("mysql:host=localhost;dbname=favourites", 'root', '');
$query1 = "SELECT * FROM " . $email;
$stat1 = $db->prepare($query1);
$stat1->execute();
$count = $stat1->rowCount();
$fave = $count;
if ($fave > 9) {
echo "tooMany"; exit();
} else {
echo "addedFav"; $fave++;
}
JS:
jQuery.post({
url: 'favaddDB.php',
data: jQuery('#addfaveform').serialize()
}).then(function (code) {
switch (code) {
case "addedFav":
alert('Added To Favourites');
break;
case "tooMany":
alert('Too many favourites');
break;
}
}).catch(function (error) {
console.log(error);
});
Alright, this is probably super simple but I've been breaking my head over this all day and I cannot get it to work.
I have a page that displays a list of users from a mysql query. On this page it should also be possible to add users. To do this, I'm sending an AJAX call to process.php which does some validation and sends an error if there is one. If there is no error, I want AJAX to update the page.
The problem is, that if there are no errors (a user has been added), I want to return the updated userlist. This means storing the output of my getUsers(); function in an array, which isn't possible.
How can I achieve this?
p.s. I realise this is crappy code and I should be using OOP/PDO, but this isn't for a production environment and it works. So I'll leave it like this for the time being.
users.php
<article>
<ul>
<?php getUsers(); ?>
</ul>
</article>
<form id="addUserForm">
...
<input type="hidden" name="addUser">
</form>
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if (response.success) {
$("article ul).html(response.data);
} else {
$(".errorMessage).html("<p>" + response.error + </p>");
}
}
});
});
functions.php
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
function addUser($email, $password)
{
global $db;
$result = mysqli_query($db, "INSERT INTO users ... ");
return $result
}
process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}
}
Your getUsers() function is printing and not returning the data to json connstructor
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
it has to be something like this
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
$list = "";
while($row = mysqli_fetch_assoc($query))
{
$list. = "<li>" . $row["user_firstname"] . "</li>";
}
return $list;
}
And there is a syntax error in the following line
if (addUser($email, $password)
close it with ")"
You can capture the output of the getUsers function without changing the current behavior if that's what you're after. In the success output change
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
to
ob_start();
getUsers();
$usersList = ob_get_clean();
$responseArray = ["success" => true, "data" => $usersList];
echo json_encode($responseArray)
What this does is captures the output and stores it into a varable $usersList which you can then return as a string.
You'd be better off returning the users as an array and dealing with generating the markup on the client side IMO, but that's up to you. This is just another way to get what you have working.
More information about php's output buffer here
Are you trying to get the error returned by ajax or you want to have custom error? (e.g. string returned by your php script). If you're referring to ajax error you should have this:
EDIT: Since you mentioned you want a custom error returned by process.php
Process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}else{
echo 1;
}
//I added else echo 1;
}
Your ajax will be:
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if(response != 1){
$("article ul").html(response.data);
}else{
alert('Custom error!');
}
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
BTW you're missing ) in your posted code if (addUser($email, $password))
This is how I do:
try{dataObj = eval("("+response+")");}
catch(e){return;}
alert(dataObj->example_key);
I am using select2 and ajax to query my database for terms under a certain taxonomy, but when I search the search boxes just hangs on "searching" without retrieving any results.
This is my html
<select multiple="" name="regions1[]" id="regions1" class="job-manager-multiselect select2-hidden-accessible" required="" tabindex="-1" aria-hidden="true"></select>
My jquery:
<script>
jQuery(function($) {
$(document).ready(function() {
$( "#regions1" ).select2({
ajax: {
url: "/ajax/connect.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data
};
},
cache: true
},
minimumInputLength: 2
});
});
});
</script>
and my php code to query the database, I am looking to get all the term names under the taxonomy "job_listing_region"
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=mydatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// strip tags may not be the best method for your project to apply extra
layer of security but fits needs for this tutorial
$search = strip_tags(trim($_GET['q']));
// Do Prepared Query
$query = $conn->prepare("
SELECT * FROM (
SELECT wp_terms.name
FROM wp_terms
JOIN wp_term_taxonomy
ON wp_term_taxonomy.term_id = wp_terms.term_id
WHERE taxonomy = 'job_listing_region'
AND count = 0
) as T"
);
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['name'], 'text' => $value['name']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
And as you can see, I am retrieving my data, but the search just hangs.
Thanks in advance.
Found the solution here How to load JSON data to use it with select2 plugin
Needed to recreate my results like this
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
}
So you need to change processResults to success and put the following into that function:
for(i=0;1<data.length;++i){
var currentObject = data[i];
var id = currentObject.id;
var text = currentObject.text;
//do what you need to here (Put things in a div, etc)
}
And from there, you can do something like this:
document.getElementById("search").innerHTML = document.getElementById("search").innerHTML+"<br />"+id+text;
I'm trying to make a login page that validates the users input data. If "username" and "password" does not match in the database he would receive a warning.
I'm a total newbie when it comes to this, so the code I have now is a combination of different tutorials.
my signin.php looks like this:
header('Content-Type: application/json')
$data = array(); // array to pass back data
if(!empty($_POST["action"]))
{
if($_POST["action"] == "signin")
{
...all the SQL code here...
if(!empty($result))
{
foreach ($result as $row)
{
...some SQL code here...
$data["success"] = true;
$data["message"] = "Success!";
}
}
else
{
$data["success"] = false;
$data["message"] = "Error!";
}
echo json_encode($data);
}
}
Now I want this json data to be used in a jquery submit function that uses ajax to get the data from signin.php:
<script>
$("#login-form").submit(function(event) {
$.ajax({
type : 'POST',
url : 'signin.php',
data : { 'action': 'signin' },
dataType : 'json'
}).done(function(data) {
console.log(data.success);
if(!data.success)
{
alert("ERROR");
}
else if (data.success)
{
alert("SUCCESS");
}
});
event.preventDefault();
});
</script>
I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.