Adding a database to jquery mobile site - php

I'm pretty new to using jquery and jquery mobile, but I was wondering if there was a simple way (or tutorial preferably) to tie a database (remote and local) to a jquery mobile site (preferably not using php).

You can use HTML5 localStorage via JavaScript, here is an explanation and some links to tutorials: http://www.html5rocks.com/en/features/storage
...there are now several technologies allowing the app to save data on
the client device...
If you want to interact with your server then you're going to need to use a server-side scripting language. It's fairly easy to use AJAX to communicate with your server:
JS--
//run the following code whenever a new pseudo-page is created
$(document).delegate('[data-role="page"]', 'pagecreate', function () {
//cache this page for later use (inside the AJAX function)
var $this = $(this);
//make an AJAX call to your PHP script
$.getJSON('path_to/server/script.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');
});
});
PHP--
<?php
//include your database connection code
include_once('database-connection.php');
//query your MySQL server for whatever information you want
$query = mysql_query("SELCT * FROM fake_table WHERE fake_col='fake value'", $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));
}
?>
You can also send data to your PHP script and have it added to a database.
Here are some documentation pages for functions used above:
jQuery .getJSON(): http://api.jquery.com/jquery.getjson
PHP json_encode(): http://www.php.net/json_encode

use http://westcoastlogic.com/lawnchair/ It offers many ways of storage and you can actually put all the adapters (options of how to store) in order so that it will pick up the first one which is available on the browser.
Also it using JSON format no matter whether u want to use localstorage or sqlite, so u'll only have to deal with JSON data.

If you want a database there is widespread support for SQLLite inside the mobile browser in the form of Web SQL Databases, which is currently supported in most android and iPhone devices.
To see a working example check the following link:
http://desalasworks.com/html5-databases-on-iphone/
Note that the SQL language available in SQLLite is more limited than (what I assume is) your MySQL database. You can create/drop tables, select, insert and update, but some of the more advanced operations will be missing.

Related

Update MY SQL DB Table from jQuery

