Jarla Jarla - 6 months ago 9
Ajax Question

How can I send a php "echo" via Ajax?

I have an Uploader with progress bar:

index.php
:

<h1>Uploader</h1>
<hr>
<form action="#">
<input type="file" name="image" >
<button class="btn btn-sm btn-info upload" type="submit">Upload</button>
<button type="button" class="btn btn-sm btn-danger cancel">Cancel</button>

<div class="progress progress-striped active">
<div class="progress-bar" style="width:0%"></div>
</div>
</form>


<script>

$(document).on('submit','form',function(e){
e.preventDefault();

$form = $(this);

uploadImage($form);

});

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){
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){
$form.find('.progress-bar').addClass('progress-bar-success').html('upload completed....');
});

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

$form.on('click','.cancel',function(){
request.abort();

$form.find('.progress-bar')
.addClass('progress-bar-danger')
.removeClass('progress-bar-success')
.html('upload aborted...');
});

}

</script>


upload.php
:

<?php

$tmp_file = $_FILES['image']['tmp_name'];
$filename = $_FILES['image']['name'];

move_uploaded_file($tmp_file, 'files/'. $filename);

echo "hello world";

?>


This is working so far very well.
I just cannot see "hello world" on my page. I tried to change this line:

$form.find('.progress-bar').addClass('progress-bar-success').html('upload completed....');
});


into:

$form.find('.progress-bar').addClass('progress-bar-success').html('upload completed....');
alert(data);
});


But still I do not see "hello world"

Answer

It is async. You need to define onreadystatechange to catch the response:

request.onreadystatechange = function () {
  if (request.readyState === 4 && request.status === 200) {
    //here you have your "hello word"
    alert(request.responseText);
  }
}