0

I do an ajax call to my script to upload a file, now I want to show some feedback of certain checks like if the file already exists.

I can't get it to show the response of my script. Why is the response not showing?

Here is my ajax call:

$(document).ready(function()
{
    $("#upload").submit(function(e)
    {
        e.preventDefault();

        $.ajax(
        {
            url: "upload.php",
            type: "POST",
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            success: function(data)
            {
                //i want response here true or false
                location.reload(true);
            }
        });
    });
});

the upload.php script:

<?php

$dir = 'files';

echo upload();

/**
 * Upload a file
 *
 * @return bool
 */
function upload()
{
    // Storing source path of the file in a variable
    $sourcePath = $_FILES['file']['tmp_name'];

    // Target path where file is to be stored
    $targetPath = "files/".$_FILES['file']['name'];

    // Check if file already exists
    if (file_exists($_FILES['file']['name'])) {
        return false;
    }

    // Moving Uploaded file
    move_uploaded_file($sourcePath,$targetPath) ;

    return true;
}

1 Answer 1

2

at first, a return on php is made for internal stuff. You need to echo a string to get the value back to js:

<?php
 echo "true";
?>

And you need a simple if to check for that in js:

if(data=="true"){
  window.location.reload();
 }

Complete code:

$(document).ready(function(){
        $("#upload").submit(function(e){
            e.preventDefault();
            $.ajax({
                url: "upload.php",
                type: "POST",
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData:false,
                success: function(data)
                {
                      if(data=="true"){
                          //window.location.reload(); 
                          alert("upload finished!");
                     }           
                 }
            });
        });
    });
Sign up to request clarification or add additional context in comments.

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.