1

I want to send a file from an input to a php script, using ajax. Here is what I've done so far:

HTML

  <div id="inserting">
     <button id="inserting_btn">Upload</button>
     <input type="file" id="inserting_file"/>
   </div>

JS

$('#inserting_btn').click(function(){
        var file = $('#inserting_file').val();
        $.ajax({
            method: 'POST',
            url: 'input_text/import.php',
            data: 'file='+file,
            success: function(data){
                alert(data);
            }
        });
    });

PHP file import.php

if ($_FILES['file']['tmp_name'] ){
       echo 'yes';
    }
    else {
        echo 'no';
    }

(Sorry for my english.)

2
  • Possible duplicate of jQuery AJAX file upload PHP Commented Apr 24, 2017 at 0:25
  • I just use - data: { "file": file }, Commented Apr 24, 2017 at 22:09

2 Answers 2

1
data: {file: file}

try replacing your data line with this

and in php

 $file = $_POST['file'];
Sign up to request clarification or add additional context in comments.

Comments

0

Try to change this in your code :

$('#inserting_btn').click(function(){
    var file_rec = $('#inserting_file').prop("files")[0]; // get the file
    var form_data = new FormData();                  
    form_data.append('file', file_rec);
    $.ajax({
        method: 'POST',
        url: 'input_text/import.php',
        data: form_data,
        success: function(data){
            alert(data);
        }
    });
});

PHP file import.php

if ($_FILES['file']){
   echo 'yes';
}
else {
    echo 'no';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.