Based on the user input's, i calculate some values on my submit action of my form. I have to persist these values in my backend DB. I use PHP for my server side scripting. Please let me know the best practice for doing this. It is a single page application and i use .load("Report.html"); to show the summary page.
Just thinking aloud, can i fetch the row(to be updated) from DB, json_encode, update the json object in jQuery, decode it, then update in DB?
Please help...
My submit button code...
$('form').on('submit', function(event)
{
event.preventDefault();
//CALCULATE SCORE
var noOfCorrectAnswers = 0;
var noOfQuestionsViewed = 0;
$.each(questionsArray, function(i, item)
{
if(item.correctOption == item.selectedAnswer)
{
noOfCorrectAnswers++;
}
if(item.isQuestionViewed == 'YES')
{
noOfQuestionsViewed++;
}
});
alert(noOfQuestionsViewed);
$('#sampleDiv').load("UserReport.html");
});
Run some AJAX passing all of the information you need (which may even be none depending on your use case) from the client-side to your server-side PHP. Your PHP script can fetch things from the database if necessary, make any calculations and/or manipulations and then store the information back in the DB.
If you need to return information to your client-side after updating the database then try returning a JSON object (by just printing the code out in the proper format) from your PHP script before exiting with whatever your JS needs.
Do note that this should be all done asynchronously, so you need to setup your AJAX callback function to handle any information that's returned from your PHP script. If you want to do it synchronously, go for it - but you asked for best practices :P
Looks like you're using jQuery - here's the documentation on AJAX
Raunak Kathuria's answer provides some same code
On form submit make ajax call to set database in the db and access the json
$('form').on('submit', function(event)
{ ...
alert(noOfQuestionsViewed);
$.ajax({
url: "yourphp.php", // php to set the data
type: 'POST',
data: 'yourparams', // all the input selected by users
dataType: json
success: function(json){
//here inside json variable you've the json returned by your PHP
// access json you can loop or just access the property json['sample']
$('#sampleDiv').load("UserReport.html", function () {
// its callback function after html is loaded
$('#someid').html(json['sample'));
});
}
})
You can also use the done callback of ajax
PHP
yourphp.php
Set the values here in db running the desired query and return values using
<?php
// your db ooperations will come here
// fetch the db record
// return the db records in json
$responseVar = array(
'message'=>$message,
'calculatedValue'=>$calculated
);
echo (json_encode($responseVar));
?>

Using AJAX/PHP/JS to report multiple status messages during a long process

I understand that using PHP it isn't possible to send messages to the DOM using AJAX as the entire script must execute before the response becomes available. As such, it appears that I have two options:
Split the long process into several smaller ones and report back after each
Write status updates to a file and then have the system read the file as the process executes.
Are there any big advantages or disadvantages to either method?
I haven't understood what methods are you questioning, but here is what you could do (using jQuery and PHP):
In javascript, use window.setTimeout(), to call function that uses ajax callback to check url.
URL is for php script, that checks if new message is present or not.
PHP script checks for new message either in flat tile or in db, not sure what you will use.
Script then prints message, either in straight html markup, or simple text, or in JSON or XML format.
On success, ajax call, outputs response to some selector on page, and calls again window.setTimeout().
this is part of html markup:
<div id="systemmessage">here goes new message</div>
this is part of javascript:
$(document).ready(function(){
window.setTimeout('checkForMessages()',5000); //sets for 5 seconds.
});
function checkForMessages(){
$.ajax(function(){
url: "checkformessages.php",
success: function(data){
if(data!=''){
$('#systemmessage').html(data); //place response in systemmessage
}
window.setTimeout('checkForMessages()',5000); //we set timeout again
}
});
}
this is part of php script called i.e. "checkformessages.php":
$message = file_get_contents('messages.txt'); //check from file where you output new message
//or
$message='';
//use db table, with fields id (int autoincrement, primary), message(text), user_id (integer), created(integer, strtotime - timestamp)
$sql = 'SELECT * FROM system_messages WHERE user_id=somenumber AND created>(current time - 5 seconds)'; //this is more pseudo code, than correct syntax
$result = mysql_query($sql);
if(mysql_num_rows($result)>0){
while($row = mysql_fetch_object($result)){
$message.= $row->message.' <br/>';
}
}
if($message && $message!=''){
echo $messages;
}

I seem to be unable to get AJAX/JS to reload a PHP script and update various page elements

So here is the situation. I'm building a page to host a radio stream hosted on an Icecast server. I got the player working great and cobbled together a PHP script to extract and parse out various data points from the server. Information such as current track, number of listeners, etc.
Here's the problem. It loads fine when the page is first opened, but I can't figure out a way to get these variables to be updated every 5-10 seconds or so and update the page with the new information WITHOUT reloading the page completely (it is a radio station after all, and having to re-buffer the station ever 10 seconds just isn't feasible.
Here's what I have so far, after various attempts have been removed from the code. Any ideas? I've seen it done for one or two variables, but I have almost a Dozen here...
<div id="current_song"></div>
<script language="javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script language="javascript">
{
$.ajax({
type: 'POST',
url: 'script.php',
data: 'getLatestInfo',
dataType: 'json',
cache: false,
success : function(dp){
$.getJSON('script.php', function(dp) {
//'data' will be the json that is returned from the php file
$.("#current_song").html("dp[9]");
});
getlatest();
};
});
}
</script>
and here is the PHP parser
<?php
Function getLatestInfo() {
$SERVER = 'http://chillstep.info:1984';
$STATS_FILE = '/status.xsl?mount=/test.mp3';
$LASTFM_API= '27c480add2ca34385099693a96586bd2';
//create a new curl resource
$ch = curl_init();
//set url
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);
//return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//$output = our stauts.xsl file
$output = curl_exec($ch);
//close curl resource to free up system resources
curl_close($ch);
//loop through $ouput and sort into our different arrays
$dp = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($dp,$to_push);
}
}
$x = explode(" - ",$dp[9]);
echo json_encode($dp);
}
?>
I know it doesn't look pretty yet, but that's what CSS is for right?
Any ideas? Essentially I need the PHP script to rerun, update the variables, and rebuild the text output without touching the audio tag.
Javascript is code that executes client-side (on the website visitors machine) and PHP executes serverside. The way to insert content into a page without reloading the entire page is to use Javascript to inject code into the HTML. Now, for example, say that you have a PHP file on your server, called getLatest.php with a function called getLatestVariables() that finds out the latest values for all your variables and returns an array containing them. What you can do is use javascript to call getLatestVariables() from getLatest.php, and when the function returns the array, it will return it to the javascript. Once the array of variables has been returned to the javascript you can then insert the variabes into HTML divs without having to refresh the entire page.
to call the php function I suggest using jquery to perform an ajax call
also to insert the data returned from the php, jquery is your best bet too.
You need client side JavaScript for this. Get your hands on basic ajax books.
You can request the script for updated data every 5 seconds and update it on the page, this is complicated and needs some knowledge of JavaScript.
The script will have to be new too, or this one edited to trace type of request and return data accordingly.
var url="http://script-address"
var req = new XMLHttpRequest(); // Begin a new request
req.open("GET", url); // An HTTP GET request for the url
req.send(null);
This is how you can check the response
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
//we got a complete valid HTTP response
var response = req.responseText;
//code to handle response
}
php is a serverside language, so re-running the php inside your page will always result in the entire page refreshing, however if you use a javascript ajax call (I suggest using jquery) to a different php file, that php file can be executed serverside without affecting your page. you can then return the newly found variables from this php file to the javascript, and insert them in the callback of the ajax call.
see the answer to this question
If you need any more detail let me know...
$.getJSON('phpFileThatReturnsJSON.php', function(data) {
//'data' will be the json that is returned from the php file
$.("#idOfDivToInsertData").html("an item from the json array ie data['song']");
});
look at JQuery docs for ajax calls, if you've got this far you should be able to nail it out pretty quickly.
Also dont forget to include the jquery library in your html header...
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>

