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

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)

Related

Pull mySQL data via PHP into an array of Javascript objects

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

When I store a javascript variable in mysql, how does it get linked to the current user's id?

Let's say there is a site that has a button that uses javascript to increase the value of the javascript variable "javascriptx" by +1 each time it is clicked. UserA (id=1 on the MySql table) logs in to the website and presses the button 3 times, so javascriptx = 2.
The next time UserA logs in, I want javascriptx to still equal 2 (assuming the button hasn't been pressed any more times), so I need to convert that javascript variable to a php variable and send it to MySql. As far as I understand, this is the correct way to do that:
Add the following to the javascript code:
var xhr = new XMLHttpRequest();
xhr.open("get","/path/to/php/page.php?phpx=javascriptx");
xhr.send();
Now, the php variable "phpx" has the same value as the javascript variable "javascriptx"
Then, that php variable needs to be sent to the MySql table, so the following is added to the php code:
($_GET['phpx'])
From here, I get lost. Where does phpx get stored in the MySql table? More specifically, how does it know to put this in the same row as user with id=1?
You should connect to the MySQL database using something like mysqli:
$database = new mysqli(db_host, db_username, db_pass, db_name);
Then you can make queries to your database with prepared statements to read/write data. In this rough example, the data will return a JSON response to your web application or wherever you make the request from:
//set user id from post variable
$uid = $_POST['uid'];
//store sql query as string
$sql = "SELECT phpx FROM users WHERE uid=?";
//initiate new prepared statement
$stmt = $database->stmt_init();
$stmt->prepare($sql);
//pass uid var to statement
$stmt->bind_param('s', $uid);
//store result as var
$stmt->bind_result($phpx);
$stmt->execute();
//catch errors
if ($stmt->errno) {
die("error: " . $stmt->error);
} else {
//store result and send as response
$stmt->store_result();
if($stmt->num_rows){
while($stmt->fetch()){
$phpx_packet[] = array(
"uid" => $uid,
"phpx" => $phpx
);
}
echo json_encode($phpx_packet);
}
}
//close statement
$stmt->close();

Cannot use echo after connection to database

I'm using ajax to send a request to php with some text.
$.get("process.php", { finalQuery : finalQuery }, function(data) {
alert("Data Loaded: " + data);
});
I know this works because in php I can put
$val = $_GET['finalQuery']; echo $val;
And it outputs the correct data.
However, if I put
$db = pg_Connect("host=localhost port=5432 dbname=Blah user=postgres password=1888");
pg_close($db);
It stops echoing the results back to javascript. If I use a different port or name, and it doesn't connect, it then goes back to sending the data to javascript and outputting the correct data.
So basically, when I connect to the database, I cannot communicate my results back with echo. What am I doing wrong?
EDIT(update):
Here's the complete php code
<?php
$val = $_GET['finalQuery'];
echo $val;
$db = pg_Connect("host=localhost port=5432 dbname=Blah user=postgres password=1888");
$result = pg_query($db, 'SELECT gid FROM "Perfect"');
while ($row = pg_fetch_row($result)) {
echo "gid: $row[0]";
echo "<br />\n";
}
pg_close($db);
?>
However, the problem still occurs as long as I use pg_connect. All the other lines can be removed and the problem persists. As long as I remove the pg_connect, the problem disappears and I can send the information back through echo
NEW EDIT(debugging) :
The connection to the database and the php code seems ok. After loading the php page with
error_reporting(-1);
ini_set('display_errors', 'On');
no errors are logged on the page, and the connection to the database is returning all the data properly on every page load.
The problem arises when I'm trying to connect to the php through javascript.
The page loads the data properly sometimes, but it's random, and most of the time nothing happens (not even php logged errors). If you there's no way the javascript-php connection isn't the problem then I'll keep debugging the code.
Here's the steps I'd take for debug:
Begin by ensuring the DB is running and that you can send it a query
successfully via console window DB GUI Tool (Navicat is my gui of
choice for DB's)
Load the PHP page directly. Check for output of
expected code or fatal PHP Errors
Check the browser console for errors. Since it appears to be a PHP
only page, this should be entirely clear of problems.
Check PHP logs
Check Postgres logs
More than likely, something between Postgres and PHP is the problem. Post any errors back on your question if you're still stuck after finding a clue.

AJAX Request from Table Rows to Details

This is my first time on here so I'm sorry if I'm not quite up to snuff with all of you.
In the process of learning AJAX so I'm brand new, but need to get a page done for our staff website.
I have a page (php) which builds a list through a mysql query of all patients. I have absolutely no problem with this. However, I'm stuck on this part.
When a user clicks a specific row (aka Patient Name), I want it to pull up the details of that patient associated with it in our mysql database on the right-hand side so the page doesn't have to refresh and they aren't directed to any other pages.
I have seen examples like this when it came to customers, like you click the name and a div appears to the right containing email, phone, etc. etc.
Does anyone have any good starting points? I have searched as far as I can, and I'm beginning to think I'm not using the right language when searching for my answer.
Thanks ahead of time... Matt
Use jQuery.
First you need to make a web service on your server. The web service will accept a, let's say, POST parameter which will be either patient name or the patient ID. Based on this id/name you will query your MySQL database, fetch all the details and return as json.
On the front end, you can use jQuery.post(). You will need to pass the appropriate URL and the data. In return, you will get JSON data. In the success callback method of jQuery.post/$.post you can create a div on the right and display those data.
If you are going to return the data in json format, you can also just use $.postJSON()
Please make sure to set the appropriate headers in your PHP webservice. These two are probably the most important
Content-Type: application/json // if you are gonna return the data in JSON format
Access-Control-Allow-Origin: * // to let the browser pass the data to the DOM model. This is to allow CORS (Cross Origin Resouce Sharing)
SAMPLE:
example.php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['patientID'])) {
$patientID = $_POST['patientID'];
$data = array();
// Enter the appropriate details below
$mysqli = new mysqli("host", "username", "password", "db_name");
/* check connection */
if ($mysqli->connect_errno > 0) {
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
$statement = $mysqli->prepare("SELECT * FROM `patients` WHERE `patientID` = ? LIMIT 1");
$statement->bind_param('i', $patientID);
$statement->execute();
// You need to write a variable for each field that you are fetching from the select statement in the correct order
// For eg., if your select statement was like this:
// SELECT name, COUNT(*) as count, id, email FROM patients
// Your bind_result would look like this:
// $statement->bind_result($name, $count, $id, $email);
// PS: The variable name doesn't have to be the same as the column name
$statement->bind_result($id, $name, $email, $phone);
while ($statement->fetch()) {
$data["id"] = $id;
$data["name"] = $name;
$data["email"] = $email;
$data["phone"] = $phone;
}
$statement->free_result();
echo json_encode($data);
}
example.html
Patient #123
example.js
function getPatientData(element) {
var patientID = $(element).attr("id");
$.post("example.php", {"patientID": patientID}, function (data) {
// display the data in appropriate div
}, 'json');
return false;
}
You should do an jquery ajax call on element click
$('.patientClass').on('click', function() {
var patientid = $(this).attr('id');
// attr('id') should be the patients id
$.ajax({
url: "getPatientDetailsURL.php",
type: "post",
data: {
id: patientid
},
success: function(response) {
// create div with response details or append parsed json to existing div
}
});
)}
And on the backend get the patiend id with (int)$_POST['id']
Also you on the backend you can set the page to respond only to ajax calls like this:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//code here
} else {
// not ajax call
}

