Return data from webserver with ajax - php

I use this code to upload file with ajax.
$('form').submit(function(e) {
e.preventDefault();
var fd = new FormData(this);
$.ajax({url: $(this).attr('action'),
xhr: function() { // custom xhr (is the best)
var xhr = new XMLHttpRequest();
//load
xhr.upload.addEventListener("load", function(evt) {
$("#msg").text(evt.target.responseText);
}, false);
return xhr;
},
type: 'post',
processData: false,
contentType: false,
data: fd,
success: function(data) {
// do something...
}});
});
I want to display a message in the #msg div when the upload is complete. The message is printed server side using php. Normally evt.target.responseText contains the data from the server, but it contains [object XMLHttpRequestProgressEvent] (which in turn gets written to #msg). I tried printing evt.responseText and evt.response but both also return [object XMLHttpRequestProgressEvent].

Move the line to the "success" callback function block.
An AJAX request call, or its underlying XMLHttpRequestObject (XHR) call is executed asynchronously. The "load" is a Level 3 event that notifies the calling script the progress of the execution. The evt object can be interrogated for use cases such as a file uploader progressbar.
The "success" event is mapped to readyState==4, which is checked by the onreadystatechange callback function.
Using raw XHR:
xhr = new XMLHttpRequest();
xhr.open('GET', your_url, true);
xhr.onreadystatechange=function(){
if (xhr.readyState==4){
document.getElementById('res').innerHTML=xhr.responseText;
} else {
document.getElementById('res').innerHTML='loading...';
}
}
xhr.send(null);
Realistically you can just display the loading text before the XHR call.
Tracking file uploading progress is different:
xhr.upload.onprogress=function(e){
if (e.lengthComputable)
document.getElementById('res').innerHTML=Math.round(e.loaded*100/e.total)+'%';
else document.getElementById('res').innerHTML='uploading...';
};
xhr.onload=function(e){
//display success message
}
Make sure that xhr.upload is not null. If it is, then you don't have Level 3 AJAX support on the browser.

Related

XMLHTTPRequest addEventListener

I'm using a JQuery Ajax call to send mails.
The php side of this call send mail, one at a time, in a loop.
When the loop is finished it returns some data (message, some html..) to the js script.
It works fine.
To improve the comfort of the user while waiting, I plan to use a progress bar. So I modify both the php side and the js side.
On the php side I include a "return" statement of a mail counter, inside the loop.
On the js side I added a 'xhr' parameter to my Ajax call to listen the returned value of the counter.
HERE is my problem : Js Debug return :
xhr ​<exception>: TypeError
​​​​message: "xhr.responseText.addEventListener is not a function"
I can't add a listener to the vale returned par the counter,
The same result by changing 'responseText' to 'response'.
Is it about 'responseText' or 'addEventListener' ?
Did someone can help ?
The complete JS code :
function DiffuseOffre(envoi, tab, paquet, dest) {
//$('#cover-spin').show(0);
var server = '/Admin/Offres/DiffuseOffre.php';
$.ajax({
url: server,
type: 'Post',
dataType: 'json',
data: {
envoi: envoi,
tab: tab,
paquet: paquet,
dest: dest
},
xhr: function() {
$("#xhr-rep").show(0);
var xhr = new window.XMLHttpRequest();
xhr.response.addEventListener("progress", function(evt) {
$("#xhr-rep").text(evt.text);
})
},
success: function(msg) {
//$('#cover-spin').css("display", "none");
$('#xhr-rep').css("display", "none");
if (msg.hasOwnProperty('erreur')) {
$("#dialog-erreur").html(msg.erreur);
$("#dialog-erreur").dialog("open");
$("#dialog-erreur").dialog({
width: '600px',
title: msg.title
})
} else {
$("#dialog-message").html(msg.message);
$("#dialog-message").dialog("open");
$("#dialog-message").dialog({
width: '600px',
title: msg.title
})
if (paquet == 1) {
$("#envoi_" + dest).remove();
$("#diffuser").remove();
}
if (msg.hasOwnProperty('encours')) {
$("#en_cours").html(msg.encours);
}
if (msg.hasOwnProperty('fieldset')) {
$("#" + msg.fieldset).remove();
}
}
}
})
}

issue with uploading image using ajax php

the ajax call for posting an image :
function FileUploadCheck() {
var formData = new FormData();
formData.append('LogoImageUploader', jQuery('#LogoImageUploader')[0].files[0]);
jQuery.ajax({
type: "POST",
url: "FileUploadChecker.php",
contentType: "multipart/form-data",
data: formData,
processData: false,
contentType: false,
success : function(result){
alert(result);
}
});
}
i assume the image is getting posted successfully
at the php script end :
<?php
echo var_dump($_FILES);
?>
All of the above code works fine for me when i make use of jquery 1.7.2 but I can not keep using the jquery as other JS libraries existent in application as incompatible with the jquery 1.7.2 . I need to know if i could only import any standalone JS (maybe which provides ajax functionality) to make this work similar to jquery 1.7.2.
I found an answer to this :
function FileUploadCheck() {
var formData = new FormData();
formData.append('LogoImageUploader', jQuery('#LogoImageUploader')[0].files[0]);
var http = new XMLHttpRequest();
var url = "FileUploadChecker.php";
http.open("POST", url, true);
//when i uncommentated this line, the upload failed, as i tried to manually set the header to the post, but i let XHR to set the header automatically this works.
//http.setRequestHeader("Content-type", "multipart/form-data");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(formData);
}

