Pull mySQL data via PHP into an array of Javascript objects - javascript

i am trying in pull my data from mySQL and convert it to a format I can then pass to google.maps API. I am thinking mySQL -> php -> javascript -> google.maps makes the most sense but am deffinitly open to other suggestions.
So far I have connected to and successfully queried my data into an array
<?php
//library of mysql functions including linkDB()
include('../sqlFunctions/sqlFunctions.php');
//Establish connection to database
if($link = linkDB()){
echo "connected to DB";
}
//set up a MySQL query. I am simply pulling geocoordinate ints, strings and boolean.
$sql = "SELECT title
,lat
,lng
,titleYou
,descriptionAre
,privacyRockstar
FROM shelters;";
if($results = $link->query($sql)){
echo "<p>Query succsessful.</p>";
}else{
echo "Query Failed";
}
//initialize an array to store data
$rows = array();
while ($data = $results->fetch_assoc()) {
$rows[] = $data;
echo "<br><br>Loop rotation: ";
var_dump($data);
}
echo "<br><p>The End of The Loop<p><br>";
var_dump($rows);
?>
Now I just need to convert this data into something usable I can pass to google.maps.
Before I was pulling JSON from a text file, which worked, but I want to flexibility and stability of a database. It was easy to parse into and array of Javascript Objects. Then I could just call the index and the property that I needed as you can see from this function I was using.
function setMarkers(){
for(i=0; i < jsonParsed.arrayOfObjs.length; i++){
//setting parameters to hand to google
var markerOptions = {
position : jsonParsed.arrayOfObjs[i].position,
map : mapCanvas,
description : jsonParsed.arrayOfObjs[i].title,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
};
//create marker
this ['marker' + i] = new google.maps.Marker(markerOptions);
}
}
Thank you for any light you can help shed on my issue.

It sounds like you already found your answer but I'll post for completeness.
Simply change your the var_dump($rows) line to json_encode($rows).
Read more about json_encode in the php docs.
You probably want to have two php files:
api.php file that emits Content-type: application/json
index.php file that emits Content-type: text/html and calls api.php
On the index page, you can make an AJAX call to your API endpoint and then use JSON.parse(response).

Related

How to parse sql result?

End my sorrow.
I make an ajax request to this file.
I want to get all the posts from database. Then stylise these posts and display it to the user.
But I couldn't figure out how to parse these from js.
...
$result = $conn->query($sql);
//Iterate the rows
while($row = $result->fetch_assoc())
{
//todo
}
...
//jsfile
...
var response = this.responseText;
//get the response but how to parse ?
From your Post, you sound like you want to send some Data obtained from your Database Transactions to the Requesting AJAX Script, right? If that is the case; you may have to do all the usual Processing of your DB Data and (if necessary) build them up as an Array or Object within your PHP File. Afterwards, you encode the resulting Data to JSON using json_encode() and then lastly push the JSON-Encoded Data back to the requesting AJAX Script. To illustrate; here (below) is a Mock example using bits & pieces of the Code you posted:
<?php
// PERFORM SOME DATABASE TRANSACTIONS....
$result = $conn->query($sql);
// IF YOU NEED TO BUILD-UP A SPECIAL DATA STRUCTURE TO MEET WITH
// THE NEEDS OF YOUR APP. YOU MIGHT DO THAT HERE.
// WE CREATE AN ARBITRARY ARRAY: $payload TO HOLD THE ARBITRARY DATA...
$payload = [];
// LOOP THROUGH THE RETURNED RESULT-SET / ROWS OF DATA
while($row = $result->fetch_assoc()) {
// WE PRETEND FOR NOW THAT WE NEED CERTAIN VALUES FOR THE APP
// THAT WILL BE CONSUMED BY THE REQUESTING AJAX SCRIPT
// SO WE BUILD IT HERE:
$tempData = []; //<== TEMPORARY ARRAY TO HOLD A COLLECTION
$tempData[] = $row['firs_name'];
$tempData[] = $row['last_name'];
$tempData[] = $row['address'];
$tempData[] = $row['email'];
$tempData[] = $row['avatar'];
$tempData[] = $row['telephone'];
// NOW PUSH THE COLLECTION OF RELEVANT DATA GATHERED
// FROM THE ITERATION INTO THE PAYLOAD VARIABLE: $payload
$payload[] = $tempData;
}
// OK: WE HAVE OUR PAYLOAD, READY TO BE SENT BACK AS JSON...
// SO WE NOW ENCODE THE PAYLOAD TO JSON DATA STRUCTURE.
$jsonData = json_encode($payload);
// THAT'S ALMOST IT....
// THE NEXT THING WOULD BE TO SHIP THESE DATA TO THE REQUESTING SCRIPT
// WHICH WE SHALL DO HERE WITH A SIMPLY die() STATEMENT LIKE SO:
die($jsonData);

