DerStrom8
DerStrom8

Reputation: 1341

Returning value to Javascript from PHP called from XMLHttpRequest

I am attempting to add an "Upload Image" feature to my AjaxChat window. The upload to the server works great, but now I need to be able to return the tmp_name/location of the file that was uploaded. In my Javascript I have the following (main) code (some setup code has been omitted because it is unnecessary -- The upload works as expected):

// Set up request
var xhr = new XMLHttpRequest();

// Open connection
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true);

// Set up handler for when request finishes
xhr.onload = function () {
    if (xhr.status === 200) {
        //File(s) uploaded
        uploadButton.innerHTML = 'Upload';
    } else {
        alert('An error occurred!');
    }
};

// Send data
xhr.send(formData);

My PHP code ("upload.php") is as follows:

<?php
$valid_file = true;
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
if($_FILES['photo']['name']) {
    //if no errors...
    if(!$_FILES['photo']['error']) {
        //now is the time to modify the future file name and validate the file
        $new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
        if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB
            $valid_file = false;
            $message = 'Oops!  Your file\'s size is to large.';
            exit("$message");
        }

        //if the file has passed the test
        if($valid_file) {
            //move it to where we want it to be
            move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name);
            $message = 'Congratulations!  Your file was accepted.';
            exit("$message");
        }
    }
    //if there is an error...
    else {
        //set that to be the returned message
        $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['photo']['error'];
        exit("$message");
    }
}
?>

I can tell my PHP code is being run because the image uploads to the server. However, I read that I could generate a Javascript "alert" popup from within the PHP using the following code:

echo '<script type="text/javascript">alert("PHP Code Reached");</script>';

But the above line does not seem to be doing anything. Is this expected since I'm using an XMLHttpRequest, rather than running the PHP directly?

Ultimately my goal is to pass the name of the uploaded file back to the Javascript that called the PHP so that I can create the image url, put it in img tags, and send it to the chat window using ajaxChat.insertText() and ajaxChat.sendMessage(). I'm not sure if this is possible the way I'm running my PHP, though. How would one go about doing this?

Upvotes: 1

Views: 5250

Answers (1)

Barmar
Barmar

Reputation: 782785

When you use XMLHttpRequest, the output of the server script is in the responseText of the object. So you can do:

xhr.onload = function () {
    if (xhr.status === 200) {
        //File(s) uploaded
        uploadButton.innerHTML = xhr.responseText;
    } else {
        alert('An error occurred!');
    }
};

If you want to send back multiple pieces of information, such as an informative message and the name of the file, you can use JSON to encode an associative array, which will become a Javascript object when you parse it.

Upvotes: 2

Related Questions