I have a bit of a conundrum. I have a form which has numerous fields. There is one field for links where you enter a link, click an add button, and the link(using jQuery) gets added to a link_array. I want this array to be sent via the jQuery.ajax method when the form is submitted. If I send the link_array using $.ajax like this:
$.ajax({
type: "POST",
url: "add_stock",
dataType: "json",
data: { "links": link_array }
});
when the add link button is selected the data goes no problem to the correct place and gets put in the db correctly. If I bind the above function to the submit form button using $(#stock_form).submit(….. then the rest of the form data is sent but not the link_array.
I can obviously pass the link array back into a hidden field in HTML but then I’d have to unpack the array into comma separate values and break the comma-separated string apart in PHP. It just seems 100X easier to unpack the Javascript array in PHP without an other fuss.
So, how is it that you can send an array from javascript using $.ajax concurrent to the rest of the $_POST data in HTML?
Please note that I’m using Kohana 3.0 framework but really that shouldn’t make a difference, what I want to do is add this js array to the $_POST array that is already going.
Thanks!
If you actually want to submit the form (e.g., with page refresh and all that), your only option is to add a series of
<input type='hidden'>fields to the form with the namelinksand fill each of them with one of the values from the array. Then what you get at the other end will be essentially what you get with your$.ajaxcall above.If you just want to send the data to the server but you don’t actually need to submit the form, you can use
serializeon the form to get a URL-encoded string for it, then append your links to the end of the string, and send that viaajax. Something like this:We get the beginning of the URL-encoded string from
serialize, initialize an array with it, then push encoded fields for each link on it. Then we useArray#jointo collect that all into one string to send with theajaxcall. (You could do this with string concat instead if you like, but building these long strings with an array is faster after a certain number of elements, and makes the whole “do I put an&on it or not” just fall out naturally as well.)