Nassereddine Sadoun Nassereddine Sadoun - 1 month ago 5
Ajax Question

sending data to controller in AJAX using FormData Object

i'm working with CodeIgniter, and i'm trying to send some datas to a controller with AJAX by using a FormData object.

The problem is that when i try to get the datas in the controller by using $this->input->get_post("AttributeName"), the content of it is NULL.
here's the code:

The View:

<input type="text" name="firstName" id="new-member-firstName" class="new-event-text-input" autocomplete="off"/>
 
<input type="text" name="lastName" id="new-member-lastName" class="new-event-text-input" autocomplete="off"/>
 
<input type="text" name="title" id="new-member-title" class="new-event-text-input" autocomplete="off"/>
 
<input type="text" name="mail" id="new-member-mail" class="new-event-text- input" autocomplete="off"/>


The JQuery Script:

var formData = new FormData();
formData.append("affiliation", $("#selectedAffiliate").val());
formData.append("firstName", $('#new-member-firstName').val());
formData.append("lastName", $('#new-member-lastName').val());
formData.append("title", $('#new-member-title').val());
formData.append("mail", $('#new-member-mail').val());
 
alert($("#selectedAffiliate").val())
 
$.ajax(
{
url:$("#URL").attr("myURL") + NewEvent/DataWriters/DataWriterForComities/addMember',
   type:'post',
   data:{ formData },
   cache: false,
   contentType: false,
   processData: false,
   datatype: 'html',
   success:function(res)
   {
    alert("The Member has been registred");
   },
   statusCode:
   {
      500:function()
      {
         alert(500);
      },
      403:function()
      {
         alert(403);
      },
      400:function()
      {
         alert(400);
      }
 
    }
});


The Controller:

public function addMember()
{
$this->load->model('Member');
 
$member = new Member();
$member->setLastName( $this->input->get_post("lastName") );
$member->setFirstName( $this->input->get_post("firstName") );
$member->setMail( $this->input->get_post("mail") );
$member->setTitle( $this->input->get_post("title") );  
$memberId = $member->save();
echo $memberId;
}


what's the correct way to get these datas, because i checked everything else and it's fine.

Answer

you should use formData directly, no need to warp it in an object, as follow:

data:formData,