I'm following the tuitions on XMLHttpRequest 2 from :
https://developer.mozilla.org/en/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data
and
http://www.html5rocks.com/en/tutorials/file/xhr2/#toc-send-arraybuffer
They're great tutorials for the client side, and here is a working extract from my script:
var imagebuffer = new ArrayBuffer(size); // create the readonly memory buffer
var imagedata= new Uint8Array(imagebuffer); // create a view to manipulate data
// do some cool stuff with imagedata
var exchange=new XMLHttpRequest();
exchange.open("POST",url,true);
exchange.send(arraybuffer);
So far so good, and I can see from the both client and server control panels that plenty of data is being transferred.
Here's my problem: how do I access the ArrayBuffer with PHP at the server?
I'm used to the $_POST superglobal wanting parameters passing from a HTML form so it can be accessed as an array but I can't find any reference for how to access this binary array and stick it in my MySQL database.
Okay - I've figured it out. My server side PHP opens with:
$data = file_get_contents('php://input');
$mysql_blob = base64_encode($data);
which is now in a format ready for inserting (for example) into MySQL as a BLOB format.
Works like a charm!
Related
Please bear up with me, I'm new to PHP. I'm using a mixture of PHP and jQuery on the same page. I need to pass variables from jQuery to PHP. All examples I came across describe how to pass variables to a PHP file on the server which I don't want. So far I manged to convert object to JSON using jQuery $.toJSON();
My question is: is it possible to pass jQuery data to php code if both jQuery and PHP reside on the same page?
Here is my code so far:
var myObject = {name: 'Tomas', age: 38};
var encoded = $.toJSON( myObject);
var name = $.evalJSON( encoded ).name;
var version = $.evalJSON(encoded).age;
No it is not possible since PHP is not a client side script but rather a server side script. What that means is that by the time the data is given to the client the PHP script would have most likely already finished running. The following demonstrates the relationship between PHP and JavaScript:
Server -> PHP -> Client (Browser) -> Javascript
Therefore, it is impossible to have javascript communicate to PHP on the same page. What you can do is use Ajax to call a server side file like you said - but I'm afraid that is as much as you can do in terms of PHP and JavaScript Communication
Full code can also be found here: https://gist.github.com/1973726 (partially version on jsfiddle http://jsfiddle.net/VaEAJ/ obviously couldn't have php running with jsfiddle)
I initially wrote some code which took a canvas element and saved it as an image (see working code here: https://gist.github.com/1973283) and afterwards I updated it so it could process multiple canvas elements but the main difference now is that the image data is passed through to my PHP script via jQuery ajax method rather than via a hidden form field.
Problem is the images appear to be blank. They are about 200kb each when generated so they obviously have some content but when you preview the image nothing shows and when I try and open the image in Adobe Fireworks or another photo application I can't open the file.
The image data appears to be coming through to the server fine, but I'm really not sure why now when I write the image using base64_decode it would mean the images that are generated would no longer be viewable? The only thing I can think of is that maybe the posting of data via ajax isn't sending all the data through and so it's generating an image but it's not the full content and so the image is incomplete (hence why a photo application can't open it).
When checking the post data in Firebug it suggests that the limit has been reached? Not sure if that's what the problem is?
The problem was actually with sending data via XHR. I was using jQuery ajax method initially and then I swapped it out for my own ajax abstraction but the problem was still occuring until someone on twitter suggested I use FormData to pass the data to the server-side PHP. Sample is as follows... (full code can be seen here: https://gist.github.com/1973726)
// Can't use standard library AJAX methods (such as…)
// data: "imgdata=" + newCanvas.toDataURL()
// Not sure why it doesn't work as we're only abstracting an API over the top of the native XHR object?
// To make this work we need to use a proper FormData object (no data on browser support)
var formData = new FormData();
formData.append("imgdata", newCanvas.toDataURL());
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveimage.php");
xhr.send(formData);
// Watch for when the state of the document gets updated
xhr.onreadystatechange = function(){
// Wait until the data is fully loaded, and make sure that the request hasn't already timed out
if (xhr.readyState == 4) {
// Check to see if the request was successful
if (checkHTTPSuccess(xhr)) {
// Execute the success callback
onSuccessfulImageProcessing(card, newCanvas, ctx, getHTTPData(xhr));
}
else {
throw new Error("checkHTTPSuccess failed = " + e);
}
xhr.onreadystatechange = null;
xhr = null;
}
};
```
If you are not having Cross Origin SECURITY_ERR's (which your Fiddle suffers from, but as long as your images are on the same server they will be fine), and you are getting some data so you are probably having problems with your PHP. From the PHP user notes, you have to replace the spaces with +'s to decode base64 that has been encoded with Javascript.
$data = str_replace(" ", "+", $_POST['imgdata']);
file_put_contents("generated.png", base64_decode($data));
I have an AS3 project that takes user inputs (basically like a multiple choice test) and saves the these inputs in an array. I need to save the array to a text file so it can be reloaded when the app is reloaded. When the user returns to the application they can pick up where they let off.
I really just need to know what options I have for saving an array inside an swf to an xml file or text file in the same directory. Is this even possible.
Any ideas or concepts would be greatly appreciated.
thanks,
Laurence
First, you need to serialize your object to a string. Then, post that string to a PHP script via a URLLoader instance. Store it as desired (database, text file, etc). When you need to reconstruct the object, load the string from your PHP script. Unserialize it and it's ready to go.
For serialization and deserialization, here are helper functions:
private function serializeObject(o:Object):String
{
var ba:ByteArray = new ByteArray();
ba.writeObject(o);
return ba.toString();
}
private function unserializeObject(s:String):Object
{
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes(s);
ba.position = 0;
return ba.readObject();
}
You could store your variables as "Flash cookies" using the SharedObject class. It's similar to the way PHP or Javascript store cookies locally on the user's compupter. I wrote this Session class a while back:
http://code.google.com/p/daleyjem/source/browse/trunk/com/daleyjem/as3/Session.as
It basically allows you to get, set and check if a set cookie exists.
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
I'm currently following this example for HTML 5 drag and drop. I am hoping to use this to upload the dropped files to a remote FTP server with a php script. However, how do my php script access these dropped files ?
With a regular web form, I can use $_FILES.. But I don't suppose I can use $_FILES for the dropped files..
On the example, the script calls handleFiles function after a drop event
function handleFiles(files) {
var file = files[0];
document.getElementById("droplabel").innerHTML = "Processing " + file.name;
var reader = new FileReader();
// init the reader event handlers
reader.onprogress = handleReaderProgress;
reader.onloadend = handleReaderLoadEnd;
// begin the read operation
reader.readAsDataURL(file);
}
I guessing that I can iterate each element of the array list, and send each element to my php script. As I've mentioned above, how can I send this element from the array list to the php script? JSON ? jQuery POST ?
I am aware that there are various jquery plugins available to achieve this, and I have downloaded a few of them... However I'm just curious to know if I can implement the same thing with this example.
I presume by upload you mean upload it in a ajax operation.
file refer to a File object, which is available for you after the user had drop the file. After that you have two options:
Read the file using FileReader, send the text in xhr as post data (not recommend as it only work with text)
Pass the object to FormData then pass the FormData object to xhr to send the file (Doesn't work with Firefox <= 3.6 though)
Check Mozilla Developer Center document for the usage of these interfaces. I have working projects that use these objects, however there are too much bridging code to be a good walk-through demo. https://github.com/timdream/html5-file-upload
Why not use an open source solution for your problem rather than re-inventing the wheel.
http://plupload.com/
Is pretty much all you will ever need. I use it and it works wonders. Also, it falls back onto html 4 form uploading when a browser cannot handle html5.