Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Web and WebWorks Development

Reply
Developer
Justam
Posts: 58
Registered: ‎02-14-2011
My Device: Bold 9700
My Carrier: Rogers

POST/READ data to PHP/MYSQL on webserver

This is my first webworks application and I am a little confused on how to go about this. As such I am going to try and provide as much detail as I can to paint a clear picture of what I am trying to accomplish in the hopes of recieving a response which will provide some insight into this process.

 

foreword:

 

Initial screen presented on first run of the app:

 

-HTML form with 1 text field for login

 

I would like the login data to be saved locally once it is verified by posting to my webserver and recieving some sort of responsee(Login OK/Failed). Once login is verified, I would like an image to be downloaded to the device and stored. once login/image is stored, load second screen as described below.

 

 

screen presented after first run of the app/login data is stored/image has been downloaded

 

-Show image, using a html form have a login button with the UID for login in a hidden field.

 

 

When login button is pressed on screen described directly above:

 

-open blackberry browser to load account screen php file on my webserver. eg:www.server.com?account=UID

 

 

What I already know


 -the php end is fully functional in a desktop web browser(Login, loading/saving data to mysql)

 

-I Know how to store strings to local db on blackberry devices

 

 What I dont know:


-I do not know how to download an image within the webworks app and store it locally. writing the path to thelocal db i assume is the same as storing strings. I am thinking of using a GET URL like http://www.server.com?image=UID to lookup the image url to be downloaded as these images are behind my www root and will be copied to a temp directory in the www root to be downloaded.

 

-I do not know how to post data to my webserver php files and recieve a respone from webserver within the webworks app. I have tried using html forms and used method="post" and action="http://www.server.com/login.php", GET would also be fine. What I need to know is how to pass the login UID to my webserver and recieve a OK/Failed response.

 

I know that is alot above, however I am trying to provide my specific needs to ensure a complete overview of what I need help with. I do know PHP, Html, Javascript, CSS...I have looked at the Blackberry Webworks apis and didnt find my answer. I did read something about JSON to post/recieve data from webserver but I cant find examples/usage on how to accomplish this with webworks.

 

Insight would be greatly appreciated. 

 

Please use plain text.
BlackBerry Development Advisor
oros
Posts: 1,523
Registered: ‎04-12-2010
My Device: BlackBerry Z10
My Carrier: Bell

Re: POST/READ data to PHP/MYSQL on webserver

Hello there,

 

I will do my best to answer your questions; if there's anything that isn't clear, please just let me know.

 

I put together this sample which uses an XMLHttpRequest object to communicate with a PHP script on a server. I implemented a GET approach to send data to the server and receive a response. First, the HTML:

 

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <div><input id="payload" type="text"></div>
        <div><button onclick="fire();">Fire!</button></div>
        <div id="hash"></div>

        <script type="text/javascript">
            function fire() {
                var payload = document.querySelector("#payload").value;

                var xmlhttp = new XMLHttpRequest();

                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        document.querySelector("#hash").innerHTML = "Hash: " + xmlhttp.responseText;
                    }
                };
                xmlhttp.open("GET", "http://www.MYSERVER.com/php/getHash.php?payload=" + payload, true);
                xmlhttp.send();
            }
        </script>
    </body>
</html>

First, I set up three HTML elements:

  1. A text <input> that the user can type into.
  2. A <button> to trigger our GET.
  3. A <div> to display our response in.

Next, we create the <script> which defines our fire function; responsible for sending and receiving the GET request.

 

First, we retrieve the value from the text <input>:

var payload = document.querySelector("#payload").value;

 

The next section creates an XMLHttpRequest object and registers an event listener to monitor for success conditions (readyState === 4 and status === 200).

 

On success, we fill the inner HTML of our hash <div> to the response that was provided by the PHP script on the server.

 

Now that we have that behaviour defined, I set the connection settings. Specifically we are sending a GET request to the noted URL, and are appending the payload. Note that payload is arbitrarily named, it is just a variable name that I felt like using. It could just as easily have been pancakes.

 

And lastly, we send the request. Which, again, will be handled asynchronously by our defined onreadystatechange listener.

 

As for the PHP, it's pretty basic. All I'm doing in this sample is retrieving the GET variable called payload (again, could have been called pancakes) and passing it to the hash function (built into PHP) to generate a value that I then return back to the client.

 

<?php
    echo hash("md5", $_GET["payload"]);
?>

Of course, this could be made more complicated to do more things with the request before returning a more appriopriate response.

 

Anything I echo gets appended to the responseText.

 

With respect to receiving an image, the following thread has some good information:

http://stackoverflow.com/questions/3721764/handling-images-from-xmlhttprequest-with-html-and-javascr...

 

And finally, in order to save an image file directly to the filesystem, you will need to leverage our native (i.e. WebWorks) APIs as there is no generic JavaScript to work with the file systems of mobile devices (frameworks like Phonegap not included.)

