ajax request to download an excel file is showing me truncated response - ajax

I am trying to download an Excel file using Ajax (XMLHttpRequest).
On completion the responseText is found to have just 5 characters.
The network sniffing tool (Fiddler) is showing me that my computer received the entire file..
so why is the responseText showing me only 5 characters? I have tried both Synch and Asynch calls.
Thanks for any help you can give here.
var xmlHttpReq = getXmlHttpRequestObject();
function getXmlHttpRequestObject(){
var xmlhttp;
if (window.XMLHttpRequest){// code for all new browsers
xmlhttp=new XMLHttpRequest();
}else if (window.ActiveXObject){// code for IE5 and IE6
// xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
progids = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'Microsoft.XMLHTTP'];
for (i=0 ; i < progids.length; i ++){
try {
xmlhttp = new window.ActiveXObject(progids[i]);
break;
} catch (e) {
//do nothing
}
}
}
return xmlhttp;
}
//utility method for http get
function doSynchronousGet(url){
if(xmlHttpReq == null){
xmlHttpReq = getXmlHttpRequestObject();
}
//change last param to true for making async calls.
xmlHttpReq.open("GET" ,url,false);
xmlHttpReq.setRequestHeader("Connection", "close");
xmlHttpReq.send(null);
return xmlHttpReq.responseText;
}
var resultText = doSynchronousGet(url);
alert('resultText length: '+ resultText.length);
alert('resultText: '+ resultText);

The issue is probably that XMLHttpRequest doesn't ususally take binary data like an Excel file. If you just want to let the user download the file, read Ramiz's post. If you need to read the data in JavaScript, try switching to a text format like CSV (or better for parsing, JSON). If you really need to read a binary file, there are discussions of that here and here.

Do not use Ajax call (xmlhttprequest) to download/upload files. Better do it on server side.

Related

How to fix the ajax request in IE and Firefox?

i'm experiencing problems with testing my web application on firefox and internet explorer, the problem seem to be in the ajax calls made by my application to the server i realized this when i debugged my application using FIDDLER WEB DEBUGGER and i noticed that i don't get any response when im using IE or firefox.
I tried to change my request type from "GET" to "POST" and add a cache buster without any success.
Please peep my CODE:
this is where i create my ajax object:
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject){
try{alert(0);
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xmlHttp = false;
}
}
else{
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("Can't create object!!!");
}
else{
return xmlHttp;
}
}
and this is where i send the request:
function process(){
var params = "word="+word;
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
xmlHttp.open("POST","/gwizz/scripts/definition.php",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length",params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(params);
}else{
setTimeout('process()',1000);
}
}
Any piece of help will be much appreciated.
#Moor
I can't answer exactly what is wrong but here are some pointers that may help you.
XMLHttpRequest - Perhaps this is a bit of topic but think its useful for more browser independent code.
I suggest using to create Ajax request and use ActiveXObject only in case you can't find XMLHttpRequest. Most browsers including IE8+ support this object so you have less code dependent on browsers. e.g. below copied from http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Use Developer tools Firefox and IE modern versions come with very useful developer tools. Check the network sections and then perform clicks on your web application that are expected to invoke the ajax call. The full details of the http request actually fired are available in the network section. It will show you how the browser sees the request.
use console.log This question talks about some logging support which is available in IE. The same is also available in firefox. You should be able to pin point where your code execution fails. Does IE9 support console.log, and is it a real function?
If I were to take a guess, I would say the URL that is used to connect to the server may be resulting in 404.

Ajax Broken in Browsers works in Android

