Skip to content Skip to sidebar Skip to footer

Submit Form With Ajax But Get "Illegal Invocation"

I try to submit form via ajax, below is the form.
$.ajax accepts:

Type: PlainObject or String or Array

So, your form_data should be in one of those formats - it should not be an instantiation of a FormData. It depends on what your backend is expecting, but one option would be to convert the form's values to an object with serializeArray():

on_click_form_submit = function(event) {

  event.preventDefault();

  var form_data = $('#request-form').serializeArray(),
    form_url = '/' + $('#request-form')[0].action.split('/').pop();

  console.log('url: ' + form_url);
  $.ajax({
      url: form_url,
      type: 'POST',
      data: form_data,
      dataType: 'json',
      encode: true
    })
    .done(function(response) {
      alert(response);
    })
    .fail(function(xhr, status, error) {
      alert(xhr.responseText);
    });

  return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-vertical" method="POST" id="request-form" action="/post_handler?request=add_data" enctype="multipart/form-data">
  <div class="form-group">
    <label for="date_inp" class="control-label">Date</label>
    <input class="form-control hasDatepicker" id="datepicker" type="text" name="date">
  </div>
  </div>
  <div class="form-group">
    <label for="file_inp">Upload File</label>
    <div>
      <input class="form-control" id="file_inp" type="file" placeholder="Upload File" name="file">
    </div>
  </div>
  <div class="form-group">
    <div>
      <button type="submit" class="btn btn-default submit-button" onclick="on_click_form_submit(event);">Submit</button>
    </div>
  </div>
</form>

Post a Comment for "Submit Form With Ajax But Get "Illegal Invocation""