Search code examples
phpjqueryajaxcodeigniterform-serialize

How to post form serialize data using PHP?


I have a form that contain dynamically generated fields. I need to post the form using .serialize().

Ajax

$("#save").click(function () {                              
    formData = $('#myForm').serialize();
    $.ajax({
        type:"POST",         
        url: base_url +'home/save',
        data: {
            formData:formData,
            csrf_test_name: csrf_token
        },
        success: function(response){         
            console.log(response);           
            alert(response);
        }     
    }); 
});

I need to post all the data using input field name. Now I got all the result like that:

   echo $fomdata=$this->input->post('formData');

output

room_count_new=5&room_id=1&bedcount_1_1=1&extra_age_1_1_1=middle&extra_age_1_1_2=0&bedcount_1_2=0

But I want to post with the corresponding name.


Solution

  • Get rid of the object with formdata property and only send the serialized string and add the csrf to the end of it or add the csrf to the form as a hidden input and let it get serialized also in serialize()

    $("#save").click(function() {
      var formData = $('#myForm').serialize();
      formData += '&csrf_test_name=' + csrf_token
    
      $.ajax({
        type: "POST",
        url: base_url + 'home/save',
        data: formData,
        success: function(response) {
          console.log(response);
          alert(response)
        }
      });
    });
    

    Then in php access the same names as in form.

    $fomdata=$this->input->post();
    
    $roomCount = $fomdata['room_count_new'];
    $csrfToken = $fomdata['csrf_test_name'];