0

I need help, I can't find the solution. I have a javascript array which I need to pass to a php script that will store all the array values (max 3) on Session variables. My javascript array comes from a string.split call:

var indentificators = id.split("_");

What I need is some help on how to do the Ajax call and then how to get every element of the array one by one.

My main problem is the format that this data has to be sent and how to retrieve it.

PD: I would post my current ajax call code but I think it would not help, it´s all messed up.

MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89
Albert Prats
  • 786
  • 4
  • 15
  • 32

4 Answers4

1

JSON is your answer here.. Are you using a javascript library like jQuery or MooTools?

jQuery: How do I encode a javascript object as JSON?

url = 'target.php';
data = {identificators: JSON.stringify(identificators) };
jQuery.post( url, data, , function( response ) {
      //response handling
});

MooTools:

url = 'target.php';    
data = { identificators: JSON.encode(identificators) };

howto post (Async) in mootools: http://mootools.net/docs/core/Request/Request

In php:

$phpArray = json_decode($_POST['identificators']/$_POST['identificators']);
Community
  • 1
  • 1
0
var array = id.split("_");
data = JSON.stringify(array);
var url = 'you/url'    
$.ajax({
  type: "POST",
  url: url,
  data: {array: data},
});
Liauchuk Ivan
  • 1,913
  • 2
  • 13
  • 22
0

You can format your answer to send as JSON String

For example:

Javascript array:

var indentificators = id.split("_"); // [0] => 'Stack', [1] => 'Overflow'

so you can do this:

var response_to_send = "{\"var1\":" + indentificators[0] + ", \"var2\": " + indentificators[1] + "}";

here you receive this string in your php script (supposing the ajax request is successful and the value of the string in POST is 'values'):

$values = json_decode($_POST['values'])
echo $values[0]; // This print 'Stack' echo $values[1]; // This print 'Overflow'

I hope this is what your searching

Ollie Strevel
  • 861
  • 1
  • 14
  • 27
0

Finaly I solved it:

var identificadors = id.split("_");

$.ajax({
   url: './phpScripts/comunicador.php?method=sessioList',
   type: "POST",
   data: ({data: identificadors}),
   success: function(){
       alert('cool');
   }
});

Then at my php page:

function sessioList() { 

    $data = $_POST['data']; 

    $_SESSION['list_id_product']    = $data[0];
    $_SESSION['list_id_tarifa']     = $data[1]; 
    $_SESSION['list_index']         = $data[2];     

}

As I said, my main problem was the format for the data to be sent and how to get it.

Thanks all, I really appreciate it.

Albert Prats
  • 786
  • 4
  • 15
  • 32