mongotop
mongotop

Reputation: 5774

upload a file in the same page as the form using php and ajax not working

Trying to upload a file using php/ajax but seems like its not working, maybe its not recognizing the $_FILES["file_name"]["tmp_name"] variable in the upload_file.php because I could not display it in the page.

Can you please help!

index.html

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="upload_file.js"></script>

<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file_name" id="file_name" />
<input type="submit" name="submit" value="RUN" id ="btnSubmit"> 
</form>

<div id='upload_here_div'></div>

upload_file.js

$(document).ready(function(){

    console.log(file_name +'uplooad');

    $('#btnSubmit').click(function(e) {

        console.log('click trigger');
        var file_name           = $("#file_name").val();


        $("#upload_here_div").load("upload_file.php?file_name=" + client_info )
        console.log('value for file_name=' + file_name ); //
      });

});

upload_file.php

<?php
$file_name  = $_REQUEST['file_name'];

if ( isset($_FILES["file_name"])) {

    //if there was an error uploading the file
    if ($_FILES["file_name"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file_name"]["error"] . "<br />";
    }
    else {

          $file_locatioon = "upload/".$file_name ;
          echo 'file_locatioon = '.$file_locatioon."<br>";
          move_uploaded_file($_FILES["file_name"]["tmp_name"], $file_locatioon);
          echo "ploaded!!<br>";
    }

 } else {echo "No file selected <br />";}
?>

Upvotes: 2

Views: 996

Answers (2)

Javakid
Javakid

Reputation: 357

I found this tutorial before and tested OK. By using FormData may give what you want.
But please take the browser compatibility in consider. For more information please reference here.

Upvotes: 1

Gary Liu
Gary Liu

Reputation: 13918

I think you get a same problem with this jQuery Ajax File Upload. Maybe it is helpful for you.

Upvotes: 1

Related Questions