0

So i have a page set up that needs to send a blob variable to a php page. The php page then uploads the blob to mysql using pdo. I have the ajax set up so it sends just a text variable and uploads it just fine. However when I try to do a blob it will not work.

Main page

    var blob = new Blob(["i am a blob"]);

   $.ajax({

      type: 'POST',
      url: 'test.php',
      data: {roll: blob},
    });

Php page

$got = $_POST['roll']; //gets the variable

$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
    $query = $pdo->prepare('INSERT INTO books (test,rec) VALUES (?,?)'); 
    $query->bindValue(1, '35');
    $query->bindValue(2, $rollv);
    $query->execute();
SolidCloudinc
  • 329
  • 10
  • 27

2 Answers2

0

JavaScript is not the best language, at the moment, to work with binary data. It is being improved widely, but only on modern browsers (most notably, only IE10+ and mobile support is sometimes partial).

Thus said, with XHR2 (browser support) you can send binary data. Using XHR2 is really easy, and you can read a very nice article here: http://www.html5rocks.com/en/tutorials/file/xhr2/ . If you really need to use jQuery for managing async requests, then you need to use FormData and the tricks explained here: https://stackoverflow.com/a/13333478/192024

PS: be careful with storing blob data into MySQL databases, as sometimes there can be issues, especially with large files!

Community
  • 1
  • 1
ItalyPaleAle
  • 7,185
  • 6
  • 42
  • 69
-2

You could try something like this.

var data;
var blob = new Blob(["i am a blob"]);

var reader  = new FileReader();

reader.onloadend = function () {
    data = reader.result;

    $.ajax({
      type: 'POST',
      url: 'test.php',
      data: {roll: data},
    });
}

reader.readAsDataURL(blob);
cmorrissey
  • 8,493
  • 2
  • 23
  • 27
  • 1
    This would send to the server a Base64-encoded representation of the data, however, not the raw binary data – ItalyPaleAle May 20 '14 at 20:36
  • Can I retrieve the Base64 and convert it? Or would that distort the file? – SolidCloudinc May 21 '14 at 13:36
  • @SolidCloudinc you could and that would not distort the file. BUT remember that this creates a lot of overhead: processing time to convert to and from base64, memory usage etc. Additionally, base64-encoded strings are ~33% bigger, so it also uses more bandwidth. (PS: remember to tag me in comments!) – ItalyPaleAle May 24 '14 at 20:49