I'm trying to create a loader, which loads an animation between visits new paths, something like this:
https://koisquad.com/
The problem is I made my project with following logic (MVC Model View Controller) and I need to not reload the page when the path changes.
I have been investigating and realize that need to use javascript using window.history.pushstate
I tried a lot ways but I can not implement propertly.
Layout page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo $title; ?></title>
</head>
<body>
<?php
include_once __DIR__ . '/templates/loader.php';
?>
echo $content; //ONE EXAMPLE VIEW (events.php)
<!-- My Javascript -->
<script src="/build/js/main.min.js" defer></script>
</body>
</html>
One example view (/events.php)
<main>
<div> EVENTS CONTENT </div>
</main>
The Controller
class PublicPagesController {
//Main page
public static function index(Router $router) {
//The Backend logic, Database querys for render later in view...
$router->render('views/index', [
'title' => 'Inicio',
]);
}
//Contact page
public static function events(Router $router) {
//The Backend logic, Database querys for render later in view...
$events = Events::all();
$router->render('views/events', [
'title' => 'Contact',
'events' => $events
]);
}
The router:
public function render($view, $data = [])
{
foreach ($data as $key => $value) {
$$key = $value;
}
ob_start();
include_once __DIR__ . "/views/$view.php";
$content = ob_get_clean(); // THAT IS THE CONTENT THAT SHOWS ON LAYOUT PAGE
}
I have the models too, but I think it's irrelevant to the question.
How can I obtain the view and render in the $content without reloading the page? (With JS or Other solutions)
Thank you a lot in advance, sorry if the question is a little dumb I'm trying to improve :(
I tried to use fetch in JS to URLs (Previusly encoded in JSON in php) for try to get the view content and window.history.pushstate but I cant get the view without a reloading.
Related
I need to create a centralized page where all the variables that are needed in more than one page get set. For example:
centralized.php
$displayPath = "/var/www/html/wordpress/";
Then, I need html and php pages across the server to have access to it. For example:
page1.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</body>
</html>
<?php
echo ($displayPath);
?>
page2.php
<?php
echo ($displayPath);
?>
I was looking at using window.localStorage, but when doing so, how could pass the value from JS variables to php variables.
If you only want to read the variables from different pages, you can create a file with all of your variables:
myVariables.php
<?php
$displayPath = "/var/www/html/wordpress/";
$myglobalvariable="hello";
?>
And then include it in every page that needs it.
page1.php
<?php
require_once("./myVariables.php");
?>
NOTE: This will not allow you to change the variables in one page and then access the modified variables in another page. If that's what you want, you can take a look at this:
How to access a variable across two files
My end goal to pass eventSources via JSON dynamically. Before I even get to producing the JSON content dynamically, I am trying to use the documentation example to pass a simple single event via a JSON URL into my event tag, written manually.
I can see the URL works because I can echo the results in my wordpress website via php, but the JS script i'm passing the JSON URL to just crashes the calendar. I'm really scratching my head on this one.
There's also mention of the prev/next buttons triggering a GET to the JSON with the local timezone dates (say for the range of the currently displayed month). How am I supposed to syntax the json so as to have the event call find the data points range? I'm just really confused about all this.
JSON File: calendar.json
{
"title" : "something",
"start" : "2019-04-23"
}
PHP File: page-calendar.php
<?php
//Wordpress function for URL to the file location
$url = get_stylesheet_directory_uri() . '/calendar.json';
$data = file_get_contents($url);
$content = json_decode($data);
echo $content->title; // Just to test if the URL works
echo $content->start; // This echos just fine
?>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid' ],
events: $url;
});
calendar.render();
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
The JSON needs to be an array of events (even if the array only contains one object). Currently you have a single object, and fullCalendar won't read that.
Make your calendar.json file look like this:
[
{
"title" : "something",
"start" : "2019-04-23"
}
]
You'll also need to change the code a bit so that your PHP $url variable is treated as PHP and rendered, and also so the output is treated as a string by JS, not just injected into the JS as-is:
events: "<?php echo $url; ?>"
If your php and fullcalendar is on the same page you may need this
<?php
$url = get_stylesheet_directory_uri() . '/calendar.json';
?>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid' ],
events: "<?php echo $url; ?>";
});
calendar.render();
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
Remember to check your output of calendar.json.
It should look like so
[
{
"title" : "something",
"start" : "2019-04-23"
}
];
I'm not really sure, if this might solve your problem, also I don't know about WordPress. However, maybe you might try using WordPress built-in functions, maybe in this case, you might try wp_remote_get or find similar functions to use instead of file_get_content(). Because, maybe for security or permission reasons, you are not allowed to get contents from some URLs, not sure.
You might test it with chmod($url, 0000); to see if you are allowed to change the permission of the file. Then, if it was a permission issue, you could just add chmod()to your script:
//Wordpress function for URL to the file location
$url = get_stylesheet_directory_uri() . '/calendar.json';
chmod($url, 0777);
//$data = file_get_contents($url);
$data = wp_remote_get($url);
$content = json_decode($data);
chmod($url, 0755);
echo $content->title;
echo $content->start;
Your PHP codes seem to be fine. Maybe, var_dump($url); to make sure everything is fine.
Also, you might try changing
events: $url;
to
events: <?php echo $url; ?>
I'll briefly explain what I am trying to do.
I have different entries on a mySql database, I want to load them from a PHP page, convert to JSON, and eventually read them back through AngularJS. So far I have manage to do all the steps but the last one. I'll go step by step so that other people can use this as a reference:
/// GRAB DATA FROM SQL DATABASE WITH PHP
access_db.php
<!DOCTYPE html>
<html>
<body>
<?php
$host = "myhost";
$user = "myusername";
$psw = "mypsw";
$dbname = "mydatabasename";
//open connection to mysql db
$conn = mysqli_connect($host,$user,$psw,$dbname); // Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT EntryName as name, EntryType as type, EntryPlatform as platform, EntryStatus as status, EntryDate as submitDate FROM pl_entries";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0){
while($r = $result->fetch_assoc()){
$rows[] = $r;
}
echo json_encode($rows);
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</body>
</html>
If I run the php file, i get this:
[{"name":"name1","type":"type1","platform":"platform1","status":"status1","submitDate":"date1"},{"name":"name2","type":"type2","platform":"platform2","status":"status2","submitDate":"date2"},{"name":"name3","type":"type3","platform":"platform3","status":"status3","submitDate":"date3"},{"name":"name4","type":"type4","platform":"platform4","status":"status4","submitDate":"date4"}]
The connection with the database therefore seem to work correctly.
/// READ THE JSON WITH ANGULARJS
(the problematic part)
for this of course I need both an HTML page as well as a JS file.
dbService.js
var app = angular.module('dbApp', []);
function GetEntries($scope, $http){
$http.get('/php/access_db.php').success(function(data) {
$scope.entries = data;
});
}
index.html (I removed part of the code to make it more readable)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<script src="js/dbService.js"></script>
</head>
<body ng-app="dbApp">
<div class="main" ng-controller="GetEntries">
<div class="container">
<!-- ENTRIES LIST -->
<div id="diary">
<div ng-repeat="entry in entries | orderBy: '-date'">
<div class="row">
<h1>{{ entry.submitDate | date: 'dd' }}</h1>
<p>{{ entry.submitDate | date: 'MMM'}}, {{ entry.submitDate | date: 'yyyy'}}</p>
<p>{{ entry.type }}</p>
<h1>{{ entry.name }}</h1>
<p>{{ entry.platform }}</p>
<p>{{ entry.status }}</p>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</body>
</html>
The result of this is that nothing shows up on index.html.
EDIT: to be clearer, none of the AngularJS elements appear, which I guess means that it correctly tries to load data, but probably can't correctly parse it.
I believe the project is in the JS file, but at this point I tried so many different things that I am just confused. I hope someone can help me out understanding how to fix this situation, I hope I provided enough details.
Thanks!
There a few possible reasons why you are facing this problem. Try to make sure your controller is working first. Check your console to see it is initiating or not.
I think you are confused between controller and service. I saw you injected GetServices which meant for services not controller
var myApp = angular.module('dbApp',[]);
myApp.controller('GetEntries', ['$scope', '$http', function($scope,$http) {
console.log("Initiating the controller");
$http.get('/php/access_db.php').success(function(data) {
$scope.entries = data;
});
}]);
Here is a simple app with $http.get usage. I use random API but it should work with your PHP server. http://plnkr.co/edit/ZzPrkg8yokh1jXtzrmdR
This is not really a good practice. Try to move the http request to services instead of controller.
I have made a RESTful API in PHP. To do shortly, I can register some information by calling an address like http://api.website.com/addInfos
This request is a POST request. Here my method:
File: api.php
<?php
/* Page api.php */
private function addInfos()
{
// Check if it's a POST request and if all fields are correct
// Insert data in my MySQL database
// TODO: make an automatic refresh for page named infos.php
}
?>
Second file, where the data are displayed from my database:
File: infos.php
<?php
/* Page infos.php */
// Connection to database
// Prepare the request using PDO
// Execute the request
// Display infos in a while loop
?>
My question is: How can I refresh the part of code where the data is displayed just after the function named "AddInfos" of my API is called ?
EDIT 1:
Here is what I can do:
File: index.php
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<title></title>
<script src="js/jquery.js"></script>
</head>
<body>
<div id="infos"></div>
<script>
function displayInfo(r) {
$.post("infos.php",
{ refresh : r},
function(data){
//alert("Data Loaded: " + data);
$("#infos").html(data);
}
);
}
$(document).ready(function() {
displayInfo(1);
$('a.info_link_text').click(function(){
alert($(this).text());
});
});
</script>
</body>
</html>
File: infos.php
<?php
require_once('database.php');
if(isset($_POST['refresh'])){
$selectInfos = getAllInfos();
$selectInfos->execute();
echo "<table>";
echo "<th>User</th>";
echo "<th>Email</th>";
while($row = $selectInfos->fetch(PDO::FETCH_OBJ)){
$fullname = $row->user_fullname;
$email = $row->user_email;
echo "<tr>";
echo "<td>".$fullname."</td>";
echo "<td>".$email."</td>";
echo "</tr>";
}
echo "</table>";
}
?>
When I load index.php, I can get the infos from the page infos.php. But I really don't know how can I do this when the method "addInfos" of my API is called, because I need to make a POST request on infos.php (it's OK) but put the result data on index.php (not ok, I don't know how to do that). Please, could you let me know how to achieve this ?
Thank you so much for your help.
Best regards,
Lapinou.
I think what you need is a library based on WebSocket HTML5. The server can retain and send notifications to all clients connected at the same time. Then in your javascript handler, you can process anything you want.
In PHP, you could try these examples WebSocket HTML5 PHP on Google
The other way would be to send multiple REST queries on a regular basis to the server to update your page, but it seems you want real-time updates only.
I've created a Facebook fan page that works as a fan gate / like gate. When the user clicks the "Like" button the page redirects to the wall. I want to override this behavior and have the page redirect back to the Liked version of the fan gate. The app is an iFrame page tab app using the PHP signed request to determine liked/notliked status.
An example of this is http://www.facebook.com/1800flowers
When you like the page, it redirects you to http://www.facebook.com/1800flowers?sk=app_116748578401618
So my search-fu found a piece of JavaScript that was supposed to fix this:
<script type="text/javascript">
if (top != self) top.window.location = 'linkgoeshere';
</script>
I've tried placing this block of JavaScript in both the have liked and have not liked sections of the page. Either way it creates a redirect loop where the page just continually refreshes.
If this code is the answer, where should it be located, and what should "linkgoeshere" be replaced with? There is a possibility I've been using the wrong link.
If this isn't the answer, is there an alternative?
This is a bug on facebook right now, described here - https://developers.facebook.com/bugs/110015112440103
It'd be great to have an interim fix but since the code for the Like button is outside of what's accessible to the page tab, I'm having trouble imaging what a solution might look like, short of removing the address from your page to make it not a "place", which seem to be the only pages affected.
I've been having this problem for the past few days, but today I found the solution. You were right with your suspicions that this is caused by the new recommend dialog box on pages. This box only appears on pages for PLACES. If you have a address assigned to your page then remove it and your fangate will reload in the window when liked and not redirect to the wallpage.
You shouldn't need any JavaScript.
Makes sure you set the "Default Landing Tab" to be your fan gate in the "Manage Permissions" section of the page Admin.
Here is the solution I use. Also, be sure as marked above to set the default landing tab. You will need to download the latest facebook sdk for php, and replace the lines for your app ID, app secret, and the path to your fanpage int he $loginNextPage below.
Notice that there are two places where you can add your own HTML or an include of the page content that should be served for the appropriate audiences.
Also, returning users who liked you pages always get the wall by default, no matter what you set as the default tab. So if they leave and come back, they will get the wall.
<?php
require 'facebook.php';
$app_id = "YOUR APP ID";
$app_secret = "YOUR APP SECRET";
$loginNextPage = 'YOUR FAN PAGE URL'.'?sk=app_'.$app_id;
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$signed_request = $facebook->getSignedRequest();
$page_id = $signed_request["page"]["id"];
$like_status = $signed_request["page"]["liked"];
if ($like_status) {
// FOR FANS
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'next' => $loginNextPage,
'req_perms' => 'publish_stream,photo_upload,user_photos,user_photo_video_tags'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
else {
try {
$access_token = $facebook->getAccessToken();
$fbme = $facebook->api('/me');
$user = $facebook->getUser();
$url = "https://graph.facebook.com/".$user;
$info = file_get_contents($url);
$info = json_decode($info);
$vars = "id=$user&first_name=$info->first_name&last_name=$info->last_name&access_token=$access_token&pathToServer=$pathToServer&appName=$appName";
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
// Begin Like Gated Content.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</head>
<body>
<h1>You Have Liked The Page</h1>
</body>
</html>
<?
}
}
else {
// FOR NON FANS
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
</head>
<body>
<h1>Click Like To View Content</h1>
</body>
</html>
<?
}
?>