Using javascript to get php/mysql values

i am thinking of building an android app in appcellerators titanium application, and i have a question, the website which the app is for is built using php/mysql, and what i am wondering is, as titanium works using javascript, html and css only, is there a way i can pull the data dynamically from my database using javascript?
if this has already been posted I'm sorry i searched and couldnt find it :S
With PHP, take your database response array and encode it like this:
<?php
json_encode($db_array);
?>
More information:
http://php.net/manual/en/function.json-encode.php
Note that you'll need PHP 5.2 or above in order to have the built in JSON functions for PHP.
In Titanium, you want to open a XHR (or network handler) to grab the data:
var xhr = Ti.Network.createHTTPClient();
var.onload = function()
{
try
{
data = JSON.parse(this.responseText);
}
catch (excp)
{
alert('JSON parse failed');
}
// you should handle your network async, meaning you should handle any renders or any post elements here. if you make it sync, you'll cause all other handlers and functions to work improperly (like click events, etc).
}
xhr.open("GET", "your url here");
xhr.send();
You can access the the data array by simply calling data[0].some_col;
Try reading tutorial about using SQLite databases in Titanium applications
I'm sorry it's for iPhone, but in basics the principle is the same
http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite/
http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite-part-2/
http://mobile.tutsplus.com/tutorials/appcelerator/titanium-mobile-database-driven-tables-with-sqlite-%E2%80%93-part-3/
using is like this:
var db = Ti.Database.install('../products.sqlite','products');
var rows = db.execute('SELECT DISTINCT category FROM products');
Documentation:
http://developer.appcelerator.com/apidoc/mobile/1.3/Titanium.Database-module
The best way would be to use JSON using json_encode if you were accessing the database from the website. If you were trying to use a local database then use sqlite.
You need to build an webservice on your website, and pull the data in with Titanium.Network.HTTPClient
You can see it here: http://developer.appcelerator.com/apidoc/mobile/latest/Titanium.Network.HTTPClient-object
An example would be:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
var data = this.responseText; //response is here
// do your thing within this scope, or call a function/event from here
}
var url = 'http://www.google.nl';
xhr.open("GET", url); // or "POST"
xhr.send();
Note that the data variable is not accessable outside the scope, even if it is a global. Call your function from within the scope
In the app you could either use SQLite, or don't store the data. Whatever suits your application best

