Solved

how do I use the abort() in ajax?

Posted on 2014-07-25
41
459 Views
Last Modified: 2014-07-31
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';
      }
}
0
Comment
Question by:kadin
  • 22
  • 12
  • 7
41 Comments
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
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
0
 

Author Comment

by:kadin
Comment Utility
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();}
}
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
function abortHandler(event) {
console.log("===","aborterror");
      if (ajax) {ajax.abort();}
}

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

Duncan
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
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

0
 

Author Comment

by:kadin
Comment Utility
No I have never heard of such a thing. Should I do that now and if so how?
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
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
0
 

Author Comment

by:kadin
Comment Utility
I am using firebug. Will that work just the same?

I found browser console, but did not see anything related.
0
 

Author Comment

by:kadin
Comment Utility
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
how you know it did not abort , you see the upload is still in progress Right ?

Duncan
0
 

Author Comment

by:kadin
Comment Utility
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.
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
how you simulate there is error ?

Duncn
0
 

Author Comment

by:kadin
Comment Utility
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.
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
Sorry, I mean how you simulate the abort event ? By clicking abort on the file upload tab ?
ajax.addEventListener('abort', abortHandler, false);

Duncan
0
 

Author Comment

by:kadin
Comment Utility
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.
0
 

Author Comment

by:kadin
Comment Utility
I click an input button  <input name="abort" />
ajax.addEventListener('abort', abortHandler, false); detects this and calls the abortHandler().
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
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
0
 

Author Comment

by:kadin
Comment Utility
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';
}
0
 

Author Comment

by:kadin
Comment Utility
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.
0
 

Author Comment

by:kadin
Comment Utility
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.
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
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

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:kadin
Comment Utility
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();
      }
}

Screen-Shot-001.JPG
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
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
0
 

Author Comment

by:kadin
Comment Utility
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)) {
               }
       }
}
0
 

Author Comment

by:kadin
Comment Utility
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
0
 

Author Comment

by:kadin
Comment Utility
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.
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
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
0
 
LVL 13

Expert Comment

by:duncanb7
Comment Utility
Dear Author

Please advise

Duncan
0
 

Author Comment

by:kadin
Comment Utility
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.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
.abort cancels the network connection
Your server side code should also abort the connection if the connection is interrupted.

Post all your upload functions.
0
 

Author Comment

by:kadin
Comment Utility
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';
      }
?>
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Where did you get this code from?
0
 

Author Comment

by:kadin
Comment Utility
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
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

0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
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/
0
 

Author Comment

by:kadin
Comment Utility
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;
}
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
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.
0
 

Author Comment

by:kadin
Comment Utility
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.
0
 
LVL 58

Accepted Solution

by:
Gary earned 500 total points
Comment Utility
jQuery uses $ symbol the way I have. I don't think that's why the code is not working.
Your code as you posted above does not work at all.

ajax = new XMLHttpRequest();  is all you need unless you need to support IE6 (splutter splutter)

His code does not have any abort mechanism - even though he has an handler for it.

If you want to attach your full code with no changes it might make more sense.
0
 

Author Comment

by:kadin
Comment Utility
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.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
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.
0
 

Author Comment

by:kadin
Comment Utility
No thanks. I am not feeling well today. I cannot continue this discussion further. Thanks again for your help, I do appreciate it.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now