I can run this code in Android app (using PhoneGap adn jQuery Mobile) but not on desktop browsers.
It gives me a syntax error in firebug for this line =
var TicketList = eval("(" + ajax.responseText + ")");
Here is the code
// JScript source code
// ran on body load
function doJsStuff()
{
var ajax = AJAX();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
var TicketList = eval("(" + ajax.responseText + ")");
if (TicketList.ListCount > 0) {
document.getElementById("opencount").innerHTML = TicketList.ListCount +" Open Tickets";
for (Ticket in TicketList.Tickets) {
// add stuff to DOM
//AddTicketToList(TicketList.Tickets[Ticket]);
}
}
else {
document.getElementById("opencount").innerHTML = "All Tickets Reviewed";
DisplayNoresults();
}
}
}
ajax.open("GET", "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open", true);
ajax.send(null);
//document.addEventListener("deviceready", onDeviceReady, false);
//event to check for PhoneGap
//$('ul').listview('refresh');
$('#mtickets').page();
//showVars();
}
function AJAX()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
}
return xmlHttp;
}
**TicketList is a variable in the JSon that comes across like this=
{"Tickets" : [{"TicketID": "1054","Category": "N/A","SubmittedUserID": "bob.thebuilder","ShortDescription": "test question QID:16668","CreationDate": "2/16/2011 12:24:19 PM","TicketStatus": "Open","LongDescription": "Something is wrong with this question I know I hve the right answer but it keeps telling me I'm wrong"},{"TicketID": "1053","Category": "Mission Support","SubmittedUserID": "dave","ShortDescription": "Make courseware revisions","CreationDate": "2/16/2011 9:34:48 AM","TicketStatus": "Open","LongDescription": "Find help tickets generated by users for possible courseware update."}], "PageCount": "6", "ListCount": "11"}
Note about PhoneGap If you are trying to include phoengap functions in a place where the code may also be executed on in a browser make sure you only add the phone gap function with on "deviceready" or your browser will not render. Example:
function onload(){
//event to check for PhoneGap
document.addEventListener("deviceready", onDeviceReady, true);
}
...
function onDeviceReady()
{
// Now PhoneGap API ready
vibrate(90); // vib to ack pg ready
$("a").click(function(event){
vibrate(30); // add 30 sec vib to all links
});
}
My immediate response would be to use jQuery's getJSON method, since you're aready using jQuery. jQuery's AJAX provides a much broader base of browser compatibility. Also, every time you use eval(), a small baby somewhere cries.
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(TicketList){
if (TicketList.ListCount > 0) {
$("#opencount").html(TicketList.ListCount +" Open Tickets");
for (Ticket in TicketList.Tickets) {
...
}
} else {
$("#opencount").html("All Tickets Reviewed");
DisplayNoresults();
}
});
If this still doesn't work for you, ensure that the JSON being returned is valid. But please stick to this method, and don't use eval!!
SIMPLIFIED UPDATE
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
UPDATE USING 'DATA'
If your url becomes too long, you might begin to encounter problems. It is suggested to pass the url data via the data argument.
var url = "http://website.com/ListTicketsRequest.ashx";
var data = "PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url, data, function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
Looking at your code, it seems likely to me that the syntax error isn't in the code you posted, but instead is contained in the JSON object you're evaluating in ajax.responseText. Take a look at the data being returned by the AJAX request. Is it valid Javascript? Does the page you're calling return something different to desktop browsers vs mobile? Is there an error message where the JSON code should be?
Another possibility: Is your app running on website.com? If not, Firefox is probably blocking the XMLHttpRequest from functioning properly. Firefox 3 and below block cross-site AJAX requests. Firefox 3.5 seems to allow some exceptions.

In IE, I can only send request to server 7 times maximum when using ajax

