0
votes

I'm trying to upload files with datas using ajax. here is my html form :

<body>
  <input type="text" id="name" value="test" />
  <input type="file" id="pic" accept="image/*" />
  <input id = "submit" type="submit" />
</body>

when I send the uploaded file alone with ajax it is working using new FormData();

var file_data = $('#pic').prop('files');   
var form_data = new FormData();                  
form_data.append('file', file_data);
alert(form_data);                             
$.ajax({
            url: 'test.php', // point to server-side PHP script 
            dataType: 'text',  // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(php_script_response){
                alert(php_script_response); 
            }
 });

but Idon't know how to send the input 'name' with Data

var DATA = 'name='+name;

$.ajax({
  url: "test.php",
  type: "post",
  data: DATA,
  success: function (response) {
    console.log($response);             
  },
});

Thanks

2
just on one ajax you can add the input value to the data by using form_data.append('input_name', $('#name').val()); - Mohamed-Yousef

2 Answers

0
votes

First of all you should include form tags such as the following example.

<form id="uploadForm" enctype="multipart/form-data" action="http://yourdomain.com/upload" method="post" name="uploadForm" novalidate>
    <input type="text" id="name" value="test" />
    <input type="file" id="pic" accept="image/*" />
    <input id = "submit" type="submit" />
</form>

Then you can send all of the form data using code such as the following:

var form = $('#uploadForm')[0];
var form_data = new FormData(form);

To answer your specific question about sending the value of only the text field with ID "name", simply use the following line:

var DATA = 'name=' + $('#name').val();
0
votes

var name = $("#name").val(); form_data.append('name', name); Maybe it's wrong, please try