Search code examples
jqueryajaxformsposthidden

jQuery AJAX also send hidden fields on form change


I've been searching for this all morning but didn't find anything that could help me. I couldn't figure this out with the manual... I've never really written any jQuery or javaScript so please be gentle.

I was able to figure out how to update the database when the user leaves the input field. :) But I also want to send the hidden input fields.

Here is my form & script (the form elements have the same NAME as ID so for this example I left them out to keep things readable)

<form id="Form">
  <input id='idA01-01-2017' type='hidden' value="1234"/>
  <input id='idB01-01-2017' type='hidden' value="5678"/>

  <input id='fromA01-01-2017' type='text' value=""/>
  <input id='toA01-01-2017' type='text' value=""/>
  <input id='fromB01-01-2017' type='text' value=""/>
  <input id='toA01-01-2017' type='text' value=""/>
  <input id="checkA01-01-2017" type="checkbox" value="1">
  <input id="checkB01-01-2017" type="checkbox" value="1">
  <input id='suggestion01-01-2017' type='text' value=""/>
</form>


<script>
    $('input, select', $('#Form')).change(function(){
        var dataFields = $(this).attr('id')+$(this).val();
    $.ajax({
            url: 'update.php',
            type: 'POST',
            data: dataFields,
           dataType: "json",
           success: function() {}
        })
    });
</script>

-edit- I'm very thankful to the help I got from Axel, but the script seemed to break my checkboxes.

The initial form was submit by onChange="document.Form.submit()" because of this I needed the hidden input fields before the checkboxes, to set the value in case the box was unchecked.

Now with the jQuery part this didn't work, so I removed the hidden fields and use the following script. As I'm completely new at jQuery there is probably a better way, but it seems to work alright.

    $('input, select', $('#Form')).change(function(){

    var FORMdata = {},

    // get current name
    currName = $(this).attr('name'),
    // extract the date
    sDate = currName.substr(currName.length - 10);

    //check if a checkbox is changed
    if (currName.indexOf("checker") >= 0 ){
       if($(this).is(":checked")) {
          FORMdata[currName] =  '1';
       } 
       else {
          FORMdata[currName] =  '0';
       }
    }else{
        // no checkbox was changed so it was a input field
        // add current field to data object
        FORMdata[currName] =  $(this).val();
        }

    $.ajax({
            url: 'update.php',
            type: 'POST',
            data: FORMdata,
            success: function() {
            }
        })
    });

Solution

  • In case you want just submit your changed fields plus the related (identified by the ending of each name attribute) hidden ones, you can do something like this:

    $('input, select').on('change, input', function(){
        var data = {},
            // get current name
            currName = $(this).attr('name'),
            // extract the date
            sDate = currName.substr(currName.length - 10);
    
        // add current field to data object
        data[currName] =  $(this).val();
    
        // loop over all hidden fields ending with the same 
        // identifier (date) add them to data
        $('#Form').find("input[type='hidden'][name$='"+ sDate+"']").each(function(){
            data[$(this).attr('name')] =  $(this).val();
        });
        $.ajax({
            url: 'update.php',
            type: 'POST',
            data: data,
            dataType: "json",
            success: function() {}
        })
    });
    

    In case you want to send complete form - jQuery has a function for this: serialize. You might also use the native method FormData which works in recent browsers:

    // also use input event to handle pasting of data
    $('input, select').on('change, input', function(){
        // jQuery way (strings only)
        var formData = $('#Form').serialize();
        // or native javascript (older browsers not supported)
        // var formData = new FormData(document.getElementById("Form"));
        $.ajax({
            url: 'update.php',
            type: 'POST',
            data: formData,
            dataType: "json",
            success: function() {}
        })
    });