Grabbing (& parsing) array sent from ajax

a few weeks ago had the same problem with java… got a lot of responses, most of which involved json; but in the end the solution was very simple, & did not require json:

java:

String[] resp = request.getParameterValues("colors[]");

if (resp.length > 0) { 
    for (int i=0; i < resp.length; ++i) {
       out.println(resp[i] + "<br>"); 
    }
}

jquery:

var arrColors = ["red","blue","green","yellow"];

$.ajax({
   url:"array.jsp",
   type:"POST",
   data: {colors:arrColors},
   success:function(data){
     $("#output").append( data );
   },
   error: function() {
    $("#output").append('fail'); 
   }
    
});

based on code here,

I changed ‘data’ line to:

data: "colors="+arrColors,

& was able to grab the array, but I can’t parse it:

php:

$arrColors = $_POST['colors'];

this

echo $arrColors;

prints

“red,blue,green,yellow”

and this

 echo count($arrColors);

prints just

“1”

and I can’t parse it and print it like I do in java (with loop, inserting ‘<br>’ after each element…)

I also explode it (again, based on code in url above),

$arrColorsExpl = explode(', ', $arrColors);

and this

print_r($arrColors);

prints:

“Array ( [0] => red,blue,green,yellow )”

(& I can only print it with print_r, and not echo (???) )

(& again, I can’t parse it to print it however I want…)

& this

for ($i=0; $i < count($arrColors); $i++) {
   echo $arrColors[i] + '<br>'; 
}

prints simply: “0”

& this

foreach ($arrColors as $element) {
  echo $element . '<br>';
}

prints nothing…

I would like this to work with the same flexibility as in java… I would appreciate some help… (I have limited access to the internet now, probably won’t see any response(s) till Monday…)

thank you…

@maya90,

I think your question is in js forum,

try this in your ajax

data: 'colors='+JSON.stringify(arrColors)

and decode that in your serverside

$colors = json_decode($_POST[‘colors’],true);

No, a json string is almost never going to be a valid url string The function needed here is one of PHP’s more poorly named functions - parse_str

I did not know that,but why ?

Well, for starters, do these look anything alike to you?

JSON Encoded

{"colors":["red","orange","yellow","green","blue","violet"]}

HTTP Query Encoded

colors%5B0%5D=red&colors%5B1%5D=orange&colors%5B2%5D=yellow&colors%5B3%5D=green&colors%5B4%5D=blue&colors%5B5%5D=violet

The strings above were built by this PHP script (5.4+):

<?php

$data = [ 'colors' => ['red','orange','yellow','green','blue','violet']];

echo json_encode($data);
echo "\n\n";
echo http_build_query($data);

hi Jemz,

mi question in jQuery forum was about grabbing the array with java (that is solved now… as I explained at the top of my OP… I even showed the java code for it, hoping I could be pointed to an equiv code in PHP…) I had also posted a question here, but that was solved… now problem is getting the array with PHP… :wink:

since this was solved in java w/o json, I suspect there should be a way of getting w/o json in PHP also, but am not sure…

thank you for your response…

The PHP equivalent to this line is just to check $_REQUEST[‘colors’]. Note however that in PHP it is advised you use $_GET for get requests and $_POST for post requests. All three of these are superglobals - that is they are available in all scopes throughout the program.

it is recommended to never use $_REQUEST as that allows your visitors to set up a cookie on their system containing whatever they want and to feed that instead of the querystring or post value.

Uhm, very next sentence in my post:

[quote]Note however that in PHP it is advised you use $_GET for get requests
and $_POST for post requests.[/quote]

Geez, calm down dude. Also, you’re partially wrong. The assembly order of the $_REQUEST var is subject to a php.ini setting - the default is indeed Get, Post, Cookie, but you can change it to mitigate such mischief to, say, Cookie, Get, Post. The main reason $_REQUEST is a problem is it gives no context for the data as to the user’s intent - where GET implies data lookup and POST a data write. 99% of the time a user setting a cookie to override POST and GET values they’d just be screwing themselves over. If loading an arbitrary value off a cookie messes up the system’s security, it wasn’t secure to begin with.

1 Like

I was agreeing with you and expanding on what you said.

thank you very much… this worked… :slight_smile: however:

this

foreach($arrColors as $element) {
      echo  $element . ' === <br>';
    }

prints fine…

but the traditional loop still prints “0000”… (???)

thank you very much…

PS: in response to Michael Morris: I did use $_POST for the request… (see my OP… thank you…)

When doing a post from ajax the object passed an argument will be the encoded by the library for you - you don’t need to do a json stringify. That is this object

{
  name: 'Aaron',
  location: 'New York'
}

Will generate a $_POST[‘name’] and $_POST[‘location’]. It is important to note that the data contained in each key must be a string AFAIK, I’ve ever tried passing anything else. You could JSON stringify that and then use json_decode on the PHP side…

{
  colors: JSON.stringify(arrColors)
}

But strictly speaking, even POSTS are html encoded, but they are decoded before populating the $_POST array so we never see them in the encoded state. You can verify this by looking at the request headers for the page.

ooppps… special chars are not getting passed…

array now:

var arrColors = ["M&oacute;nica", "Saleem", "Rob", "Mar&iacute;"];

this

count($arrColors)

returns “0”

and neither loop prints anything…

(in foreach loop, I get an “invalid argument” error…)

(please note, np at all getting spec chars to pass in java, with code I posted above, in OP (I posted java and jQuery ajax code at very top of OP…))

so is this a JSON thing? yikes…;~(

thanks again to all for your help…

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.