Frank Lucas
Frank Lucas

Reputation: 611

PHP show response of script in ajax call

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;
}

Upvotes: 0

Views: 116

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138557

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!");
                     }           
                 }
            });
        });
    });

Upvotes: 2

Related Questions