Sunil Aggarwal
Sunil Aggarwal

Reputation: 3

posting text file thru jQuery ajax in php and download the response file

Requirement:

I have to submit a form in a PHP file which has a file type input. I need jQuery ajax to post this text file to lets say processFile.php

processFile.php will take this text file as input and after processing will return a csv file which I want to download at the client.

I have seen many posts but nothing is helping me out.

HTML:

    <form id="utilityForm" class="utilityForm4" method="POST" enctype="multipart/form-data" style="margin-top:25px">
        <input type="file" name="image" id="image"/>
        <br/><input type="submit" name="download" class="submit" value="Submit"/>
  </form>

jQuery:

$(document).ready(function(){
      $(".submit").click(function(e){
var urlstring = "processFile.php"
          var form_data = new FormData($(this)[0]);
          $.ajax({
                url : urlstring,
                type: "POST",
                data : postData,
                success:function(result){
                         var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
                         window.open(uri, 'result.csv');
                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                    alert('failed');
                    echo (errorThrown);
                }
          });
      });
}); 

I have tried hundreds of solutions given on the net but none is working.

Upvotes: 0

Views: 804

Answers (1)

KinjalB
KinjalB

Reputation: 121

Here I am providing complete working example:

HTML File:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
    $("#uploadimage").on('submit',(function(e) {
        e.preventDefault();

        $.ajax({
        url: "ajax_php_file.php", // Url to which the request is send
        type: "POST",             // Type of request to be send, called as method
        data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
        contentType: false,       // The content type used when sending data to the server.
        cache: false,             // To unable request pages to be cached
        processData:false,        // To send DOMDocument or non processed data file it is set to false
        success: function(result)   // A function to be called if request succeeds
        {
                e.preventDefault();  //stop the browser from following
                window.location.href = 'upload/'+result;
        }
        });
    }));

// Function to preview image after validation

});
</script>
</head>

<body>

<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<a href='#' id="tmpcsv" style="display:none">Download</a>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</form>
</body>

PHP File:

<?php
if(isset($_FILES["file"]["type"]))
{
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);

    if (file_exists("upload/" . $_FILES["file"]["name"])) 
    {
        echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
    }
    else
    {
        $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
        $targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
        move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
        echo $_FILES["file"]["name"];
    }
}
else
{
    echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
?>

Try to upload any file. Is this useful for you?

Upvotes: 1

Related Questions