Angular JS declare controller using data retrieved from PHP file - php

I have a controller declared and I was loading the data from a json file. THat was working fine, so I decided to create a database and a php file to do a select and retrieve the data from the table I am storing it.
The data from php is retrieved on json, this is my code on php:
<?php
$con = mysqli_connect("127.0.0.1", "root", "", "peopledir");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM people");
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
print json_encode($rows);
mysqli_close($con);
?>
It retrieves this:
[{"0":"1","id":"1","1":"Santiago","name":"Santiago"}]
My controller is:
'use strict';
/* Controllers */
var myApp = angular.module('myApp');
myApp.controller('PeopleController', function($scope, $http) {
$http.get('http://localhost').success(function(data) {
$scope.peoples = data;
});
});
But it is not showing any data on the frontend.
To be clear, if I paste the data to a json file, exactly as php is showing it, I can see the user Santiago on the page, but with above code, reading directly from http://localhost, I can not see anything.
Thanks

You should use mysqli_fetch_assoc:
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}

Related

retrieve from database and send to another php file

I have 2 php files one that retrieve from database, other one take each value came from the database. the problem: data is being sent as whole not row by row. so I can not have each value seperatly. I am trying to find smart way to do so.
first file:
$host = 'localhost';
$user = 'root';
$pass = '';
$db_name="bbbb";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = array(); // create an array
while( $row = $result->fetch_assoc()) {
echo $row ['input']; //if my database have 2 rows one with value t1 and other with t2.
}
?>
second file:
<script src = "https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function(){
retrieveData();
});
function retrieveData(){
$.post('quick.php',{}, function(data){
window.alert(data);
});
}
</script>
the output i have is a single alert with (t1 t2)
my desire output to be 2 alerts window. first one with value t1 second with value t2.
try This:
use json to your server side,
while( $row = $result->fetch_assoc()) {
echo json_encode($row['input']);
}
and on your second file:
$.post('quick.php',{}, function(data){
window.alert(data);
},"json");

Simple GET request with AngularJS and PHP, expected JSON but got copy of the php file returned

I'm trying to figure out AngularJS with PHP as backend.
The purpose here is to generate a JSON file from a mysql database, but in return my data variable is a string containing literally the code from my php file.
Here is the code:
The angular controller:
(function (){
"use strict";
var module = angular.module("App");
var CountryController = function ($scope, $http, $log) {
$scope.countries = null;
$http.get('php/get_countries.php')
.success(function(data){
$log.info("data= " + data);
$scope.countries = data;
});
};
module.controller("CountryController", CountryController);
}());
The php file:
<?php
$db = new mysqli('localhost','root','','db_test');
if($db->connect_errno > 0) {
die('Unable to connect to database[' .$db->connect_error. ']');
}
$sql = "SELECT * FROM `country`";
if(!$result = $db->query($sql)){
die('There was an error running the query [' .$db->error. ']');
}
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$item = array();
$item['id'] = $row['country_id'];
$item['name'] = $row['country_name'];
$arr[] = $item;
}
}
header('Content-Type: application/json');
echo json_encode($arr);
?>
The log shows me a copy of the code from the php file.
I compared my code with other examples online with the same purpose, and I can't find anyone who runs into the same problem.
Also I ran the php code in my browser, which returns the correct JSON code. Only when I try to use it in my angular app, I get the php code returned as a string.

Get Data from Mysql instead XML?