How to get MySQL query result returned using $.ajax

i'm trying to update is a javascript which when you hover over an image, a div object floats near your mouse with information, this information is stored in a .js file as an array,
eg.
Text[0]=["image 1","data 1"]
Text[1]=["image 2","data 2"]
in the past if this array is change/data added to/removed from it would require uploading a new copy of the .js file, if data was added to/removed from it would also require a change to the .dwt file for the new image which would update every file that use the .dwt file as the main template which could result in 20+ pages being uploaded
i figured i can automate this by using the database by flagging records if they are active and using a mysql query to get only those which are active, this way a blackened app can add to the database and deactivate record thus eliminating having to upload files every so soften.
to do this, i had planned on storing the information in the database and building the above array based off the results, researching how to use mysql queries in javascript lead me to code like this
$.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
now i understand that i need to make a .php file which runs my query and that my formatting of the query results into the array would be one in the .done part but what i don't understand is what i'm supposed to do in the .php file to output the query results how in the .done part i'm supposed to reference the output
bellow is the code i use to echo my query results to the page to ensure i am getting results
$resultIndex = 0
while($row = $results->fetch_array(MYSQLI_ASSOC))
{
echo '<'.strval($resultIndex).'><br>';
echo 'id = 'strval($row['id']).'<br>';
echo 'name = 'strval($row['name']).'<br>';
echo 'desc = 'strval($row['desc']).'<br>';
echo 'active = 'strval($row['active']).'<br>';
echo '-----------------------<br>';
$resultIndex += 1;
}
i am wondering 2 things
do i just echo or print_r what i want returned from my .php file
how to i access what my .php file returns in .done
I recommend using http://www.php.net/json_encode to output into Json. Yes, just echo the output. On success, a callback is called passed with the data from server.
$.post (url, function (data){
//do some stuff with data from server
});
See http://api.jquery.com/jQuery.post/
Your $.ajax function just points to a page and reads the data on that page. If you want that page to use MySQL, you will need to use php to set up the MySQL query and print the data. The layers of a web app are complicated, but I'll try to break it down for you.
A traditional php/mysql setup works like this:
Javascript:
Client side, only deals with content already available on the page. Often edits html based on user interaction.
HTML
Client side, defines the content on a page
PHP
Server side, runs on the server and construct the html
MYSQL
Server side, used to communicate between the php and the database
Database
Server side, used to permanently store data
Ajax is a way for the Javascript layer to call some php in the background. That php can use MySQL to access data in the database and print it out in a format that the javascript can parse and use. Typically the javascript will then edit the HTML.

Categories