Becky
Becky

Reputation: 5595

Send multiple base64 to php

I want to send multiple base64 strings via jquery's $post(). The number of strings are not always the same. How can I do this and fetch it in php?

Is it a good option to have all strings in an array and add them in $post()?

var items = [
    "data:image/png;base64,i.....", 
    "data:image/png;base64,i....", 
    "data:image/png;base64,i...."
] //the number od these strings varies on each post
$.post("../send.php",
   {
     for(i=0;i<21;i++){
        'item'+i: items[i]
     }
   },
)

php:

if($_POST['item1']){
   $item1 = $_POST['item1'];
}

Upvotes: 1

Views: 776

Answers (3)

Tejas
Tejas

Reputation: 711

I would create a regular array of strings, and then iterate to the array of strings and add them as properties of an object using a for loop. Here's an example.

var items = []; // Empty array.
items.push(item1, item2, item3); // Add Base64 strings.

var postdata = {}; // An object for our postdata.

// Iterate through the array and add items as properties to the object.
for (var _i = 0, _j = items.length; _i < _j; _i++) {
  postdata['item_'+_i] = items[_i]; }

// POST the object to the PHP file.
$.post("../send.php", postdata);

Then, in PHP, you get $_POST['item_1'] until $_POST['item_n'] from jQuery. :)

UPDATE

You can process the postdata in PHP like below.

<?php

  foreach($_POST as $k => $v) {
    // Do things for each item POSTED.
    // This will end after the last POSTed item is reached.

    // $k is the 'key', as in what's inside the square brackets of $_POST[]
    // $v is the 'value', as in $_POST[key] = "THIS STUFF";
  }

?>

Hope that was helpful!

Upvotes: 1

Faizan A. Chughtai
Faizan A. Chughtai

Reputation: 31

I would go with the following steps:

1) Create a form with the input fields that contain all these base64 strings. (the form and all its fields can all be hidden in html) 2) In my form all the input text fields can have the same name like in this case

<input type="text" name="text1[]">

2) When I need to add a new string, I shall add an input field in that form by using jQuery.append() 3) in my jquery post i will set the data to

$.post('../send.php',$('#myFormId').serialize(),function(){
   // what i want to do with the response
})

4) in my php page I can easily loop over

foreach($_POST['item1'] as $item){
    // do what you want with data
}

that's it!

Upvotes: 2

venkat7668
venkat7668

Reputation: 2777

Try this

JS :  

$.post("../send.php",{items:items}); //send to server

PHP:

$_POST['items'] // catch in server

Upvotes: 1

Related Questions