Link to home
Start Free TrialLog in
Avatar of kadin
kadinFlag for United States of America

asked on

how do I use the abort() in ajax?

I am trying to abort the file upload, but I think I am doing it wrong. I keep an error such as this one - ReferenceError: formdata is not defined

I have tried:
ajax.abort();
ajax.upload.abort();

I put the abortHandler function inside videoUploadFile function because it needs the ajax object.

function videoUploadFile() {
      var ajax = getXMLHttpRequestObject();

      if (ajax) {
                  $('v-upload-file-form').onsubmit      =      function() {
                        var file = $('input-browse-button').files[0];
                        var formdata = new FormData();
                        formdata.append('file', file);
                        ajax.upload.addEventListener('progress', progressHandler, false);
                        ajax.addEventListener('load', completeHandler, false);
                        ajax.addEventListener('error', errorHandler, false);
                        ajax.addEventListener('abort', abortHandler, false);
                        ajax.open('post', '/upload_file.php', true);
                        ajax.send(formdata);
                        return false;
                  }

      function abortHandler(event) {
            ajax.send(formdata).abort();
            window.location.href='/another_page';
      }
}
Avatar of duncanb7
duncanb7

Could you send us complete or portion code ? We don't see
where or  location you are putting the ajax.abort()

Did you include it within if  statement


if (ajax) {
ajax.abort();
}

Duncan
Avatar of kadin

ASKER

Thanks for your response.
It is inside this function. I don't know if that causes a out of scope problem. I removed the var key word from -  var ajax = getXMLHttpRequestObject(); but the upload still won't stop.

function abortHandler(event) {
      if (ajax) {ajax.abort();}
}
function abortHandler(event) {
console.log("===","aborterror");
      if (ajax) {ajax.abort();}
}

Did you check any console.log output at developer's console

Duncan
What is this, why you need this ?
ajax.send(formdata).abort();

try this at this as follows

function videoUploadFile() {
      var ajax = getXMLHttpRequestObject();

      if (ajax) {
                  $('v-upload-file-form').onsubmit      =      function() {
                        var file = $('input-browse-button').files[0];
                        var formdata = new FormData();
                        formdata.append('file', file);
                        ajax.upload.addEventListener('progress', progressHandler, false);
                        ajax.addEventListener('load', completeHandler, false);
                        ajax.addEventListener('error', errorHandler, false);
                        ajax.addEventListener('abort', abortHandler, false);
                        ajax.open('post', '/upload_file.php', true);
                        ajax.send(formdata);
                        return false;
                  }

      function abortHandler(event) {
console.log("===","aborterror");
            if (ajax) {ajax.abort();}
            window.location.href='/another_page';
      }
}
}

Open in new window

Avatar of kadin

ASKER

No I have never heard of such a thing. Should I do that now and if so how?
Yes, on click broswer option->developer tools->console, you will see all
javascript error if you have for assisting you debugging

console.log() will echo out the message on console window

Duncan
Avatar of kadin

ASKER

I am using firebug. Will that work just the same?

I found browser console, but did not see anything related.
how you know it did not abort , you see the upload is still in progress Right ?

Duncan
Avatar of kadin

ASKER

The upload starts over and completes. Even if I click abort twice, it completes. I check the server and the video is completely uploaded. If I redirect to another page my browser continues running like it is busy until the file is uploaded.
how you simulate there is error ?

Duncn
Avatar of kadin

ASKER

I use firebug to alert me of javascript errors. I don't know how to simulate an ajax error. In php I can check file type etc. and echo back an error message.
Sorry, I mean how you simulate the abort event ? By clicking abort on the file upload tab ?
ajax.addEventListener('abort', abortHandler, false);

Duncan
Avatar of kadin

ASKER

I don't know how the abort function works exactly. I don't think I have to do anything differently in PHP with the abort function in mind.

abort() only temporarily stops the upload and then it immediately starts the upload from the beginning again.
Avatar of kadin

ASKER

I click an input button  <input name="abort" />
ajax.addEventListener('abort', abortHandler, false); detects this and calls the abortHandler().
If abort event triggered means abort , why you still need  ajax.abort() ?
Take a look at this video, the code is similar to yours
http://www.developphp.com/view.php?tid=1351

Duncan
Avatar of kadin

ASKER

I saw that video yesterday, that was how I made my code. I removed abort() so now it just redirects, but still the file continues to upload completely.

function abortHandler(event) {
      window.location.href='/redirect';
}
Avatar of kadin

ASKER

I have a progress bar and kb readout of the upload and when it gets over 50% I click abort and it momentarily stops goes back to 13% and continues uploading from there and completes.
Avatar of kadin

ASKER

A new development: http://msdn.microsoft.com/en-us/library/ms535920%28VS.85%29.aspx
I think I am missing onreadystatechange propety.

ajax.addEventListener('abort', abortHandler, false);
ajax.onreadystatechange = function() {
      handleResponseVideoUpload(ajax);
}

function abortHandler(event) {
      cancel = 'yes';
}

function handleResponseVideoUpload(ajax) {
      if (ajax.readyState == 4) {
            if ((ajax.status == 200) || (ajax.status == 304)) {
            
                  if (cancel == 'yes') {
                        if (ajax) {ajax.abort();}
                  }
            }
      }
}

I tried the above but it did not work. I think I am missing something.
I thought, your code is already included with onreadystatechange
What browser are using and its version ?
Take a look for older IE  version ajax if need
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first

Missing .upload ,Each XMLHttpRequest object has a unique, associated XMLHttpRequestUpload object at XMLHTTPRequest reference guide at http://www.w3.org/TR/XMLHttpRequest/
Try this
========================================================
 
ajax.upload.addEventListener('load', completeHandler, false);
 ajax.upload.addEventListener('error', errorHandler, false);
 ajax.upload.addEventListener('abort', abortHandler, false);
function abortHandler(event) {
console.log("===","aborterror");
            if (ajax ) {ajax.abort();}
            window.location.href='/another_page';
      }

Open in new window

Avatar of kadin

ASKER

firefox 31.0 I get same result in IE 11.0

With this code I get no response; the upload completes with no error in fire bug.

function videoUploadFile() {
       ajax = getXMLHttpRequestObject();

      if (ajax) {
            if      ($('v-video-upload-container'))      {
                  $('v-upload-file-form').onsubmit      =      function() {
                        var file = $('input-browse-button').files[0];
                        var formdata = new FormData();
                        formdata.append('file', file);
                        ajax.upload.addEventListener('progress', progressHandler, false);
                        ajax.upload.addEventListener('load', completeHandler, false);
                        ajax.upload.addEventListener('error', errorHandler, false);
                        ajax.upload.addEventListener('abort', abortHandler, false);
                        ajax.open('post', '/v_upload_file.php', true);
                        ajax.send(formdata);
                        return false;
                  }
            }
        }
}

function abortHandler(event) {
        console.log("===","aborterror");
      if (ajax) {
            ajax.abort();
      }
}

User generated image
it might be becaue of no errror, So, now going to how you can trigger the error ?

Could you trigger error  when upload file  and during uploading, disconnect the internet connection ?

Duncan
Avatar of kadin

ASKER

My internet modem was just upgraded a couple of months ago. It has no on off switch that I can find. I don't want to pull the plug because I am concerned it might mess something up or not work at all.

I might add I don't have this in my code. But I think abort() function sets readyState = 0;

ajax.onreadystatechange = function() {
      handleResponseVideoUpload(ajax);
}

function handleResponseVideoUpload(ajax) {
      if (ajax.readyState == 4) {
            if ((ajax.status == 200) || (ajax.status == 304)) {
               }
       }
}
Avatar of kadin

ASKER

I discovered info on this page:
http://stackoverflow.com/questions/446594/abort-ajax-requests-using-jquery

Save the calls you make in an array, then call xhr.abort() on each.
HUGE CAVEAT: You can abort a request, but that's only the client side. The server side could still be processing the request. If you are using something like PHP or ASP with session data, the session data is locked until the ajax has finished. So, to allow the user to continue browsing the website, you have to call session_write_close(). This saves the session and unlocks it so that other pages waiting to continue will proceed. Without this, several pages can be waiting for the lock to be removed.

Of note, if the server has already received the request, it may continue processing the request (depending on the platform of the server) even though the browser is no longer listening for a response. There is no reliable way to make the web server stop in its tracks with processing a request that is in progress
Avatar of kadin

ASKER

I've requested that this question be deleted for the following reason:

First of all, Thanks Duncan for all the time and effort you spent for helping me trouble shoot this.

I think there is no AJAX solution. AJAX has its limitations. Additional technology is needed to interact with the server after the PHP page started processing. Action-script is the only technology I know of that can abort an upload completely (that is, completely stop the server from uploading the file and free the browser from processing so the user can redirect to another page). Maybe Java or APC can accomplish this.
Dear Author,
As you said, we have spent a lot of effort so that we should continue this thread , Right ? You could click "request  attention" to ask other experts to assist on it.

Duncan
Dear Author

Please advise

Duncan
Avatar of kadin

ASKER

From the research I have done it looks as though this is something AJAX cannot do, so I thought I would go back to my actionscript solution. I will check back a few times each day to see if someone knows differently.

Thanks again for your help Duncan.
Avatar of Gary
.abort cancels the network connection
Your server side code should also abort the connection if the connection is interrupted.

Post all your upload functions.
Avatar of kadin

ASKER

I am reluctant to use AJAX because I read at another site, abort() may be unreliable. Maybe it works on some servers but not others. I wish I knew what youtube uses.
A few comments up I copied and pasted from another site a link and this -  HUGE CAVEAT: ...

function videoUploadFile() {
       ajax = getXMLHttpRequestObject();

      if (ajax) {
                  $('v-upload-file-form').onsubmit      =      function() {
                        var file = $('input-browser-btn').files[0];
                        var formdata = new FormData();
                        formdata.append('file', file);
                        ajax.upload.addEventListener('progress', progressHandler, false);
                        ajax.upload.addEventListener('load', completeHandler, false);
                        ajax.upload.addEventListener('error', errorHandler, false);
                        ajax.upload.addEventListener('abort', abortHandler, false);
                        ajax.open('post', '/v_upload_file.php', true);
                        ajax.send(formdata);
                        return false;
                  }
      }
}

function abortHandler(event) {
      //handleResponseVideoUpload(ajax);
      if (ajax) {
            ajax.abort();
      }
}

function progressHandler(event) {
      var loadedKb = Math.round(event.loaded/1024);
      var totalKb = Math.round(event.total/1024);
      $('v-byte-readout').innerHTML = 'Uploaded' + loadedKb + ' kb of ' + totalKb + ' kb';
      var percent = (event.loaded / event.total) * 100;
      $('v-progressbar').style.height = '10px';
      $('v-progressbar').style.width = Math.round(percent) * 2 + 'px';
      $('v-percent').innerHTML = Math.round(percent) + '% uploaded... please wait';
}

function completeHandler(event) {
      $('v-percent').innerHTML = event.target.responseText;
      $('v-progressbar').style.height = '0px';
      $('v-progressbar').style.width = '0px';
}

function errorHandler(event) {
      $('info-container').innerHTML = 'error';
}

<form id="v-upload-file-form" method="post" enctype="multipart/form-data">
      <input id="input-browser-btn" name="file" type="file" size="35"/>
      
      <div id="v-progressbar"></div>
      <h3 id="v-percent"></h3>
      <p id="v-byte-readout"></p>

      <input name="abort" type="button"/>
      <input name="submit" type="button"/>
</form>

<?php v_upload_file.php
$success = '';

$filename = $_FILES['file']['name'];
$fileTmpLoc = $_FILES['file']['tmp_name'];
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$fileErroeMsg = $_FILES['file']['error'];

$directory = the directory . $filename;
$success = move_uploaded_file($fileTmpLoc, $directory);

if ($success) {
      echo 'success';
} else {
            echo 'try again';
      }
?>
Where did you get this code from?
Ok, what you have makes no sense in comparison to the link
Where are you getting $ from - that is usually used with a javascript library.

I think it's time to go back to basics.
Here's the original link code amended for an abort, which works as it should when you click abort.
The file_upload_parser.php file is the same

<!DOCTYPE html>
<html>
<head>
<script>
/* Script written by Adam Khoury @ DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
var ajax

function _(el){
	return document.getElementById(el);
}
function uploadFile(){
	var file = _("file1").files[0];
	//alert(file.name+" | "+file.size+" | "+file.type);
	var formdata = new FormData();
	formdata.append("file1", file);
	ajax = new XMLHttpRequest();
	ajax.upload.addEventListener("progress", progressHandler, false);
	ajax.addEventListener("load", completeHandler, false);
	ajax.addEventListener("error", errorHandler, false);
	ajax.addEventListener("abort", abortHandler, false);
	ajax.open("POST", "file_upload_parser.php");
	ajax.send(formdata);
}
function progressHandler(event){
	_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
	var percent = (event.loaded / event.total) * 100;
	_("progressBar").value = Math.round(percent);
	_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
	_("status").innerHTML = event.target.responseText;
	_("progressBar").value = 0;
}
function errorHandler(event){
	_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
ajax.abort()
	_("status").innerHTML = "Upload Aborted";
}
</script>
</head>
<body>
<h2>HTML5 File Upload Progress Bar Tutorial</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="file1" id="file1"><br>
  <input type="button" value="Upload File" onclick="uploadFile()">
<input type="button" value="Abort" onclick="abortHandler()">
  <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
  <h3 id="status"></h3>
  <p id="loaded_n_total"></p>
</form>
</body>
</html>

Open in new window

I'm also going to suggest a jQuery option to you that will handle all this for you while giving a very nice GUI

http://blueimp.github.io/jQuery-File-Upload/
Avatar of kadin

ASKER

I tested his code on my server and it works. I wish I knew why exactly it works. The only notable difference I see is a call to a function. I call ajax = getXMLHttpRequestObject(); for my code instead of his ajax = new XMLHttpRequest();.

His code works without that function being defined. I assumed his function was another name for the same function definition below.

function $(id) {return document.getElementById(id);}

function getXMLHttpRequestObject() {
      var ajax = false;
      if (window.XMLHttpRequest) {
            ajax = new XMLHttpRequest();
      }      else if (window.ActiveXObject) {
                  try {
                        ajax = new ActiveXObject("Msxml2.XMLHTTP");
                  }      catch      (e)      {
                              try      {
                                    ajax = new      ActiveXObject("Microsoft.XMLHTTP");
                              }      catch      (e)      {}
                        }
            }
      return      ajax;
}
ajax = new XMLHttpRequest();.
This works in all modern browser even IE7+

I worked out what you were doing with $
He uses _ as a function name and uses it throughout his code - you cannot just replace it with $

Did you look at the jQuery link I gave.
Avatar of kadin

ASKER

Yes I looked at the link.

jQuery uses $ symbol the way I have. I don't think that's why the code is not working.

I see where this ajax = new XMLHttpRequest(); is coming from. It is in my function definition.

His code uses onclick="abortHandler(). I use just addEventListeners and a seperate js file. I don't use any onclicks because a book I read recommended not to.
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kadin

ASKER

My code worked fine, I could select and upload a file. I just could not abort.

I don't have any more time to work this today. You got me far enough I can do some experiments and narrow down the exact difference in code and why mine did not work. Thanks for your help.
As I said what you posted above doesn't work
If you want to post your whole code I'll go through it.
But the example code I posted above based on your link does work as it should.
Avatar of kadin

ASKER

No thanks. I am not feeling well today. I cannot continue this discussion further. Thanks again for your help, I do appreciate it.