0

I have one form html then I have 2 input( input text and input file) my problem input text cannot send post to upload php. I using jquery ajax to post data

upload.php

<?php


$nama   = $_POST['name'];
$filename = $_FILES['file']['name'];


var_dump($nama);
var_dump($filename);

form

 <form method='post' action='' enctype="multipart/form-data">
                       <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />

                        Select file : <input type='file' name='file' id='file' class='form-control' ><br/>

          <input type='button' class='btn btn-info' value='Upload' id='upload'>
        </form>
<script type="text/javascript" >
  $(function() {
  $("#upload").click(function() {
    var name = $('#name').val();
    var fd = new FormData();
    var files = $('#file')[0].files[0];
    fd.append('file',files);

    $.ajax({
      type: "POST",
      url: "upload.php",
      dataType: 'text',  // what to expect back from the PHP script, if anything
      cache: false,
      contentType: false,
      processData: false,
      data: fd,
      success: function(){

      }
    });
  return false;
  });
  });
</script>
senaa
  • 1
  • 3

1 Answers1

0

Just remove dataType:text. Or you can use dataType:"json" as per your requirement. Well, you can read more on this dataType here also: $.ajax - dataType

And for name parameter, you are missing to append that variable in fd variable.

So, your script should be like this:

<script type="text/javascript" >
$(function() {
$("#upload").click(function() {
var name = $('#name').val();
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
fd.append('name',name); // you were missing this, that's why $_POST['name'] was blank
$.ajax({
  type: "post",
  url: "upload.php", 
  cache: false,
  contentType: false,
  processData: false,
  data: fd,
  success: function(){

  }
});
return false;
});
});
</script>

Now try by printing below code into your upload.php file:

<?php
echo $nama   = $_POST['name'];
echo $filename = $_FILES['file']['name'];
?>
Hetal Chauhan
  • 787
  • 10
  • 22
  • so great thanks.. hm I have one question how to attach cache: false, contentType: false, processData: false, in my code is : $.post(url, {fd},function() – senaa Feb 03 '18 at 18:36
  • hey senaa, can you please upload another question along with your code? It will be great.. – Hetal Chauhan Feb 05 '18 at 06:31