-1

I have an associative array in JavaScript that looks something like this:

data = { 1: "DA", 2: "DA", 3: "NE", 4: "DA", 5: "NE", "ime": "Kojo" }

I've converted it using jQuery.param(data) and I got something liek

1=DA&2=DA&3=NE&4=DA&5=NE&ime=Kojo

Don't mind the values

How can I pass that to PHP to ajax using $_GET? And how can I receive it in PHP afterwards, still as an array? Thanks

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57

1 Answers1

1

You could convert the object to a string using JSON.stringify and pass it as one parameter. On the PHP side, you can use json_decode to convert it back to an array.

// JS
$.get('endpoint',{data: JSON.stringify(data)});

// PHP
$data = json_decode($_GET['data']);

You could also pass in the raw object as data. As far as I remember, jQuery serializes it into a flat string structure. On the PHP side, it's automatically converted into an associative array.

// JS
$.get('endpoint',{data: data)});
// endpoint?data[1]=DA&data[2]=DA&data[3]=NE&data[4]=DA&data[5]=NE&data[ime]=Kojo

//PHP
$data = $_GET['data'];
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • What exactly am I passing as data in the second method you described? Should I make a variable like var strData = $.get('endpoint',{data: data)});, or what? – Aleksa Kojadinovic Apr 25 '15 at 15:22
  • @AleksaKojadinovic `data` there is the `data` in your post. `$.get` does a ajax GET request. – Joseph Apr 25 '15 at 17:00