two ajax functions at the same time? not working

I have a simple AJAX script that suppose to to call a PHP file and get data back.
window.addEvent('domready', function() {
$('dbform').addEvent('submit', function(e) {
new Event(e).stop();
var intervalId =setInterval(function()
{
var Ajax2 = new Request({
url: '/tools/getdata.php',
method: 'post',
data: 'read=true',
onComplete: function(response)
{
$('results').set('html', response);
}
}).send();
},1000);
var postString = 'subbutton=' + $('subbutton').value;
var Ajax = new Request({
url: '/tools/getdata.php',
method: 'post',
data: postString,
onRequest: function()
{
$('message').set('text', 'loading...');
},
onComplete: function(response)
{
$('message').set('text','completed');
clearInterval(intervalId);
},
onFailure: function()
{
$('message').set('text', 'ajax failed');
}
}).send();
});
});
The file that it is submitting too is.
$object= new compare();
if(isset($_POST['subbutton'])=='Run')
{
// This take about 5 minutes to complete
$run=$object->do_compare();
}
if(isset($_POST['read'])=='true')
{
/// in the mean time, the first ajax function is suppose to return data from here..while
// the do_compare() function finish.
// the problem is that it only return it once the do_compare() finish
///
echo 'read==true';
}
the script is working fine, expect, that when the Ajax request check the file every one second, it doesn't return any thing from $_POST['read'], till $run=$object->do_compare(); has finished.
why does it do that? what What I am trying to accomplish is that one Ajax function get data from do_compare function and the other ajax function also independently get that from the getdata.php file.
The problem is in line:
if(isset($_POST['subbutton'])=='Run')
isset returns boolean true or false so if $_POST['subbutton'] is set than it returns true and due to the weak type system of php true == 'Run' because 'Run' evaluates to true. Use
if(isset($_POST['subbutton']) && $_POST['subbutton'] === 'Run')
and
if(isset($_POST['read']) && $_POST['read'] === 'true')
Are you using session in the PHP AJAX handlers? If so, your session file is probably blocked.
Second: Javascript is internally single threaded in the browser (see google for more information).

2 Mootools AJAX function at the same time?

I'm new to Javascript and Mootools and I was wondering if someone can help me learn by solving a problem that I currently have.
index.php has a form, which submit to it self and initiate this code
if($_POST['subbutton']=='Run')
{
$data=$object->do_compare();
}
I would like to know, how can I do a mootool ajax function, that will send the post['run]'
to a php script file ( data.call.php ) where the object reside and have it run.
however, I don't want any respond from data.class.php, as that object writes it's results to a txt file (data.txt)
the 2nd part,
would be an ajax function (that also run at the same time as the first ajax function) and reads a php file, every 5 seconds and bring the data back to index.php
so the squence of operations will be
index.php
form get clicked and start 2 ajax functions.
the first one, only submit the POST['run'] to a php script.
the second function, will go to another php file and get a respond from it every 5 seconds.
I didn't test the below, so use at your own risk. But that's pretty much the gist of it.
_form.addEvent('submit', function(event) {
// your first call
new Request.JSON({
url: "your-first-rpc",
data: {
subbutton: "Run"
},
onSuccess: function(response) {
// handle response here.
}
}).post();
// your second call which runs every 5 secs.
(function() {
new Request.JSON({
url: "your-second-rpc",
data: {
subbutton: "Run"
},
onSuccess: function(response) {
// handle response here.
}
}).post();
}).periodical(5000);
});
<script type="text/javascript">
window.addEvent('domready', function() {
$('dbform').addEvent('submit', function(e)
{
new Event(e).stop();
var intervalId =setInterval(function(){
var Ajax2 = new Request(
{
url: '/tools/getdata.php',
method: 'post',
data: 'read=true',
onComplete: function(response)
{
$('21').set('text', response);
}
}
).send();},1000);
var postString = 'subbutton=' + $('subbutton').value;
var Ajax = new Request({
url: '/tools/getdata.php',
method: 'post',
data: postString,
onRequest: function()
{
$('message').set('text', 'loading...');
},
onComplete: function(response)
{
$('message').set('text','completed');
clearInterval(intervalId);
},
onFailure: function() {
$('message').set('text', 'ajax failed');
}
}).send();
});
});
</script>

Attach progressbar in existing upload button

I have a browse button by which user can browse file upto 100 mb. But the problem is, it is uploading the attch file when user submitting the form. And it is not showing in anywhere that how much file uploaded. I want to show it with a progressbar.
U can visit my site http://historikindia.com/contact_us.php.
Please help me to do it. It is now sending attachment to my email. but i need to show user the progressbar otherwise they may think that it is not responding properly (for large file upload).
Here is the code from ajax uploader which updated a status bar. You need to have an html5 progress bar in your html page for it to work.
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
$('#btnupload').click(function(){
var formData = new FormData(document.getElementById('fileupload'));
$.ajax({
url: 'upload.php', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function (e) { return true; },
success: function (json) { return true; },
error: function (json) { return false; },
// Form data
data: formData,
dataType: "json",
//Options to tell JQuery not to process data or worry about content-type
cache: false,
processData: false
});
});
html5 progress bar looks like this
<progress value="1" max="100"></progress>

Categories