I added ajax to a web application with 7 'select' tags, in which selecting an option would populate the following 'select' tags with the related information. And some of these tags can also show another set of radio buttons or checkboxes. In all, you can make more than 10 requests to the server until you get your desired product.
All work fine in major browsers except in IE, where the request to the server are limited to 7 times and then nothing happens any more until you refresh the browser to start again. I even tried to disable the cache, but still the same problem occured...
Why is IE doing this nonsense?
This is the ajax code doing the server-client talking:
function updateAvailableAttributes()
{
var xmlhttp;
var form = document.forms["orderDefinition"];
form.elements["formChangeRequest"].value = "true";
var processingMsgBox = $("#waitingMsgOverlay, #waitingMsgBox, #waitingMsg, #waitingMsgParag");
var map = document.getElementById("OrderMap");
if(window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6 and below
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
switch(xmlhttp.readyState)
{
case 1:
map.disableApplication();
processingMsgBox.show();
break;
case 4:
if(xmlhttp.status == 200)
{
$('#usercontent .sleeve .toprow').html(xmlhttp.responseText);
applyValidation();
browserScrollManagement();
$("#toolpanel").height($("#orderMap").height());
inputBtnHighlightSelection();
}
else
{
sessionTimedOut();
}
$("#toolpanel").height($("#orderMap").height());
map.enableApplication();
processingMsgBox.hide();
break;
}
}
var parameters = $("form#orderDefinition").serialize();
xmlhttp.open("POST", "ajax/possibleValues.html", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Cache-Control", "no-cache");
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}
The HTTP spec recommends that simultaneous connections to a web server must be limited. The limit is lower for IE7 than it is for other browsers. Modify the registry to increase it for testing purposes only.

Receiving AJAX HTTP Response Code as 0

I have a pretty simple AJAX and PHP code. While calling the PHP through the AJAX it receives the response code as 0. The PHP code is successfully run, but I can't get the response. What does this status '0' denote and how can I solve this?
function confirmUser(id)
{
xmlhttp=GetXmlHttpObject();
regid = id;
if (xmlhttp==null) {
alert ("Browser does not support HTTP Request");
return;
}
var url="confirm.php";
url=url+"?id="+id;
url=url+"&a=confirm";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#txtHint" + regid).text("Awaiting confirmation");
} else {
alert (xmlhttp.status); //this shows '0'
}
};
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
Well, this is the javascript I used. Pardon me if I should've added anything more than this. Also tell me what I missed.
I appreciate your help
GetXmlHttpObject function:
function GetXmlHttpObject()
{
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject) {
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
When working with XMLHttpRequests in the past, I've found that status 0 is usually returned for locally processed files. When I saw this question, I had a bit of a hunt around and found a confirmation of this at the following pages:
XMLHttpRequest - Why Status 0, and StatusText Unknown occur
https://developer.mozilla.org/En/Using_XMLHttpRequest#section_3
Here are the readyState codes for you.
0. Uninitialized
1. Set up, but not sent
2. Sent
3. In flight
4. Complete
(Source: http://www.stevefenton.co.uk/Content/Blog/Date/201004/Blog/AJAX-Ready-State-Codes/)
Do you get stuck constantly on a readyState of 0? If so, it means your request hasn't been sent, although I can see a line of code in your example "xmlhttp.send(null)"...
I would predict that you'll get a 0 before you call send, but after that a different status code. What happens if you wait a bit?
I know people may not want to hear it, but this is exactly what JS frameworks are for. Why mess with all of the various browser inclinations and disasters that are custom AJAX calls when you can just do a simple AJAX call through jQuery.
Basically, you are reinventing the wheel, and for no reason. Have your php return JSON data, and embed a variable in with the success code if you need to test for that.
<script src="jquery.js"></script>
<script>
$.get("myphp.php", { id : "yes", blah : "stuff" }, function(data) {
if (data.success == 1) {
alert("got data");
} else {
alert("didn't get data");
}
},"json");
</script>
Boom, you now have cross-browser AJAX.
This can happen if you're requesting an HTTPS resource and the handshake fails (for example an invalid certificate). In particular, if you're using the XML request object from outside a browser, the error may not be obvious.

How to execute a page ,that contains JS ,in AJAX ,using innerHTML?

I send GET data with AJAX to another file.And on the another file I have echo "<script>alert('Something');</script>";.This is displayed dynamicly with AJAX ,i.e
var ajaxDisplay = document.getElementById('edit');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
puts the <script>alert('Something');</script> to div with name edit.
But it doesn't alert anything.
How to get it work?
I have mixed html/javascript.
Here is the code.
function ajaxFunctions(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('edit');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var namef = document.getElementById('nameed').value;
var queryString = "?namef=" + namef;
ajaxRequest.open("GET", "try.php" + queryString, true);
ajaxRequest.send(null);
}
Maybe to find the script tags and to eval them?
But how to find the script tags?
Instead of trying to inject a script element in the DOM, just have your script return:
alert('Something');
And then use eval(response); to run it. Or you could add a script element with the src attribute pointing to the page that returns your JavaScript into the <head> (which is the preferred method).
function loadScript(url) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
}
Keep in mind that this wont work for cross-domain requests--the script has to have the same origin as the page running your code. To get around this, you'll have to use a callback.
It looks like the only purpose of setting innerHTML is an attempt to get the JS to execute. But once the page is loaded, JS won't 'know' that it needs to parse and execute the new text you've changed, so your method won't work. In this case, what you want is a callback function:
http://api.jquery.com/jQuery.ajax/
I haven't used jQuery, but it looks like you'd simply add a 'complete' property to the settings object you pass to the .ajax() call, like so:
$.ajax({
// ......
complete: function(){
alert('Something');
}
// ......
});
In this case, the callback function would execute once the ajax call has completed. You can pick other events, such as on success, on failure, and so on, if you need to attach your code to a different event.
But how to find the script tags?
Well, parent.getElementsByTagName('script') and then evaling the data of the text node inside will do it.
However, inserting content that includes script tags is unreliable and works slightly differently across browsers. eg. IE will execute the script the first time the script node is inserted into any parent, inside the document or not, whilst Firefox will execute script the first time a subtree including the script is added to a node inside the document. So if you're not extremely careful, you can end up executing scripts twice on some browsers, or executing the script at the wrong time, following a further page manipulation.
So don't. Return script that you want to execute separately to any HTML content, eg. using a JSON object containing both the HTML and the JavaScript seperately.

Resources