Abdul Rahman
Abdul Rahman

Reputation: 1705

How to pass Array with values using Ajax in jquery and get the values in Php page

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

Upvotes: 1

Views: 7000

Answers (4)

Hamza Qureshi
Hamza Qureshi

Reputation: 202

Can be helpful in future for someone

var jsonString = JSON.stringify(my_ary);
   $.ajax({
        type: "POST",
        url:'url',
        data: {data : jsonString}, 
        
    });

Upvotes: -1

AlanP
AlanP

Reputation: 447

Or you can format a query string like this:

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

... data: query_string,

Upvotes: 1

RAUSHAN KUMAR
RAUSHAN KUMAR

Reputation: 6006

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);
   }

Upvotes: 2

Neeraj Pathak
Neeraj Pathak

Reputation: 759

$.ajax({
  url:'url',
  data:JSON.stringify(my_ary)

you need parse arrays into the string.

I hope it helps you

Upvotes: 1

Related Questions