jemz
jemz

Reputation: 5153

how to retrieve array in hidden field

I am storing my array in hidden field

var myarray = [];

if ($(this).prop('checked')) {
    myarray.push(val);
    $('#myhidden').val(JSON.stringify(myarray));

}

how can I retrieve that array ? because I want that array to past it to other page using jquery.ajax

I tried this

var retarray  = $('#myhidden').val();

["110","118"]

when I send that using jquery.ajax

$.ajax({
  type: 'post',
  dataType: 'json',
  url: 'tootherpage.php',
  data: 'param1=' + param1 + '&param_array=' + retarray,
  success: function(data) {


  }

});

it gives me error because it is not an array.

Thank you in advance.

Upvotes: 0

Views: 53

Answers (4)

Alex Nikulin
Alex Nikulin

Reputation: 8699

You can do this :

$('#myhidden').val(myarray.split("|")); //set "0|1".split("|") - creates array like [0,1] 
myarray = $('#myhidden').val().join("|"); //get [0,1].join("|") - creates string like "0|1"

"|" is a symbol that is not present in array, it is important.

Upvotes: 0

Anish Patel
Anish Patel

Reputation: 4402

Your ajax request is is using the method POST and you have specified a data type of json which means your http request is sending json in the body.

So you can send your whole request message as json, like this:

// get json from input
var retarray  = $('#myhidden').val();

// parse json into js
var arr = JSON.parse(retarray);

// create your request data
var data = { param1: param1, param_array: arr };

// stringify
var json = JSON.stringify(data);

$.ajax({
  type: 'post',
  dataType: 'json',
  url: 'tootherpage.php',
  data: json, // the json we created above
  success: function(data) {


  }

});

Then in your php script you can deserialize the json message to a php object like so:

$json = file_get_contents('php://input'); $obj = json_decode($json)

Upvotes: 0

jrath
jrath

Reputation: 990

Try this

 var retarray = encodeURIComponent($('#myhidden').val());

Upvotes: 0

jasonscript
jasonscript

Reputation: 6178

You're converting your array to a string here:

$('#myhidden').val(JSON.stringify(myarray));

If you need it to be an array, then you need to parse this array back from the string

var retarray  = JSON.parse($('#myhidden').val());

for example:

var array = [1,2,3,4];  // create an array
var stringarray = JSON.stringify(array);  // convert array to string
var array2 = JSON.parse(stringarray);  // convert string to array

Upvotes: 2

Related Questions