1

I have to send a 2-dimensional array (along with several other variables) to PHP using jQuery.ajax(). I believe my options are:

  1. Serialize to json with JSON-js
  2. Send both arrays as csv strings and recompile on the other side.

My questions are:

A. Is there anything wrong with option #2 if I'd prefer not to include another library for a small function? B. Are there other options besides options #1 and #2?

Thanks!

Kyle Cureau
  • 19,028
  • 23
  • 75
  • 104
  • Since you've included jQuery as a tag, could you just use the jQuery [`.serializeArray`](http://api.jquery.com/serializeArray/) function to serialize the JavaScript array and PHP's [`json_decode`](http://php.net/json_decode) to decode it? – Francois Deschenes Jul 21 '11 at 22:54
  • `.serializeArray` ...the name would suggest it's exactly what I'm looking for. I looked at the link you provided and it seems that it takes `$(":input")` or `$('form')` and *returns* an array with the name and values of the form elements. So (if I were using a form) it leaves me with the same problem I had before, unfortunately. But thanks for the link - good to know it exists! – Kyle Cureau Jul 21 '11 at 23:06

3 Answers3

2

You can try :

JSON.stringify(array);

No extra library required.

ChristopheCVB
  • 7,269
  • 1
  • 29
  • 54
  • JSON.stringify is missing from jQuery 1.4.1, which is the lib I'm using. Not sure if it was reintroduced in newer versions. JSON.parseJSON allows for the decoding, but no functions for the encoding that I'm aware of. Take a look at this: http://stackoverflow.com/questions/2277405/json-stringify-missing-from-jquery-1-4-1 – Kyle Cureau Jul 21 '11 at 23:08
  • Cool...I tried to find support. IE7 and below no support. Any other one you know of? – Kyle Cureau Jul 21 '11 at 23:17
0

I'm sure there are other options; there's always a million ways to skin a cat. But I'd suggest option #1. When you send it as a JSON string (using a library that is quite small and only has two methods), you can then decode it in PHP using json_decode. No fuss, no muss.

Jonathan M
  • 17,145
  • 9
  • 58
  • 91
0

A. Is there anything wrong with option #2 if I'd prefer not to include another library for a small function?

You might have issues with escaping/unescaping some characters.

B. Are there other options besides options #1 and #2?

Surely there must be. But I'd go with JSON, it's the simplest and cleanest solution.

ngn
  • 7,763
  • 6
  • 26
  • 35