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.
Related
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.
For a website I wanted to realize a type ahead search with typeahead.js from twitter to gather information from a local database. For the first step I was looking for some easy code which I found on a blog here.
My developing enviroment is a local XAMP stack on a Mac. I know all the basics about AJAX and created some good working stuff with simple javascript. I am new to jQuery and just copied the code from the blog website. I loaded down newest jQuery and typeahead.js framework and implemented it as the blog website recommends it. jQuery is initiated properly, but I cant control if typeahead.js is initiated properly. Bootstrap I left out at this step assuming that its not relevant for my test. I simply wanted to catch the Ajax call in PHP. But finally I have no success. This is the basic code.
<head>
<meta http-equiv="Content-Language" content="en-us">
<title>PHP MySQL Typeahead Autocomplete</title>
<meta charset="utf-8">
echo '<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>';
echo '<script type="text/javascript" src="js/typeahead.jquery.min.js"></script>';
<script>
$(document).ready(function() {
$('input.city').typeahead({
name: 'city',
remote: 'city.php?query=%QUERY'
});
})
</script>
</head>
<body>
<div class="content">
<form>
<h1>Try it yourself</h1>
<input type="text" name="city" size="30" class="city" placeholder="Please Enter City or ZIP code">
</form>
</div>
</body>
</html>
And here is the city.php for for simple catching the AJAX call and sending back the query.
<?php
if (isset($_REQUEST['query']))
echo json_encode(array('label' => 'success', 'value' => $_REQUEST['query'] '));
else
echo json_encode(array('label' => 'no success', 'value' => $_REQUEST['query'] '));
?>
All the code should do here is showing that typeahead and AJAX works. But it doesnt. And I do not know why.
So my questions are :
Is the remote key in the jQuery function properly setup ?
The php code uses the $_REQUEST variable, other code refer to $_GET. What is correct ?
With javascript I can log to the console easily on the AJAX callback with console.log(...). How do that with jQuery ?
Any help is appreciated.
So I have this situation, can somebody advise how to deal with it.
Using server side code take the JSON output from an unreliable API
supplied by a client, and render the data on a page in an appropriate
format.
The API URL given returns time series data that represents the
performance of a set of websites in Google rankings over a period of 30
days.
The client’s API URL is:
https://tools.ayima.com/techtest/api/marketintel
However, the client does not want the API endpoint exposed on the
public internet. The API is also slow and very unreliable, so you cannot
simply fetch the API data using JavaScript directly. You’ll need to use
some kind of server side code to get the API data for the page first.
The API is very slow and will sometimes just fail all together with a 503
HTTP status and an empty body, so your code should implement some
kind of cache or database as well as logic to retry failed requests. For
this test the actual data returned will never change, but for the purposes
of cache invalidation you can assume the data would normally change
every 24 hours.
You may either output the page/front end code using the same backend
script, directly including the output from the API in the source, or simply
print/proxy the JSON and fetch the data using AJAX in separate front
end code - whatever you feel most comfortable doing.
I tried to get the data with php so original API is hiden and after use angularjs to fetch it.
This would be my php to fetch the data
<!DOCTYPE html>
<html>
<body>
<?php
$homepage = file_get_contents('https://tools.ayima.com/techtest/api/marketintel');
echo htmlentities($homepage)
?>
</body>
</html>
And this would be angularjs part
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in ayima">
<p>{{ x.domain }}</p>
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://94.136.40.103/~boyisbadnews.com/test/marketintel.php")
.success(function (response) {$scope.ayima = response.marketIntel;})
.error(function(data, status, headers, config) {
// something went wrong
});
});
</script>
</body>
</html>
But can't make it work.
The php file (marketintel.php) to fetch the data of the server must be:
PHP File:
<?php
header("Content-Type: application/json");
header("Cache-Control: no-cache");
$homepage = file_get_contents('https://tools.ayima.com/techtest/api/marketintel');
echo $homepage;
?>
HTML File:
I've seen that you have a little errors in your markup. Here there is a proper html.
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>Page title</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div data-ng-controller="customersCtrl">
<ul>
<li data-ng-repeat="x in ayima">
<p>{{ x.domain }}</p>
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://dfjb.webcindario.com/dataAyima.php").success(function(response) {
$scope.ayima = response.marketIntel;
})
.error(function(data, status, headers, config) {
// something went wrong
});
});
</script>
</body>
</html>
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 have a javascript bootkmarklet that the user can load into what ever webpage they are on.
This then displays a php generated page over the top of the current webpage, this includes some information that the javascript has take from the page the user is on.
What I now need is to be able to have the javascript first run one php file that connects with a mysql database, have the result from the database returned to the javascript which can then call the php file that generates the page overlay.
What I am looking for really is a way for the process to go:
User runs javascript --> javascript runs php for mysql --> javascript gets mysql result back --> javascript runs second php file
Here is a starting point of how to use the ajax features in JQuery.
Edit - separate javascript file
html file:
<html>
<head><title> Ajax test page</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="ajaxfunctions.js"></script>
</head>
<body>
<div id="ajaxResult"></div>
</body>
</html>
js file called 'ajaxfunctions.js':
$(document).ready(function() {
$("#ajaxResult").load("ajaxHello.php");
});
php file called 'ajaxHello.php':
<?php
header("text/html");
echo "hello from php";
?>
To read data from a database the php code needs to be a little longer:
<?php
header("text/html");
$username = "root";
$password = "";
$databaseName = "mydatabase";
$connect = mysql_connect("localhost",$username,$password);
if (!$connect) die("Connection Error");
$result = mysql_select_db("$databaseName");
if(!$result) die("Select DB Error");
$result = mysql_query("select email from users where firstname='Abbey'");
if (!$result) die('Invalid query: ' . mysql_error());
$row = mysql_fetch_assoc($result);
echo "Abbeys email address ".$row['email'];
?>
This examples looks up Abbeys email address from the users table in the users database and returns it. The Database name, username and password are all set at the top of the script.
Usually the ajax request passes some data from the html page, I am happy to add this code if this helps.
Is this something like what you are looking for?