https://bdsc.webapps.blackberry.com/html5/apis/blackberry.io.file.html#.saveFile

 

In order to do this, you may need to perform some magic; luckily our man Tim Windsor has explained the magic in detail and I would recommend this thread for reading:

http://supportforums.blackberry.com/t5/Web-and-WebWorks-Development/stringToblog-save-image-problem/...


Erik Oros | @WaterlooErik | eoros@blackberry.com | Developer Issue Tracker

If a reply has answered your question, please click Accept as Solution to help other visitors in the future.
Please use plain text.
Developer
Justam
Posts: 58
Registered: ‎02-14-2011
My Device: Bold 9700
My Carrier: Rogers

Re: POST/READ data to PHP/MYSQL on webserver

Thank you for your time and response. I believe this is just what I need. I assume I can take the server response and pass that through a javascript function to save data to device dB if response is success and if failure notify user to try again....

 

I truly appreciate the support and the information which you have provided, again thank you. Now onto the reading material you provided!

Please use plain text.
BlackBerry Development Advisor
oros
Posts: 1,523
Registered: ‎04-12-2010
My Device: BlackBerry Z10
My Carrier: Bell

Re: POST/READ data to PHP/MYSQL on webserver

You're right, the response would be passed to the JavaScript APIs in order to be saved to the file system, or local database if you prefer.

 

If you're saving to the file system, you would need to use the WebWorks (still JavaScript) APIs noted to get access to that system on a BlackBerry device. There are a few hoops you would need to jump through though due to encoding requirements and some finicky things with those APIs.

 

If you are saving to a database, there may still be some encoding work that needs to be done; but that would depend more on your specific implementation.

 

If the response happens to be a failure message, you absolutely could notify the user to try again. Seems like you got it :smileyhappy: And if any questions come up, just let us know here.


Erik Oros | @WaterlooErik | eoros@blackberry.com | Developer Issue Tracker

If a reply has answered your question, please click Accept as Solution to help other visitors in the future.
Please use plain text.
Developer
Justam
Posts: 58
Registered: ‎02-14-2011
My Device: Bold 9700
My Carrier: Rogers

Re: POST/READ data to PHP/MYSQL on webserver

[ Edited ]

I had a read through the suggested material. Now I am already storing the base64 image data in the MYSQL db. It seems as though I can use the code by timwindsor to take my base64 data and save it to an image file. Correct?

 

It also seems using the method you supplied I will need to make several GET xmlhttp requests in order to obtain multiple peices of info. SO for example using 2 input boxes with id of "uid" and "serial" I could do:

 

http://www.myserver.com/get.php?uid=UID&key=serial&type=correlate

-preform the db lookup confirm the uid/serial correlate and echo uid from php

-store UID and serial to local filesystem using:


Is the below persistent or only when the app is running?


localStorage.setItem("uid", uid);
localStorage.setItem("serial", serial)


http://www.myserver.com/get.php?uid=UID&key=serial&type=base64, 

-preform my db lookup and echo the base64 from php

 

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
	if(request.readyState == 4) {
		if(request.status == 200){
			var response = request.response;
			var blob_data =  blackberry.utils.stringToBlob(response, "binary");
			var filename = blackberry.io.dir.appDirs.shared.documents.path + "/uid.png";
			if (blackberry.io.file.exists(filename)) {
				blackberry.io.file.deleteFile(filename);
			}
			blackberry.io.file.saveFile(filename, blob_data);
		}
	}
}

 

Please use plain text.
BlackBerry Development Advisor
oros
Posts: 1,523
Registered: ‎04-12-2010
My Device: BlackBerry Z10
My Carrier: Bell

Re: POST/READ data to PHP/MYSQL on webserver

Hi there,

 

Now I am already storing the base64 image data in the MYSQL db. It seems as though I can use the code by timwindsor to take my base64 data and save it to an image file. Correct?

Correct. Assuming the formats are matching up, which it sounds like they are, you should be able to save local copies of those images on the filesystem.

 

It also seems using the method you supplied I will need to make several GET xmlhttp requests in order to obtain multiple peices of info.

If I'm understanding the question correctly, this is where something like JSON comes in very handy. JSON is just a "container" for your request/response that can provide multiple name/value pairs, even an array of them, to minimize the number of requests needed to receive multiple data sets.

 

JavaScript and PHP both have built-in JSON capabilities:

http://www.json.org/js.html

http://php.net/manual/en/book.json.php

 

This way, in your GET you could pass 1 value; your JSON string of name/value pairs. And you would return another JSON string of name/value pairs through your request. I'd recommend a Google lookup for json samples or something similar to get an idea of how it can be used if you haven't used it before.

 

Is the below persistent or only when the app is running?

Local storage items should persist between application launches as far as I am aware. The main thing here is that local storage lets you store name/value strings, whereas the filesystem APIs would let you store more complex data (i.e. full images.)

 

 

