-1

I want to send FirstName, LastName and Image through Ajax Call to PHP. I am able to send the data without image, and I am able to send the image without text using formdata but the problem is I am not able to do both at a time. Kindly check my code what I am doing wrong:

<script>
 function createBasicInfo() {

  // For Image Send
  var formdata = new FormData();
  var file = jQuery('#photo').prop('files')[0];
  formdata.append('photo', file);

 // For Text Send
 var data = {
  'firstname'       : jQuery('#firstname').val(),
  'lastname'     : jQuery('#lastname').val(),
  };


 **//Here Is the Problem, I am not able to append the data with Text**
 formdata.append(data);



//Ajax call Start Here
jQuery.ajax({
    url: '/adminseller/parsers/sbasicinfo.php',
    method: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    data: formdata,
    success: function(data) {
        if (data != 'passed') {
            jQuery('#modal_errors_1').html(data);
        }
        if (data == 'passed') {
            jQuery('#modal_errors_1').html("");
            location.reload();
        }
    },
    error: function() {
        alert("Something went wrong.");
    },
   });
  } 
</script>

In above code if I comment

//formdata.append(data);  // Then only image will send to php

And If I use in Ajax Call

        data: data, // Then only FirstName & LastName will send to php without Image

I am not able to send text data and image both at the same time to php file. Any idea or suggestion would be welcome.

Sarah
  • 405
  • 2
  • 7
  • 23

2 Answers2

0

You could just do this insted of formdata.append(data):

formdata.firstname = jQuery('#firstname').val();
formdata.lastname = jQuery('#lastname').val();
Rikard
  • 191
  • 1
  • 6
0

Just append your firstname and lastname into formdata. Then send full formdata.

<script>
function createBasicInfo() {

    var formdata = new FormData();
    var file = jQuery('#photo').prop('files')[0];
    formdata.append('photo', file);
    formdata.append('firstname', jQuery('#firstname').val());
    formdata.append('lastname', jQuery('#lastname').val());

    //Ajax call Start Here
    jQuery.ajax({
        url: '/adminseller/parsers/sbasicinfo.php',
        method: 'POST',
        cache: false,
        contentType: false,
        processData: false,
        data: formdata,
        success: function(data) {
            // ...
            // ...
        },
        error: function() {
            alert("Something went wrong.");
        },
    });
}
</script>
Mahfuzur Rahman
  • 1,497
  • 18
  • 23