Andrew Brown
Andrew Brown

Reputation: 125

Store HTML array values into javascript array to be sent via AJAX

I have a form, in which I am able to clone a table row. Each form element is is named as an array with [] after the name. This is no big deal if I am sending the form directly to a PHP script. I do not wish to refresh so I need to store the values in a javascript array then send that array to my php script etc. I am having a difficult time creating a NEW javascript variable that is an array of all the values.

One this is complete I'm sure requesting it in PHP is pretty straight forward.

Here is an example of my HTML form.

<form  class="form8" name="formfine">
  <table  class="tablesorter2" cellspacing="0" id="adddate"> 
    <tbody> 
      <tr> 
        <td>Expense:</td>
        <td>
          <select id="fineexpense" name='fineexpense[]'>
            <option value='Mortage/Rent'>Mortage/Rent</option>
            <option value='Auto'>Auto</option>
          </select>
        </td>
      </tr>
    </tbody>
  </table>
</form>

Here is my current AJAX function

function ajax_finesave(){

var hr = new XMLHttpRequest();
var url = "PHP/FFfinesave.php";
var fineexpense = document.formfine.elements['fineexpense[]'];

any help on this would be great, also the correct way to request an ajax sent variable would be helpful.Thank you

Upvotes: 2

Views: 782

Answers (1)

Toni Leigh
Toni Leigh

Reputation: 4971

There's a simple way using JQuery which is to serialise the form. The function is here.

The usage is ...

$('.form').serialize();

... and the resulting value is a query string that can be sent as a single variable to the server and dissected as required by your php, using a function like parse_str()

Another thing to remember about JavaScript is it's array can't be used like a keyed hash, as you'd see in PHP. You need to use an object for keys. So, you won't be able to create an array in JavaScript that mimics a php $_POST array.

You could build a JSON object out of your form and post that using AJAX (JQuery's version here) then use php's json_decode() to unwrap it server side. Do pay attention to the $assoc argument here as you need that to get an array in php.

A JQuery example follows:

var myJSON = {
  formField: $('.form-field').val(),
  anotherFormField: $('.another-form-field').val()
}

$.ajax({
  url: 'my-url',
  method: 'post',
  data: {
    formJSON: myJSON
  },
  success: function() {
    // success update here
  }
});

In the example myJSON is a JavaScript object with named keys which are populated with the form field values (though anything will do). This is how you'd mimic php associative arrays in JavaScript.

Upvotes: 1

Related Questions