JavaScript passing variables between functions and processing them

I'm working on a JavaScript based page that returns the cost of delivery, depending on what the user selects(Region, service(pre 12, etc) and weight). I have muddled my way through as I just don't know JS.
My questions are:
Can I pass the variable between functions - as detailed in the script below?
Once the above has been achieved, I need to process the variables to display the result, now I could do a massive ifelse, don't really want to because there will be some 30 odd possibilities. All required info is in a SQL DB so this would be my preferred choice but I'm not sure how to do this with JS, the whole Browser side, Server side issue. Would I need to pass the variables(as above) to PHP (once all 3 are set) to grab the data from the SQL DB? If so, I'm not sure how to do this.
If I do use PHP then the page will have to be reloaded, is it possible to get this to be seamless to the user, i.e., all their selections are still displayed?
function flag(nation, area) {
this.nation = nation;
var el = document.getElementById("desc");
el.innerHTML = 'The region you have selected is <b>' + area + '</b>';
document.getElementById("flag").innerHTML = '<img src="images/flags/' + nation + '.jpg">';
}
function output(service) {
this.service = service;
var el = document.getElementById("service-desc");
el.innerHTML = 'You have selected a <b>' + service + '</b> service.';
document.getElementById("clock").innerHTML = '<img src="images/clock-' + service + '.png">';
}
function result() {
//get varibles(nation & serive) from functions above ~ not sure how to do this!
//process varibles
if (nation == "UK" && service == "Standard next day") {
document.getElementById("result").innerHTML = '£9.99';
} else if (nation == "UK" && service == "Before 12pm") {
document.getElementById("result").innerHTML = '£14.99';
}
// etc,etc,etc....
else {
document.getElementById("a1").innerHTML = "";
}
}
There are basically three alternatives:
Have the PHP script put all the data on the page as JavaScript arrays and handle everything in JavaScript. If the total amount of data is not too much, this is an OK solution
Reload the entire page when the user makes a selection and handle everything in PHP (including keeping existing selections) - this is the only way to make it work without JavaScript, but has only disadvantages otherwise.
Use AJAX when the user makes a selection, i.e. JavaScript calls the server in the background and a special PHP script returns only the relevant data (typically using JSON format) which the JavaScript then uses to update the page. This is how it's typically done nowadays.
In javascript if you declare a variable outside a function you can use it from any function, this is a global variable. E.g.
var x, y;
function flag(nation,area)
{
x = nation;
y = area;
}
function output(service)
{}
function result() {
//In here you can do whatever you want with x and y
}
You would be best creating a PHP script that gets your data from the database and returns it to your javascript. The best way to do this would be an AJAX call, this would allow you to seemlessly get the data from the database that you want and only update specific parts of the page rather than the whole page.
I would recommend having a look at jQuery as it has some very easy to use AJAX methods. It is just a library that wraps javascript and has lots of easy to use functionality, good introduction vids here
Here is a tutorial on how to use jQuery to call a PHP script which gets data from a database.
You want AJAX - write a server-side data feed in PHP and browser-side mini-application in JS that talks to the server feed and updates the webpage accordingly. This is achieved using Javascript's XMLHttpRequest object. I highly recommend you learn to use it and then rely on a JS library that wraps around it and provides higher level services (like jQuery)

Categories