JavaScript cannot find JSON data from PHP json_encode

The idea here is to automatically load (or load at all) my index page with some products out of a MySQL database table.
Firstly, my PHP.
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
echo json_encode($itemsJSON);
}
This seems to be working great, and gives me two properly encoded JSON objects of my Item class.
{"name":"Slippers","quantity":"3","cost":"4.00"}
{"name":"Gloves","quantity":"5","cost":"9.00"}
My JavaScript looks like this(and many other similar variations)
$(document).ready(function () {
$.post( "productloader.php", function( data ) {
$( "#result" ).html( data );
});
});
I'm not sure why it is not working. I did not want to use $.getJSON() because there is no query string to work with, so I'd assume I would need $.post().
It seems like this is a pretty common issue, but I've not found a solution yet. Any help would be appreciated. Thank you.
You can't json_encode() each item separately. The data you're sending to the browser is not valid JSON, just many little chunks of valid JSON one after the other. Build an array inside your loop and then encode the whole thing. See also http://jsonlint.com/
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON[] = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
}
echo json_encode($itemsJSON);
In your method of AJAX, you're outputting multiple JSON strings while the js side is expecting 1 string (data). Try removing your for loop to just:
echo json_encode($items);
You are creating JSON for each row, so you are getting separate JSON objects for each row in front end.
You should put all row in to and array and create the JSON object outside the loop, and echo the encoded JSON string.
<?php
$allitem = $db->getRows('SELECT * FROM products');
$itemArr=array();
foreach($allitem as $item){
array_push( $itemArr , new Item($item->product_name, $item->product_quantity, $item->product_cost) );
}
echo json_encode($itemArr);
?>
or
$allitem = $db->getRows('SELECT * FROM products');
echo json_encode($allitem );

PHP json_encode then getJSON issue in javascript

Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !
Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.

Mysqli query is returning a null value for a simple row of strings from a DB

I am trying to retrieve a single row from a MySQL table using a mysqli statement. I've tried several different iterations of code, subtly changing the structure based on various previous questions from this forum, and others, but can't seem to get any result other than 'null'.
This is part of a larger script which is called via an Ajax request with jQuery. I've included both the PHP and the Javascript below, though I'm fairly confident in the JS being OK (preparing to be told otherwise now...).
Any suggestions as to where I'm going wrong would be very much appreciated as I can't see the wood from the trees anymore, and am just going around in circles.
PHP:
//initiate new mysqli object
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name); //custom subclass, this definitely works as is used in other scripts on the server
//prepares DB query. Query has been tested on phpmyadmin and returns the expected data set
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute(); //no params to bind, so execute straight away
$stmt->bind_result($item);
$stmt->fetch();
$dataset = $item->fetch_row();
$response[0] = $dataset; //returned data forms part of larger dataset
echo json_encode($response); //return the entire dataset to a jquery Ajax request
die;
JS:
//this definitely works as objects have been returned via the 'success' function as the code was being developed
$.ajax({
url : "items/populate-home-page-script.php",
type : "GET",
data : {data:toSend},
dataType : "json",
success : function(data){
alert(data[0]);
},
error : function(jqXHR, textStatus, errorThrown){
alert(textStatus+','+errorThrown);
}
});
return false;
I have also tried using fetch_assoc() and fetch_row() as part of the PHP query, taking direction from the PHP reference material here and here. I have also read through these questions from Stackoverflow this, this, and this, but I still seem to get a return of null for every different code combination I try.
As I've said in a code comment, I know that the link to the DB works as I've used it in other scripts, and in other areas in this script - so there's no reason why this object wouldn't work either. I also know that the query returns the expected data when inputted to phpmyadmin.
The returned data is just a number of strings, any all I would like to do is store around 16 returned datasets to an array, as part of a loop, and then return this array to the Ajax request.
You are using "AuctionMySQLi" which appears to extend the regular Mysqli driver. I'll assume it does this correctly.
You're using prepared statements which is probably an overkill in this case. You could accomplish the same thing with something like this (php 5.3, mysqli + mysqlnd):
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
echo json_encode($result->fetch_all());
} else {
echo json_encode(array());
}
$retrieve_link->close();
If you're using an older php version, or mysqlnd is not available, you can also do
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
$output = array();
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
echo json_encode($output);
} else {
echo json_encode(array());
}
$retrieve_link->close();
I also understand that you want to limit the number of results. In both cases, a good way of getting it done is to use a LIMIT statement in SQL. This is lower the overhead overall at source. Otherwise you can array_slice to slice the output of result->fetch_all() in solution 1, or $output in solution 2.
Finally, if you insist in using prepared statement read the note at
http://ca2.php.net/manual/en/mysqli-stmt.bind-result.php
and analyze provided example:
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute();
$stmt->bind_result($itemName, $itemCat, $endDate, $auctionType, $highBidder);
$output = array();
while($stmt->fetch()) {
$output[] = array($itemName, $itemCat, $endDate, $auctionType, $highBidder);
}
echo json_encode($output);
$retrieve_link->close()
It looks to me like you may have some confusion about ->fetch() and ->fetch_row(). You should use one or the other, but not both.
Try this to retrieve your result set:
$stmt->execute();
while ($dataset = $stmt->fetch_row()) {
$response[] = $dataset; //returned data forms part of larger dataset
}
This will append each row of your result set to your $response array.