One final note. You mentioned that you're already storing your image data in base64 format, so it seems like you would be off to a good start. I do want to warn though that between the HTTP transfer (i.e request/response), JSON encoding/decoding, and filesystem requirements, there may still be some encoding issues that you run into. It's difficult to say off the top of my head, but if you do run into issues, it may be necessary to perform some manual encoding on the fly. Just wanted to point that out in case it does arise.


Erik Oros | @WaterlooErik | eoros@blackberry.com | Developer Issue Tracker

If a reply has answered your question, please click Accept as Solution to help other visitors in the future.
Please use plain text.
Developer
Justam
Posts: 58
Registered: ‎02-14-2011
My Device: Bold 9700
My Carrier: Rogers

Re: POST/READ data to PHP/MYSQL on webserver

Hello,

 

I will look into JSON. I haven't used it before but if it is the better option then it is the one I will use. Also, I am having some difficulty with storing data using the localStorage API.

 

Here is my code:

 

 

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript">
		//Check for stored data, load if available
		function load()
		{
			//Assign Variable data
			var loaduid=localStorage.getItem("uid");
			var loadserial=localStorage.getItem("serial");
			//Other Variants...
			//var loaduid=localStorage['uid'];
			//var loadserial=localStorage['serial'];
			//Check for NULL values, print results if <> NULL
			if (loaduid <> NULL && loadserial <> NULL)
			{
				document.querySelector("#hash").innerHTML = "Serial: " + loadserial + " - UID: " + loaduid;
			}
		}
		</script>
	<title>My App</title>
	</head>
	<body onload="load();" id="main_body" >
		<div>Account: <input id="serial" type="text"></div>
		<div>Record: <input id="uid" type="text"></div>
        <div><button onclick="confirmData();">Register</button></div>
		<div><button onclick="load();">Load Data</button></div>
        <div id="hash"></div>

        <script type="text/javascript">
			//Send data to server for correlation check
            function confirmData() {
				//Assign variables
                var serial = document.querySelector("#serial").value;
				var uid = document.querySelector("#uid").value;
                //Create new xmlhttprequest
				var xmlhttp = new XMLHttpRequest();
				
				//Recieve response from server function
                xmlhttp.onreadystatechange = function () {
                    //Verify Response from Server was OK
					if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        //document.querySelector("#hash").innerHTML = "Status: " + xmlhttp.responseText;
						var payload = xmlhttp.responseText;
						
						if (payload == "validated")
						{
							//Print Results
							document.querySelector("#hash").innerHTML = "Status: " + payload;
							//Store Data
							localStorage.setItem("uid", uid);
							localStorage.setItem("serial", serial);
							//Other Variants of localStorage I have tried:
							//localStorage['uid']=uid;
							//localStorage['serial']=serial;
							//localStorage.uid = uid;
							//localStorage.serial = serial;
						}else{
							//Validation Failed Show Results for Debugging
							document.querySelector("#hash").innerHTML = "Unvalidated: " + xmlhttp.responseText;
							//Prompt user to try again
							alert("The Serial & Record numbers do not match. Please try again.");
						}
                    }
                };
                xmlhttp.open("GET", "http://www.berrygooddesigns.com/script.php?uid=" + uid + "&serial=" + serial + "&type=correlate", true);
                xmlhttp.send();
            }
        </script>
	</body>
</html>

 When I click the Load Data button it says undefined for each variable....

 

Please use plain text.
Developer
Justam
Posts: 58
Registered: ‎02-14-2011
My Device: Bold 9700
My Carrier: Rogers

Re: POST/READ data to PHP/MYSQL on webserver

[ Edited ]

I got it working...not sure exactly what the issue was....I have a feeling it was a typo. I originally had a function to validate the response but to make things simple I moved the code from that function into the xmlhttp.onreadystatechange = function () and I ended up retyping a couple things....so most likely typo. Sorry about that.

 

Ok I'm on to try and get this base64 thing going and looking into json.

Please use plain text.
BlackBerry Development Advisor
oros
Posts: 1,523
Registered: ‎04-12-2010
My Device: BlackBerry Z10
My Carrier: Bell

Re: POST/READ data to PHP/MYSQL on webserver

Awesome, glad to hear it!

 

Let us know if anything else comes up.


Erik Oros | @WaterlooErik | eoros@blackberry.com | Developer Issue Tracker

If a reply has answered your question, please click Accept as Solution to help other visitors in the future.
Please use plain text.
Developer
Justam
Posts: 58
Registered: ‎02-14-2011
My Device: Bold 9700
My Carrier: Rogers

Re: POST/READ data to PHP/MYSQL on webserver

Hello, 

 

Application is working great! One question though:

 

Is there a way or a javascript class maybe that emulates a native application feel? Ie: remove the cursor and have the focus go through items like it would on a native application?

 

Thanks

Justam

 

 

Please use plain text.