Catch Return Xmlhttprequest send

Asked

Viewed 1,058 times

3

Good afternoon, I am 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 wonder how I get the return of the archive server.php in the upload function?

1 answer

1


You need to add another event receiver for changes in the 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 server results to the client you can use so:

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

and in Javascript

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

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

You can also use in PHP json_encode(array);, but if it is little thing it can be more practical as I put up.

  • In addition to the files I am sending another form fields, I will insert in the database within the file server.php, I would like to return something other than the server response. Can do ?

  • @Matheusilary what do you mean retornar algo sem ser a resposta do servidor? you can explain better?

  • If the insertion is successful I want to return a variable with true value and another with a message for example

  • @Matheusilário ok, you can pass a JSON with json.encode() in PHP and JSON.parse() no JS. If you do not know how to do I can put here an example later.

  • would be grateful if you could post an example

  • 1

    @Matheusilary I put together at the end of the answer. That’s what you wanted right?

  • Okay Sergio, thank you very much! On Monday I take the test! Vlw

  • 1

    Sergio was just that! Thank you very much.

  • @Matheusilary great! See you soon.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.