Hi I have a JQuery Function that is calling a controller when
Controller Response (success()) it is loading an iFrame;
Basically; converter is returning success function after 30 seconds, for that reason I am trying to display a loading image using
beforeSend: function()
{
},
Function I tried a lots but its not working; Could you please give me advice how can I achieve it. My code are given bellow:
var callController = function (FirstName, documentId, fileName, packet) {
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&packet=" + packet,
cache: false,
async: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
event.preventDefault();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
}
});
};
you can show your loader right after or before $.ajax({...}) but you should never use async:false, this is the root of evil, it will freeze the browser while the request has not succeeded.
like this:
var callController = function (FirstName, documentId, fileName, SL) {
//here
showLoader();
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&SL=" + SL,
cache: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
//hide Here
hideLoader();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
//hide Here
hideLoader();
}
});
}
Related
I want to check if a response was successful from an Api and then put it in the iframe.
If I call it twice like this... it works.
function getPDF(fileDirectorGuid) {
if ($('#viewDownloadWindow').is(":visible")) {
$.ajax({
url: $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true',
type: 'GET',
success: function (data) {
if (data == null) {
alert("failed");
}
else {
$('#pdfFrame').attr('src', $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed");
}
});
}
however I don't want to call this twice and this doesn't work out like I thought
function getPDF(fileDirectorGuid) {
if ($('#viewDownloadWindow').is(":visible")) {
$.ajax({
url: $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true',
type: 'GET',
success: function (data) {
if (data == null) {
alert("failed");
}
else {
$('#pdfFrame').attr('src', data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed");
}
});
}
When viewing this in the debugger data looks like this
"%PDF-1.6
1 0 obj
<<
/Length 2 0 R
/Filter /FlateDecode
>>
stream
x��[�%Iv�wO�����H�|��8&`%ِږ8�.���D�J�h ��^of�Z�;wsj�g�<�4��O�X�Nq���c��������l����������7��?����>���S������4��>�y||��z�<J����Gݏ�c�?C����6�����?
so on and so forth.
The src attribute of an iframe is a url, you're setting the actual pdf data. You can use a blob url to achieve your goal
$.ajax({
url: $('#fdApiURL').val() + 'getDocAsPDF' + FIRST_ARGS + '&guid=' + fileDirectorGuid + '&fallbackToNative=true',
type: 'GET',
xhr:function(){
var xhr = new XMLHttpRequest();
xhr.responseType= 'blob'
return xhr;
},
success: function (data) {
if (data == null) {
alert("failed");
}
else {
var url = window.URL.createObjectURL(data);
$('#pdfFrame').attr('src', url);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed");
}
});
I am using the following code to prepend information into my list and it is working fine. On top of that, I want to send the 2 variable below (listDescription and payment) to a url too as follows :
http://mywebsite.com/public/user/spent/?amount=listDescription&account=payment
I am trying to use ajax and send the information over with the following code but it is not working and I get no response alerts either way. Can I get some help on this please. Thanks.
$(document).ready( function() {
var listDescription;
var payment;
//prepending - working fine
$('#add_list').click( function() {
listDescription = $('#list_description').val();
payment = $('#payment').val();
$('.expense_list').prepend('<div>' + "\u00A3 " + listDescription + "\t\t\t" + payment + "\t" + '</div>');
//This is not working
$.ajax({
url: "htttp://mywebsite.com/public/user/spent/",
data: {
amount: listDescription,
account: payment
},
type: "GET",
async:true,
cache:false,
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
$('#list_form')[0].reset();
return false;
});
});
$(document).ready( function() {
//prepending - working fine
var listDescription = $('#list_description').val();
var payment = $('#payment').val();
$('#add_list').click( function() {
$('.expense_list').prepend('<div>' + "\u00A3 " + listDescription + "\t\t\t" + payment + "\t" + '</div>');
//This is not working
$.ajax({
url: "htttp://mywebsite.com/public/user/spent/",
data: {
amount: listDescription,
account: payment
},
type: "GET",
async:true,
cache:false,
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
$('#list_form')[0].reset();
return false;
});
});
This should work :)
May be try to add data type JSON in your AJAX Request?
dataType:'json',
I have jQuery ajax call to get results from the server, and in success, the code should call javascript function which is not in jQuery region code, so I got error in firebug: that the call of function doesnt have reference.
here is my code (see the ajax call in function addGMarker):
function test1234(res) {
PreInfo = res;
popupContentHTML = deviceMoreinfo_callBack_ForGoogle(PreInfo);
var sum = '<p>Please, Select <b>[Sensors Reading List]</b> tab to view vehcile sensors reading, and select <b>[Device Communication Commands]</b> tab to send commands for the device:</p><br/>';
var tabs = [
new MaxContentTab('Sensors Reading List', maxContentDiv),
new MaxContentTab('Device Communication Commands', maxContentDivForCommands)];
this.openMaxContentTabsHtml(map, popupContentHTML, sum, tabs, { maxTitle: "Sensors and Features" });
var iw = map.getTabbedMaxContent();
iw.id = this.id;
GEvent.addListener(iw, 'selecttab', function (tab) {
var node = tab.getContentNode();
switch (tab.getLabel()) {
case 'Sensors Reading List':
maxContentDiv.innerHTML = '<IMG SRC="../../../images/FullModeIcons/LoadingImage.gif" /> Loading...';
//GetSensorsReading(this.id, ClientID, "En", GetSensorsReading_CallBack);
jQuery.ajax({
type: "POST",
url: "../../../DevicesManagerAjax.asmx/GetSensorsReading",
data: "{Device_ID: '" + this.id + "', ClientID: '" + ClientID + "', Page_ID: 'En'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 70000,
success: function (msg) {
var res = msg.d;
GetSensorsReading_CallBack(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
break;
case 'Device Communication Commands':
maxContentDivForCommands.innerHTML = '<IMG SRC="../../../images/FullModeIcons/LoadingImage.gif" /> Loading...';
//GetContorolableSensors(this.id, ClientID, "En", GetContorolableSensors_CallBack);
jQuery.ajax({
type: "POST",
url: "../../../DevicesManagerAjax.asmx/GetContorolableSensors",
data: "{Device_ID: '" + this.id + "', ClientID: '" + ClientID + "', Page_ID: 'En'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 70000,
success: function (msg) {
var res = msg.d;
GetContorolableSensors_CallBack(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
break;
}
});
}
function addGMarker(ID, point, Marker_Icon) {
icon = new GIcon(G_DEFAULT_ICON);
if (_IconClientID == "0") {
if (Marker_Icon == "blue") {
if (ID == FollowVechicleID) {
icon.image = "../../Images/Icons/" + _Follow_Icon;
}
else {
icon.image = "../../Images/Icons/" + _Normal_Icon;
}
if (ID == FollowVechicleID) {
ShowLastThreePositions();
}
}
else {
icon.image = "../../Images/Icons/" + _Speed_Icon;
}
}
else {
if (Marker_Icon == "blue") {
if (ID == FollowVechicleID) {
icon.image = "../../Images/Icons/ClientsIcons/" + _Follow_Icon;
}
else {
icon.image = "../../Images/Icons/ClientsIcons/" + _Normal_Icon;
}
}
else if (Marker_Icon == "red") {
icon.image = "../../Images/Icons/ClientsIcons/" + _Speed_Icon;
}
}
icon.iconSize = new GSize(32, 32);
icon.dragCrossSize = new GSize(0, 0);
icon.shadowSize = new GSize(32, 32);
icon.iconAnchor = new GPoint(5, 5);
marker = new GMarker(point, icon);
marker.id = ID;
GEvent.addListener(marker, 'click',
function() {
popupContentHTML = Device_Option_forGoogle(this.id);
this.openInfoWindowHtml(popupContentHTML);
}
);
GEvent.addListener(marker, 'mouseover',
function() {
//PreInfo = getDeviceInfoForPopUp(this.id, ClientID, "En");
jQuery.ajax({
type: "POST",
url: "../../../DevicesManagerAjax.asmx/getDeviceInfoForPopUp",
data: "{deviceID: '" + this.id + "', IDclient: '" + ClientID + "', Page: 'En'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 70000,
success: function (msg) {
var res = msg.d;
test1234(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
});
var markers = [];
markers.push(marker);
mgr.addMarkers(markers, 0);
mgr.refresh();
ClientPOI.refresh();
POImgr.refresh();
}
It's the same code for calling Javascript function from jQuery. It's working fine. The problem is elsewhere in your code.
This might not be the exact solution, but given not to divert from the solution.
function test1234(res) {
alert(res)
}
function Test() {
jQuery.ajax({
type: "POST",
url: "/TestWebApp/ProcessServlet.do",
success: function (res) {
alert(res);
test1234(res);
},
error: function (xhr, status, errorThrown) {
alert("An error occered, " + errorThrown);
}
});
}
How can i checkstatus of ajax response to wait and check that it has changed from 200 -->500 -->200?
it has to be checked and recheck. Mine isnt working correctly here my code below.
NoTe: On succesfull form submission it will always be 200 .. so it need to check and recheck for 500 and then for 200 before redirecting to the mainpage again.
I tried to create checkstatus function so i can resuse. how can this be done correctly?
// setTimeout(function() { location.reload(true);}, 3000);
function checkStatus() {
/*** Re check bit ***/
var restartCheck = window.setInterval(
$.ajax({
// dataType : 'jsonp',
//jsonp : 'js',
url: "../../../../../rest/configuration",
beforeSend: function (jqXHR, settings) {
console.info('in beforeSend');
console.log(jqXHR, settings);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(" 500 top data still loading " + jqXHR + " : " + textStatus + " : " + errorThrown);
console.info('in error');
console.log(jqXHR, textStatus, errorThrown);
},
complete: function (jqXHR, textStatus) {
alert(" complete " + jqXHR + " : " + textStatus);
console.info('in complete');
console.log(jqXHR, textStatus);
},
success: function (data, textStatus, jqXHR) {
window.clearInterval(restartCheck);
alert(" success " + jqXHR + " : " + textStatus);
console.info('in success');
console.log(data, textStatus, jqXHR);
}
}), 3000); //This will call the ajax function every 3 seconds until the clearInterval function is called in the success callback.
/*** recheck bit **/
}
/**
On initial success form submission the success values is 200.
After that I need to wait sometimes to check and recheck for 500 for server starts, when the Server restarts or is restarting it gives a 500 internal server message, it take about 30 to 40 sec or more to restart the server so i have await time for 30 sec.. Once the server restarts it gives a 200 success server message. and then redirect the page . SO i am trying to checkstatus until it changes from 200 --> 500 -200
**/
$.ajax({
type: "POST",
url: "foo.json",
data: json_data,
contentType: 'application/json',
success: function (data, textStatus, xhr) {
console.log(arguments);
console.log(xhr.status);
alert("Your changes are being submitted: " + textStatus + " : " + xhr.status);
$('#myModal').modal('hide');
$('#myModal-loading').modal('show');
//call function checkstatus not currently workign
//statsu val ==200 server inital form success val from server
setTimeout(function () {
count=0;
var statusval = checkStatus();
while(statusval == 200 and count <=5) {
statusval = checkStatus();
//statsu val has changed to 500 server is restarting
if (statusval==500) {
//wait for 30 sec to recheck if the server has restarted and changed to success ie 200
setTimeout(function () { checkStatus();}, 30000);
}
count++;
}, 3000);
alert("restartCheck " + restartCheck)
setTimeout(function () {
location.reload(true);
}, 3000);
// $('#myModal-loading').modal('hide');
$('<div id="loading">Loading...</div>').insertBefore('#myform');
//location.reload(true);
},
error: function (jqXHR, textStatus, errorThrown) {
// alert("Warning and error has occured: "+errorThrown + " : " + jqXHR.status);
alert(jqXHR.responseText + " - " + errorThrown + " : " + jqXHR.status);
}
});
});
});
Give this fiddle a try.
HTML:
<div></div>
Code:
function waitForStatus(url, status, maxRetries, success, failure) {
var count = 0;
var restartCheck = setInterval(function() {
count++;
if (count <= maxRetries) {
$.ajax({
url: url,
type: "POST",
complete: function (jqXHR, textStatus) {
if (jqXHR.status == status) {
clearInterval(restartCheck);
success(status);
}
}
});
} else {
clearInterval(restartCheck);
failure();
}
}, 3000);
}
var successCallback = function(status) {
$("div").append('<p>SUCCESS: returned ' + status + '</p>');
};
var failureCallback = function() {
$("div").append('<p>FAILURE: max attempts reached</p>');
};
// This will succeed
waitForStatus('/echo/xml', 200, 5, successCallback, failureCallback);
// This will fail
waitForStatus('/echo/xml/404', 200, 5, successCallback, failureCallback);
I have the following jQuery which does not give the most descriptive error messsages...
url: 'server_page.aspx',
type: 'POST',
data: { intID:$(this).attr("id"), strState:"1" },
error: function() { alert('Error'); },
success: function() { }
How do I get more descriptive error messages if it is possible?
EDIT:
This is the full javascript:
$(document).ready(function(){
$("input:checkbox").change(function() {
var that = this;
if($(this).is(":checked")) {
$.ajax({
url: 'favorite_on_off.aspx',
type: 'POST',
data: { strFavoriteID:$(that).attr("id"), strState:"1" },
timeout: 1000,
error: function(xhr, status, error)
{
alert("values: strFavoriteID: " + $(that).attr("id") + " strState: " + "1");
alert('Error: ' + status + '\nError Text: ' + error);
},
success: function() { }
});
} else {
$.ajax({
url: 'favorite_on_off.aspx',
type: 'POST',
data: { strFavoriteID:$(that).attr("id"), strState:"0" },
timeout: 1000,
error: function(xhr, status, error)
{
alert("values: strFavoriteID: " + $(that).attr("id") + " strState: " + "0");
alert('Error: ' + status + '\nError Text: ' + error);
},
success: function() { }
});
}
});
});
These are the error messages:
values: strFavoriteID: c:\folder\document.doc strState: 1
Error: error
Error Text: undefined
You can use all of the arguments passed to the error callback, for example:
error: function(xhr, status, error) {
alert('Error: ' + status + '\nError Text: ' + error);
},
The second argument provided to the error callback is textStatus, which should contain a description of the error:
error: function(xhr, textStatus) { alert(textStatus); }
Note that you should probably not provide this information to your users. Parse the message using Javascript and give them a nice friendly message explaining the error.
I have this method:
function HandleAjaxError(request, status, error) {
var ex = eval("(" + request.responseText + ")");
$('body').addClass("ui-widget-overlay");
alert(ex.Message);
$('body').removeClass("ui-widget-overlay");
}
$.ajax({
type: "POST",
url: window.location.pathname + "/DoStuff",
data: "{}",
success: Success,
error: HandleAjaxError
});
This way, I can gracefully handle the error message (and possibly the status code) on the ASP.NET side. I usually log the original error, then throw a custom/descriptive one for the client.