Angular JS $http.get does not receive data from PHP script - javascript

I am using angular's $http.get function to call a PHP script file to retrieve data
var $promise = $http.get("../php-bin/example.php",obj).success(function(data) {
console.log(data);
});
The php is supposed to just get data from a mysql db to figure out a way to get data into my app
$user = json_decode(file_get_contents('php://input'));
$email = $user->email;
$pass = $user->pass;
$con = //a mysql_connection;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$validateEmail = "SELECT `Email` FROM `newUsers` WHERE `Email` = '$email' ";
if ($result = mysqli_query($con,$validateEmail)) {
if ($result->num_rows == 1){
$date = '2014-08-13';
//$sql = "INSERT INTO newUsers (Email, CreationDate, UserRef, Type, id) VALUES ('$email','$date','$email','Host','$ssid')";
$sql = "SELECT `email` FROM `newUsers` WHERE `hashpass` = '$pass' ";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);
return $row;
//I never receive this data in the angular app.
}
}
mysqli_close($con);
?>
Could some one point me to the correct way to do this.

I see you have a return statement instead of an echo statement. A return statement is not printed in the PHP output. A return statement outside a function has only sense when you include the file:
$returned = include('the_file_you_showed_here.php');
//you will hold the row here
A return statement kills the current script returning to an includer script (if any), but does not send any value to the output (that's the purpose of die/exit). You should:
Change the return to echo.
Remember to have a header('Content-type: application/json') sent if you intend to send json data, before any actual echo instruction or non-php content.
Remember to encode the data: return json_encode($row).

in your php make sure you echo your result the echoed results get passed into your variable
for example if you are passing in a varibale say from your scope
function($scope,$http){
$scope.obj= "your variable";
$reuslt = http.get('yourlocation/yourfile.php?val='+obj');
your php script
<?
$value = $_GET['val']
//not your variables have been passed in and you can use it to do your custom function wich ever way you like
and echo your result after wards
?>
hope this helps

You cannot call relative paths like that. The file has to exist at the public directory or lower. For instance, if all of your files are in /home/yourname/public, you'd need to call /php-bin/example.php instead, where php-bin is inside of the public directory (/home/yourname/public/php-bin).

Related

Displaying data from a database using Angularjs

Basically what I am trying to do is ng-repeat records from my database, however, I am getting the following error 'SyntaxError: Unexpected token F in JSON at position 0'.
Here is my code:
HTML
<tr ng-repeat="x in data">
<td>{{x.songName}}</td>
<td>{{x.albumName}}</td>
</tr>
JS
$scope.loadTracks = function(){
$http.get('includes/functions/gettrack.php').success(function(data){
$scope.data = data;
})
}
PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
$data = array();
$sql = "SELECT * FROM tracks";
// Create a prepared statement
$stmt = mysqli_stmt_init($connection);
// Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
// Error exists
die('Fatal error: service unavailable at this time');
} else {
// Run parameters inside the database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) > 0) {
// Check for results and assign results to array
while ($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
}
}
?>
I suspect that your code is executing die('Fatal error: service unavailable at this time');. Character 0 of that string is F which matches your error.
The JS will be trying to decode Fatal error: service unavailable at this time which is not valid JSON.
die() does not set an http code so the AJAX request will be considered successful. Try setting the code with http_response_code():
if (!mysqli_stmt_prepare($stmt, $sql)) {
// Error exists
http_response_code(500);
die('Fatal error: service unavailable at this time');
} else {
You should also adjust your AJAX call to deal with the error:
$http.get('includes/functions/gettrack.php').success(function(data){
$scope.data = data;
}).fail(function(){
console.error('AJAX call failed');
});
Alternatively you could change the string being returned within die(), but I would advise that this is not really a good way to fix it.
die('"Fatal error: service unavailable at this time"');
You're missing the connection to the database...
$connect = mysqli_connect($db['hostname'],$db['username'],$db['password'],$db['database']);

Php, Sql query won't let me pass in a variable, i keep getting an empty Array

So i am trying to run a Select query to my database but the query won't work when i pass in a pre defined variable. but it work only when i explicitly type it in For Example 'username', but won't let me pass in variable for example '$username'
So i have a a function in my angular file that is posting information to my php file.
Here is my php file:
<?php
require "loginConnect.php";
if($conn)
{
$gotIt = json_decode(file_get_contents('php://input'));
$username = mysqli_real_escape_string($conn, $gotIt->{"username"});
$password = mysqli_real_escape_string($conn, $gotIt->{"password"});
$myquery = "SELECT Email, Firstname, Lastname, Username, Password, ConfirmPassword FROM Myusers WHERE Username = '$username'";
// creating var to store the server's results
// passing in $conn for connection and $myQuery
$request = mysqli_query($conn, $myquery);
if ($request)
{
echo "the request was made successfully";
}
else
{
echo "the request failed";
}
// declaring an array to store the results objects in
$data = array();
// using the foreach loop to loop thu object in results
foreach ($request as $i) {
$data[] = $i;
}
// closing the connection and display the data
mysqli_close($conn);
echo json_encode($data);
}
else //otherwise connection failed come here
{
echo "sorry bad connection";
}
?>
so when i pass in the $username variable in my query i get nothing even thought i should be getting something, but when i type the username like 'theblackmamba' get what i want. even though the variable containers the same string, the variable is just not working. Please help i am super STUCK!

Passing variable from php to javascript - follow-up

I saw this post Passing a variabe to jquery using Odometer but am unable to comment on it. I had a follow-up question.
Hoping I can get an answer.
I am using this php to pull a value from mysql:
<?php
// Make a MySQL Connection
include("/home/www/php_snippets/dbconnect.php");
//execute the SQL query and return records
$query = "SELECT total_miles, SUM(total_miles) FROM mileage as total_miles";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total Miles". $row['type']. " = ". $row['SUM(total_miles)'];
echo "<br />";
}
//close the connection
mysql_close($dbhandle);
?>
I want to use this script to put this value on my page:
<script>
$(function () {
setTimeout(function () {
//Get the value from serverside
var uid = '<%=odometervalue %>';
odometer.innerHTML = uid;
}, 1000);
});
</script>
The solution says to use a puplic string to declare the variable but I am confused where to use it. In my PHP?
You can use the below implementation to pass the value from code behind to Jquery
This is one example how to do it.
First Declare a Public Variable in code behind
//Declare a Public Variable in code behind
public string odometervalue = "667";
Could I use:
public string odometervalue = total_miles;
In my above php?
I am still learning so please assist if you can :)

.post javascript with PHP to enable select statement return

.post javascript with PHP to enable select statement return
Okay I got this script that is working
$.post('2.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
This is what my 2.php looks like
$data = $_POST['id'];
$file = fopen("test.txt","w");
echo fwrite($file, $data);
fclose($file);
So I did a test, I run 1.php and saw test.txt was created with the data.
this prove the connection was successful.
Now is the difficult part.
I need to send id:12345 to 2.php, and 2.php need to
"select * from account where account_id='$data'";
And then the return result, I think of using MYSQL_ASSOC or MYSQL_BOTH
I not sure which is best.
Then get the result, be it 1 row result or many row result.
Return as an array and then use 1.php to perform
alert( ArrayReturnResult );
Assuming that my account table have this value
account_id, account_name, account_phone, account_email
How do I accomplish this?
Assuming you know how to establish a database connection (using PDO, of course), you could do something like this in 2.php:
if(!empty($_POST)) {
$data = (int) $_POST['id'];
// query the table
$stmt = $pdo->prepare("SELECT * FROM account WHERE account_id = :id");
$stmt->bindValue(":id", $data, PDO::PARAM_INT);
$stmt->execute();
// fetch results
$buffer = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$buffer[] = $row;
}
// output JSON string
echo json_encode($buffer);
}
Of course, this isn't tested... and probably isn't secure if dealing with personal details.
Don't forget to update your $.post method so that it can expect JSON-encoded data:
$.post('2.php', { id: 12345 }, function(data) {
console.log(data); // this will now be a JS object, from 2.php
}, 'json');

Passing JSON object built from SQL from PHP to JavaScript

I am trying to pass a JSON object from PHP to Javascript. the object is being filled from an SQL Database here is the PHP code I am using.
<?php
$conn = mysql_connect("localhost","root","");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db') or die( 'Error'. mysql_error() );
$query = "SELECT * FROM products;";
$results = mysql_query($query, $conn);
$return = array();
while($result = mysql_fetch_assoc($results))
{
$mount = array('product_code' => $results['product_code'], 'colour' => $results['colour'], 'price' => $results['price']);
array_push($return, $mount);
}
return json_encode($return);
?>
I have changed a few of the variable names but the same functionality is there.
now when I try to do an AJAX Get to this .php file it crashes at the JSON.Parse part code shown below:
$.get("JSON.php", function(data) {
var JSONdata = JSON.parse(data);
alert(JSONdata[0].colour);
});
My alert is there just for testing.
I Understand the problem may lie in my building of the $return array. Rather new to JSON, any help would be greatly appreciated.
EDIT: taking all the information from below I have corrected my PHP code to look as such.
<?php
$conn = mysql_connect("localhost","root","");
$error = array("result" => false, "error" => mysql_error());
if(! $conn )
{
die(json_encode($error));
}
mysql_select_db('db') or die(json_encode($error));
$query = "SELECT * FROM products;";
$results = mysql_query($query, $conn);
$return = array();
while($result = mysql_fetch_assoc($results))
{
$mount = array('product_code' => $result['product_code'], 'colour' => $result['colour'], 'price' => $result['price']);
array_push($return, $mount);
}
echo json_encode($return);
?>
I'm Looking into changing the mysql_* functions to new more compatible versions
You are using 'return' at the end of the php script, echo the json encoded string :
echo json_encode($return);
Also, it might be a good idea to set the contenttype header to application/json.
Edit:
If you script fails, you use die('error'.mysql_error());
This will also be a response to the ajax call, but not json, and the parse function will throw an exception.
I would recommend returning a json object instead, like:
$error = array("result" => false, "error" => mysql_error());
die(json_encode($error));
Also as stated in comments, do not use mysql_* functions, they are deprecated in later php versions and will be gone from php all together in future releases.
Check out mysqli or even better, PDO.

Categories

Resources