Connecting to a MySQL database using PhoneGap, AJAX, and JQuery Mobile

I'm in a team developing an Android application that will rely greatly on the use of a remote database. We are using PhoneGap and Jquery Mobile and have been attempting to connect to our MySQL database using AJAX and JSON calls. Currently, we are having trouble in our testing phase, which is to verify we even have a connection at all by pulling a hard-coded user of "Ted" from mySQL / input via MySQL Workbench.
From what we have gathered, the process of data transmission works as this:
On our html file, we have a
<script type="text/javascript" src="Connect.js"></script>
^ Which should run the Connect.js script, correct? So from there, Connect.js is ran?
Connect.js runs, connecting it to our ServerFile.php that is hosted on an external web service, allowing it to run PHP to connect to the MySQL database and pull information.
//run the following code whenever a new pseudo-page is created
$('#PAGENAME').live('pageshow', function(event)) {
// cache this page for later use (inside the AJAX function)
var $this = $(this);
// make an AJAX call to your PHP script
$.getJSON('http://www.WEBSITENAME.com/ServerFile.php', function (response) {
// create a variable to hold the parsed output from the server
var output = [];
// if the PHP script returned a success
if (response.status == 'success') {
// iterate through the response rows
for (var key in response.items) {
// add each response row to the output variable
output.push('<li>' + response.items[key] + '</li>');
}
// if the PHP script returned an error
} else {
// output an error message
output.push('<li>No Data Found</li>');
}
// append the output to the `data-role="content"` div on this page as a
// listview and trigger the `create` event on its parent to style the
// listview
$this.children('[data-role="content"]').append('<ul data-role="listview">' + output.join('') + '</ul>').trigger('create');
});
});
Here is ServerFile.php. This should connect to the MySQL Database, make the Select statement, and then send the output to the browser encoded in the JSON format.
<?php
//session_start();
$connection = mysql_connect("csmadison.dhcp.bsu.edu", "clbavender", "changeme");
$db = mysql_select_db("cs397_clbavender", $connection);
//include your database connection code
// include_once('database-connection.php');
//query your MySQL server for whatever information you want
$query = mysql_query("SELECT * FROM Users WHERE Username ='Ted'", $db) or trigger_error(mysql_error());
//create an output array
$output = array();
//if the MySQL query returned any results
if (mysql_affected_rows() > 0) {
//iterate through the results of your query
while ($row = mysql_fetch_assoc($query)) {
//add the results of your query to the output variable
$output[] = $row;
}
//send your output to the browser encoded in the JSON format
echo json_encode(array('status' => 'success', 'items' => $output));
} else {
//if no records were found in the database then output an error message encoded in the JSON format
echo json_encode(array('status' => 'error', 'items' => $output));
}
?>
Yet nothing is showing here. What do we do from here?
First thing first. Try to determine where is the problem come from, server side or client side.
Print out your database query and encoded json can be useful. If you are creating a simple API service, you should be able to enter http://www.WEBSITENAME.com/ServerFile.php using your browser and look how the output is.
Use echo to print things with php.
If all looks ok, time to print out the response you receive from the server in the javascript and see what is off.
Use console.log to print thing with javascript. The logs should appear in the logcat section of eclipse (since you are developing android app)

Categories