Get return XMLHttpRequest send

2

Good afternoon, I'm using the following code to upload images:

   function uploadImage($form){
        $form.find('.progress-bar')
            .removeClass('progress-bar-success')
            .removeClass('progress-bar-danger');
    var formdata = new FormData($form[0]); //formelement
    var request = new XMLHttpRequest();

    //progress event...
    request.upload.addEventListener('progress',function(e){
        $('.progress').removeClass('hidden');
        var percent = Math.round(e.loaded/e.total * 100);
        $form.find('.progress-bar').width(percent+'%').html(percent+'%');
    });

    //progress completed load event
    request.addEventListener('load',function(e){
        $('.progress').removeClass('active');
        $form.find('.progress-bar').addClass('progress-bar-success').html('Upload completo');
    });

    request.open('post', 'server.php');
    request.send(formdata);

}

the file server.php contains:

<?php
    foreach ($_FILES as $name => $file) {

        $tmp_file = $file['tmp_name'];
        $filename = $file['name'];

        move_uploaded_file($tmp_file, 'uploads_folder/'. $name.$_POST['categoria_nome'].'.jpg');
    }
    return true;
? >

I would like to know how do I get the return of the server.php file in the upload function?

    
asked by anonymous 15.05.2015 / 20:20

1 answer

1

You have to add another event observer, for changes in ready state .

Example:

request.onreadystatechange = function () {
    if (request.readyState < 4)                             // está à espera de resposta
        console.log('A carregar...');
    else if (request.readyState === 4) {                    // 4 = A resposta do servidor está carregada
        if (request.status == 200 && request.status < 300)  // http status entre 200 e 299 quer dizer sucesso
            alert(request.responseText);                    // ou usa o xhr.responseText de outra maneira
    }
}

or using request.addEventListener('readystatechange ', function(){ // etc...

To pass results from the server to the client you can use this way:

echo '{"done": true, "message": "hello world!"}';

and in JavaScript

var resObject = JSON.parse(request.responseText);

and then you give alert(resObject.message); will give "hello wordl!"

You can also use PHP in json_encode(array); , but if it's a little something can be more practical as I put it on.

    
15.05.2015 / 20:49