1

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?

1
  • That echo only works for normal form submission, not AJAX. With AJAX, the script's output is in xhr.responseText, and the xhr.onload function can do with that what it wishes. Commented Aug 10, 2016 at 21:19

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

9 Comments

So let's suppose I want to only return the file name (if upload is successful), I could create a variable in my javascript: var returnedFileName = xhr.responseText; and in my PHP I remove all exit("$message"); calls except for one (in the case of a successful upload): $message = $new_file_name; exit("$message"); Would this work to retrieve the return value from the PHP using the Javascript? I can then check the format of the returned message and make sure it is a valid filename (and not an error message or empty). I just want to make sure I'm understanding correctly.
Yes, you're understanding correctly. Everything echoed by the script will be in xhr.responseText.
Just tested this out and it works beautifully! Thanks very much!
strange, it worked for a little while but now it keeps causing the server to completely crash. I tried uploading an image to the chat from my phone and that's when the problem started, now every time i open the chat (on my phone or on my PC) it doesn't load and my browser hangs. Eventually the page crashes completely
What does it say in the Javascript console when this happens?
|

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.