skip to Main Content

I am using AJAX to save some data. I need to save FormData and other info. I am using the below function, but I am not sure how to add the other information to the FormData object. Could you please help?

function vignetteAjax(company_id, client_id, type_id, url) {
  var formData = document.getElementById("edit_form");
  var fd = new FormData(myform);

  $.ajax({
    url: url,
    type: "post",
    data: {
      "_token": "{{ csrf_token() }}",
      "company_id": company_id,
      "client_id": client_id,
      "type_id": type_id,
    },
    beforeSend: function() {},
    success: function(data) {
      console.log('done');
      $("#policies_list").empty().html(data);
    },
    complete: function() {
      console.log('compete');
    }
  });

  return 0;
}

3

Answers


  1. You can send the entire Form-Data via Post

    data: {
        "_token": "{{ csrf_token() }}",
        "company_id": company_id,
        "client_id": client_id,
        "type_id": type_id,
        formData: $('#edit_form').serialize()},
    },
    

    Also, hence you are using jQuery, you dont need to use document.getElementById(“edit_form”). You can directly use $(‘#edit_form’).
    On the PHP Side (assuming you use PHP), use parse_str to unserialize.

    parse_str($_POST['formData'], $formData);
    
    Login or Signup to reply.
  2. you just need to append the other data with your FormData

    var fd = new FormData(myform );
    fd.append('NameHere',"ValueHere");
    // Rest of Code 
    
    Login or Signup to reply.
  3. Use the append method to add the additional data to the FormData object, then send just the FormData object.

    var formData = document.getElementById("edit_form");
    var fd = new FormData(myform);
    fd.append("_token", "{{ csrf_token() }}");
    fd.append("company_id", company_id);
    fd.append("client_id", client_id);
    fd.append("type_id", type_id);
    
    $.ajax({
        url: url,
        type: "post",
        data: fd,
        contentType: false,
        processData: false,
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search