1

I have an ajax posted parameter as below:

$.ajax({
      url:'url',
      data:{ary:my_ary},
  ...

Where value in the my_ary = Array([0]=> Test Text,[1]=> test Text2)

Now i need to get values from this array using a foreach() loop like this:

 foreach($_POST['ary'] as $val){
         echo($val.'<br>');
   }

But it is showning the following error

An invalid arguments passed to foreach loop

Rob Quincey
  • 2,834
  • 2
  • 38
  • 54
Abdul Rahman
  • 1,669
  • 4
  • 24
  • 39

4 Answers4

2

Convert the array to a string before passing it like so:

my_ary.join(',');

Or if it's a complex array consider JSON:

JSON.stringify(my_ary);

In case of your associative array

$.ajax({
   url:'url',
   data:{
      my_ary:JSON.stringify(my_ary);
   }
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
  • My array looks like: my_ary: Array(++++[0]+=>+Mr.+Justice+Waqar+Ahmad+Seth++++[1]+=>+Mr.+Justice+Rooh-ul-Amin+Khan+) this is the result when checked in browser developers tool – Abdul Rahman Jun 19 '17 at 07:34
1
$.ajax({
  url:'url',
  data:JSON.stringify(my_ary)

you need parse arrays into the string.

I hope it helps you

Neeraj Pathak
  • 759
  • 4
  • 13
1

Or you can format a query string like this:

var query_string = "action=" +  "action_name" + "&data_id=" + data_id + "&nonce=" + nonce;    

... data: query_string,

AlanP
  • 447
  • 8
  • 18
-1

Can be helpful in future for someone

var jsonString = JSON.stringify(my_ary);
   $.ajax({
        type: "POST",
        url:'url',
        data: {data : jsonString}, 
        
    });
piotrek1543
  • 19,130
  • 7
  • 81
  • 94
Hamza Qureshi
  • 172
  • 2
  • 20