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

5
  • 1
    just do print_r($_POST); and show the output from the php file Commented Jun 19, 2017 at 7:30
  • send array with json_encode and decode your array in code before loop. Commented Jun 19, 2017 at 7:31
  • Is there any jquery / javascript function to decode the array and send it as parameter? and if yes then how i will decode this encoded array in PHP ? Commented Jun 19, 2017 at 7:33
  • 2
    please refer this stackoverflow.com/questions/8890524/… Commented Jun 19, 2017 at 7:33
  • For decode array in php json_decode(); function is used :) Commented Jun 19, 2017 at 7:35

4 Answers 4

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);
   }
Sign up to request clarification or add additional context in comments.

1 Comment

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
1
$.ajax({
  url:'url',
  data:JSON.stringify(my_ary)

you need parse arrays into the string.

I hope it helps you

2 Comments

let suppose it work here , then how i will get values from this parameter in php page?
then you need parse JSON string into objects stackoverflow.com/questions/17488207/…
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,

Comments

-1

Can be helpful in future for someone

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.