Using javascript to get php/mysql values - php

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

Related

How i can to save a json object from javascript to a php session variable?

Hi i need some examples about how i can to store an json object to php session variable.The json object as the follow:
var jsonObject={ "menu":
{
"intro":{
"intosub":"sub_1"
}
"vis":{
"visub":"sub_2"
}
}
regards
Based on what you gave us, your json object is wrong. It should be:
var jsonObject={
"menu":
{
"intro":{
"intosub":"sub_1"
},
"vis":{
"visub":"sub_2"
}
}
};
EDIT
var jsonObject={ "menu": { "intro":{ "intosub":"sub_1" }, "vis":{ "visub":"sub_2" } }
var string=JSON.stringify(jsonobject);
var phpcode="<?php $_SESSION["jsonObject"]= " phpcode+=string+"?>";
Javascript is client side when PHP is server side. That means that when you create your object with javascript, you can't interact with the server anymore until you use Ajax that allows the transmission of client side data to your server then send them again to the client if necessary.
What you did with your var phpcode="<?php $_SESSION["jsonObject"]= " phpcode+=string+"?>" is that you asked your server BEFORE it sends to the client to fill your "phpcode" JS variable with... I don't really understand what you tried here with setting a session variable but if you tried to set the PHP session variable with your json object like that, it is the same as if you set the PHP session variable directly without the use of JS.
However, I guess you want to fill your session variable with dynamic data you created with the use of JS or your question makes no sense.
What you need to understand is that when you write <?php stuff; ?> in javascript, when it is send to the client, it is as if you wrote stuff directly in your javascript. It's done and it won't change and certainly not communicate with your server.
Ex: var math=<?php echo 10+1;?>; is the same as if you wrote var math=11; directly in your JS. Of course, you use PHP to insert PHP stuff into your JS but once it's done and send to the client, it is set in stone and you use Ajax to change that.
What you need to do is to take your json object and use Ajax to send it to PHP.
I saw you are using Jquery so here is the Jquery doc about Ajax > https://api.jquery.com/jQuery.ajax/
That will look like:
$.ajax({
type:'post',
url:'path/to/a/PHP/file',
data:{jsonobject:yourstringifyjsonobject}
});
You will retrieve that "jsonobject" in your "path/to/a/PHP/file" with $_POST['jsonobject'] and here you go:
session_start();//to not forget if you want session variables to work
$_SESSION['whatever']=json_decode($_POST['jsonobject'])
your session variable is set with your json object.

Sending php variables to Javascript variables

Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");

Visit a URL in PHP or javascript in background

I write my scripts in PHP, and there are HTML and javascripts inside. What I want is when I click a button(in HTML), it calls a javascript function, the function should visit a url like "http://localhost/1/2" And the page stays as before. Is it feasible?
I just want it work, no matter in js or php. Thanks.
Since the page is on the same domain, you may use an Ajax request:
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.send(null);
Note that this does not do any error-checking, however. If you need that, there are a multitude of available tutorials easily found with a search.
And since you ask, for pages not on the same domain, using an <iframe> is sometimes possible:
var frame = document.createElement("iframe");
frame.src = url;
frame.style.position = "relative";
frame.style.left = "-9999px";
document.body.appendChild(frame);
This is commonly known as AJAX (being able to send a request to the server and receive a response back without navigating away from the page).
AJAX is supported in ALL modern browsers, but sometimes there are inconsistencies, so it is best to use a javascript framework such as JQuery, YUI or another framework.
I tend to use YUI, so here's a quick example on how to send an AJAX request using YUI. This uses the IO Utility:
// Create a YUI instance using io module.
YUI().use("io", function(Y) {
var uri = "http://localhost/1/2";
// Define a function to handle the response data.
function complete() {
Y.log('success!');
};
// Subscribe to event "io:complete"
Y.on('io:complete', complete);
// Make an HTTP request to 'get.php'.
// NOTE: This transaction does not use a configuration object.
var request = Y.io(uri);
});

PHP/Flash integration inconsistencies

I am having some consistency problems with my flash application, when I echo out variables for flash to get, it doesn't always pick up what PHP is sending, it seems to vary from PC to PC.
I am getting info from a database, and I need to pass it to flash, say for instance I need to send through 5 variables $uid,$name,$points,$from,$page , how could I go about sending these from PHP to flash using AMFPHP?
I was told that AMFPHP would be the best tool to use for such situations, but I have NO knowledge of how it works and the sample code on the site is not making complete sense to me.
Thanx in advance!
You cannot push it from PHP to Flash - the communication has to be initiated by the Flash end. And you don't need AMFPHP for this; just use a URLLoader.
var ldr:URLLoader = new URLLoader();
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.load(new URLRequest("page.php"));
function onLoad(e:Event):void
{
var loadedText:String = URLLoader(e.target).data;
/**
* Following will throw error if the text
* is not in the format `a=something&b=something%20else`
* */
var data:URLVariables = new URLVariables(loadedText);
for(var t:Object in data)
trace(t + " : " + data[t]);
}
inside the page.php, just do a simple echo:
//don't forget to urlencode your variables.
echo "uid=$uid&name=$name&points=$points";
It seems a hassle to get involved with AMFPHP just to send a couple of variables to a flash file. I suggest you try:
Flashvars (though it's kind of limited to short variables)
LoadVariables
XML (returning the values you need as XML from PHP)
All of the above have worked consistently for me.

[PHP/JavaScript]: Call PHP file through JavaScript code with argument

I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.
<script>
function SetRowInCookie(NewCookieValue)
{
try
{
alert(NewCookieValue);
document.cookie = 'row_id=' + NewCookieValue;
loadCookies();
}
catch(err)
{
alert(err.description);
}
}
function loadCookies() {
var cr = []; if (document.cookie != '') {
var ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
var cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
alert(cr['row_id']);
}
</script>
I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.
Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.
Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.
jQuery ajax example;
$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:
$.post(url, params, callback_function);
Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.
AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.

Categories