views:

58

answers:

3

I have a few arrays that I want to send to process with PHP. Using json2.js I will stringify the arrays like so:

var JSONlinks = JSON.stringify(link_array);
var JSONnotes = JSON.stringify(note_array);

but then I'm confused. Do I need to use a XMLHttpRequest object? Is there another way? If that is the simplest way, could someone please just share the most basic instance of the code needed in order to send to PHP where I can then use JSON decode? I think it might help others in the future really.

I'm currently using Jquery and I know there are many options out there for frameworks and each one may or may not make this process any easier. If you're using a framework in your reply please mention why you'd choose that framework rather than just javascript.

+2  A: 

Like this:

$.post('path/file.php', 
    { links: link_array, notes: note_array }, 
    function(response) { ... }
);
SLaks
@Slaks, thanks. I know this is a shortcut for what @karim posted. Upvoted you for that.
dscher
A: 

try jquery.post() -> http://api.jquery.com/jQuery.post/

yamspog
+3  A: 

You can send the object many ways in jQuery, most flexibly using $.ajax:

$.ajax({
  type: 'POST',
  url: my_url,
  dataType: 'json',
  data: JSONlinks,
  success: function() { alert('success!') }
});

Bear in mind:

Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

See http://api.jquery.com/jQuery.ajax/

karim79
I can't get the above code to work. I'm sure I'm doing something stupid but I can't figure out what it is. Should I get an alert if I'm only sending the data to my PHP script but am getting nothing back? I don't want something back. Thanks for the answer.
dscher
@dscher - You can omit the success callback if you don't want anything back. You should probably use firebug to check that the request is getting through.
karim79
Thanks, getting a 403 error...think my framework is preventing me from posting that data to the controller in Kohana. That is certainly the problem. I'm new to jQuery and javascript actually so I didn't even think to use Firebug to troubleshoot. Great tip for this newbie!
dscher