hey i have this javascript for a bubble up... this script gets InfoID and InfoData tags from an xml file...
<script type="text/javascript">
$(document).ready( function ( ) {
// Get the XML data from your file
$.get('scores.xml', function( data ) {
// Because we've given jQuery the XML datatype, we can jump straight to finding the element.
$(data).find('Game').each( function ( ) {
// The current object now holds a single "GAME" - find the elements we need
var game_id = $(this).find('InfoID').text( );
var game_info = $(this).find('InfoData').text( );
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
}); // end of each
}, 'xml'); // The 'xml' tells jQuery to expect XML back from the request
});
</script>
i need to make this script get data from Database table instead of xml.
i have the same InfoID and InfoData rows in a table in my database...
i use this php script to get data from db:
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
<?php echo $row['Header'].""; ?>
<?php echo $row['Row'].""; ?>
<?php echo $row['Date'].""; ?>
<?php echo $row['Time'].""; ?>
<?php echo $row['AwayTeam'].""; ?>
<?php echo $row['Score'].""; ?>
<?php echo $row['HomeTeam'].""; ?>
<?php echo $row['Other'].""; ?>
<?php echo $row['InfoID'].""; ?>
<?php echo $row['InfoData'].""; ?>
<?php } mysql_close(); ?>
any idea how i can do that? so i can remove my xml file and use database :)
Thanks in advance.
You could use an ajax post with a seperate callback function and return json data from your php script.
Give this a shot:
// try this for your javascript
<script type="text/javascript">
$(document).ready( function ( ) {
function getGameInfo() {
$.post("path/to/phpScript.php",
// this is the success callback
function (json) {
// this calls the function with the returned data
parseReturnedData(json);
});
return false;
};
// process json data to set your game_id and game_info vars
function parseReturnedData(data) {
var obj = jQuery.parseJSON(data);
var game_id = obj.InfoID;
var game_info = obj.InfoData;
}
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
</script>
// try this for your php file
<?php
// declare vars
$response = array();
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
$response['Header'] = $Header;
$response['Row'] = $Row;
$response['Date'] = $Date;
$response['Time'] = $Time;
$response['AwayTeam'] = $AwayTeam;
$response['Score'] = $Score;
$response['HomeTeam'] = $HomeTeam;
$response['Other'] = $Other;
$response['InfoID'] = $InfoID;
$response['InfoData'] = $InfoData;
}
echo json_encode($response);
mysql_close();
?>

Inserting a javascript code into php

I am searching for possibility to include a javascript function into a php code.
The code should get the results from the search php file and then print them out in form of a Javascript Playlist.
This is the javascript code:
<script type="text/javascript">
$(document).ready(function(){
var description = '';
var myPlaylist = [ {
mp3:'./../sounds/mysql-upload',
title:'mysql-title',
artist:'mysql-artist',
subcategory:'mysql-subcategory',
date:'mysql-date',
rating:'mysql-rating',
},
/* var myPlaylist has to repeat */
];
$('#main').ttwMusicPlayer(myPlaylist, {
autoPlay:false,
description:description, }
);
});
</script>
And here is the php code:
<?php
if (!empty($_POST['search'])) {
/* Connect to database */
$hostname = '';
$database = '';
$username = '';
$password = '';
if (!($mysql_link = mysql_connect($hostname, $username, $password))) {
die('Could not connect');
}
/* Select databse */
if (!($db_selected = mysql_select_db($database, $mysql_link))) {
die('Could not find database');
}
/* Send mysql command */
$sql_cmd = "SELECT * FROM sounds WHERE `keywords` LIKE '"
. $_POST['search']."%'";
if (!($res = mysql_query($sql_cmd))) {
die('Invalid MySQL query');
}
/* Show results */
while ($dsatz = mysql_fetch_assoc($res)) {
$upload = $dsatz["upload"];
$title = $dsatz["title"];
$artist = $dsatz["artist"];
$subcategory = $dsatz["subcategory"];
$date = $dsatz["date"];
$rating = $dsatz["rating"];
/* Here should be the Javascript code */
}
/* Close database connection */
mysql_close($mysql_link);
}
?>
Please note that I don't want to include the full Javascript function in the results part of the php code but the playlist variable which should repeat.
In PHP, you can make an array, and fill it with arrays of those attributes.
Something like:
$results = array();
while ($dsatz = mysql_fetch_assoc($res)) {
$results[]=$dsatz; }
$printout = json_encode($results);
Now to put it into the JavaScript, you'd do this:
var myPlaylist = <?php echo $printout; ?>;
If I understood you correctly, you'll need AJAX for doing that. Here's some places to start with:
W3Schools AJAX Tutorial
Tizag's AJAX Tutorial
Also, as you're already using JQuery, it can make your life with AJAX much easier.
Take a glance to JQuery AJAX API at http://api.jquery.com/category/ajax/
this is fairly possible, but how abt using json instead. JSON encoded string can be generated in php via json_encode($array) You can then, possibly using AJAX, load the json into the current page.
The other option is, generate javascript arrays from the php code, and then include the javascript array on to the web page.

Using jQuery and php to pull data from database

I have a page that is pulling data through jQuery but it is only pulling the return code. Here is my code:
<script type='text/javascript' language='javascript'>
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val()
},
function (response) {
$('#contact').val(response).show();
$('#email').val(response).show();
$('#phone').val(response).show();
})
}
</script>
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . $_POST['id'] . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
if (mysql_num_rows($query) > 0) {
while ($get = mysql_fetch_array($query)) {
$priContact = $get['priContact'];
echo $priContact;
echo $get['priEmail'] . " | " . $get['priPhone'];
}
} else {
echo "No users";
}
So the call is pulling from getCU.php whenever the onchange event handler is called. That is why this is in a function. What I want to do is every time a user chooses something from the option list the text values change according to what was selected. I have the php page pulling from a db and echoing out the code correctly. jQuery id pulling the data from the php page correctly, but I cannot get the code to place the single details in each of the text boxes.
So what I want to happen is this:
A user selects a name from a drop-down box. Then the mysql data attached to that name would be displayed on the page in form text fields.
Let me know if more information or code is needed.
I think you'll be better off structuring your data. My general recommendation is JSON.
// QUICK WARNING: Don't take unparse GET/POST responses.
// This is asking for trouble from SQL injection.
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . mysql_escape_string($_POST['id']) . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
$retVal = array();
if (mysql_num_rows($query) > 0) {
$retVal['data'] = array();
while ($get = mysql_fetch_array($query))
{
$retVal['data'][] = $get;
}
} else {
$retVal['error'] = 'No users';
}
header('Content-type: application/json');
echo json_encode($retVal);
Javascript:
<script type="text/javascript">
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val(),
dataType:'json'
},
function (response) {
if (response.error) {
//handle error
}
else
{
$('#contact').val(response.data.priContact).show();
$('#email').val(response.data.priEmail).show();
$('#phone').val(response.data.priPhone).show();
}
})
}
</script>

Categories