Passing JSON object built from SQL from PHP to JavaScript - 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.

Related

JQuery tokeninput: [Error] TypeError: undefined is not an object (evaluating 'term.replace')

I'm using http://loopj.com/jquery-tokeninput/ because I needed to interface a select box directly to DB.
I wrote the PHP script that accept GET request like explained on his GitHub:
<?php
require_once('sondaggio.php');
# Connect to the database
$s = new Sondaggio();
# Perform the query
$query = sprintf("SELECT id, nome from Regioni WHERE nome LIKE '%s%' LIMIT 5", $s->getRealEscapeString($_GET["q"]));
$arr = array();
$arr = $s->readFromDB($query);
# JSON-encode the response
$json_response = json_encode($arr);
# Return the response
echo $json_response;
?>
Class Sondaggio constructor:
function __construct(){
$this->conn = new mysqli($this->host, $this->user, $this->password, $this->database);
// Check connection
if ($this->conn->connect_error) {
exit("Connection failed: " . $this->conn->connect_error);
}
}
function readFromDB($query):
public function readFromDB($query){
$arr = array();
$result = $this->conn->query($query);
if ($result->num_rows > 0){
while($row = $result->fetch_object()) {
$arr[] = $row;
}
}
return $arr;
}
All is tested and works good, the output is correct following his documentation. However I get an error when I start to type into the selectbox:
[Error] TypeError: undefined is not an object (evaluating 'term.replace')
regexp_escape (jquery.tokeninput.js:828)
find_value_and_highlight_term (jquery.tokeninput.js:844:88)
(anonymous function) (jquery.tokeninput.js:899)
each (jquery.min.js:2:11781)
populateDropdown (jquery.tokeninput.js:896)
success (jquery.tokeninput.js:1031)
o (jquery.min.js:2:14739)
fireWith (jquery.min.js:2:15504)
w (jquery.min.js:4:12484)
d (jquery.min.js:4:18320)
So I'm stuck with this error and I don't know why it appears, please help me. Thank you
EDIT:
var_dump($json_response) (with ...php?q=t) output:
string(75) "[{"id":"16","nome":"Toscana\r"},{"id":"17","nome":"Trentino-Alto Adige\r"}]"
Solved, just a mistake.
According to http://loopj.com/jquery-tokeninput/ documentation:
Your script should output JSON search results in the following format:
[
{"id":"856","name":"House"},
{"id":"1035","name":"Desperate Housewives"},
...
]
Here fields are 'id' and 'name'.
My query instead asked the DB for 'id' and 'nome':
$query = sprintf("SELECT id, nome from...
So I just updated the query like this:
$query = sprintf("SELECT id, nome as name from...
Now all works correctly!

Mysqli(or PDO) and PHP to Javascritpt array through JSON

I have researched this question thoroughly. I know there are similar posts but there is simply something wrong with the code. I am fetching all rows from my database through PHP/PDO script (have also tried the similiar MYSQLI version). I then use json_encode to send the results back to the javascript/jquery.
What ever it is, i can send any other type of data through the json and print it through the javascript. But I can't seem to get the array stored in $arr stored in the javascript allArray.
I have tried JSON.parse(allArray) with no luck.
getAllData.php
<?php
header('Content-Type: application/json;');
$a = "bob";
$b = "george";
$arr = [];
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=guessthe_bob;host=localhost';
$user = 'guessthe';
$password = '***';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sth = $dbh->prepare("SELECT id,title FROM questions2 ORDER BY id");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
//print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
$arr = $result;
echo json_encode($arr);
// Free result set
$sth = null;
$dbh = null;
?>
.js
$.getJSON("functions/getAllData.php", function(data) {
var allArray = data;
$.each(allArray, function(index, value){
$('.testSpot').append(index + ": " + value + '<br>');
});
}
null

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!

.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');

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

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).

Categories

Resources