InvalidStateError - Kendo UI Upload - kendo-ui

I keep getting this weird bug where when I try to set my Authorization header, I keep getting 'InvalidStateError'. Here is my code:
$("#files").kendoUpload({
async: {
saveUrl: myApiUrl + "/" + id,
autoUpload: true
},
upload: function(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function onReady(e) {
if (xhr.readyState === 1 /* OPENED */) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
}
});
}
}
});

It turns out that IE for some reason fires the readystatechange twice for readyState==1. I dont know why but it does. Its the second time that it calls it that make it throw the error. So here is my solution:
After the first time it is called, I just remove the listener.
$("#files").kendoUpload({
async: {
saveUrl: myApiUrl + "/" + id,
autoUpload: true
},
upload: function(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function onReady(e) {
if (xhr.readyState === 1 /* OPENED */) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
xhr.removeEventListener("readystatechange", onReady);
}
});
}
}
});

Related

Ajax is not aborting

How to correctly abort an asynchronous ajax request? Whenever I click the stop button, the ajax is still running. Here is my code below:
My js
linhaenviar.forEach(function(value, index) {
setTimeout(
function() {
var xhr = $.ajax({
url: //url here,
type: 'GET',
async: 'true',
success: function(resultado) {
if (resultado.match("okay")) {
approved(resultado + "");
}
else {
removelinha();
}
$('#loaded').html(total);
}
}
);
$("#toStop").click(function () {
xhr.abort()
});
}, 3000 * index);
}
);

Ext.Msg.show in ajax not append the page

I have a function for saving data. Before saving data there is dialog confirmation Yes or No. While I click option Yes the page behind this is back to the gridview (it's list). What i want is while click Yes the page behind is not change.
This is my function :
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
var str = "<br/><br/><span style='color:red;font-weight:bold'>Success add new PF !</span>";
MsgBox2("Budget Validation", result.Error + str);
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I add new dialog confirmation like this, but it does not work (didn't append the page after click Yes button):
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
$.post(root + "PF/GetSetupName", function (datas) {
if (datas == "FILTER_BRAND") {
Ext.Msg.show({
title: 'Over Budget',
msg: 'Budget is over. Modify or Not ?',
fn: function (btn) {
if (btn == "yes") {
SaveData("none");
}
else {
CancelData();
}
},
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION
});
}
});
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I try also separate this Ext.Msg.show in another function. but it doesn't work. Is there any idea please ?
I've found that when I try to do a mask and an ajax request at the same time, Ext gets overwhelmed and will not properly display the mask.
To fix this, I delay doing my ajax request until Ext & the browser have had enough time to properly display the mask. It generally does not need much time. In the example below, it waits 50 ms before posting.
Ext.get(document.body).mask("Updating data .. Please Wait ...", 'x-mask-loading');
Ext.defer(function() {
Ext.Ajax.request({ ... });
}, 50);
This gives the browser enough time to render the masking before it has to do anything else.

ajaxfileupload problemajaxFileUpload is not a function

I am using ajaxfileupload to upload file , whenever i upload the file it gives me this error . I tried alot to fix it but no luck .
TypeError: $.ajaxFileUpload is not a function
success: function (data, status)
Here is code my code .
$id =$("#id").val();
$.ajaxFileUpload
(
{
type: "POST",
url: "main_page/save_image_data",
secureuri:false,
fileElementId:'userfile'+id,
dataType: 'json',
data: { "image_id":id},
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
/*error: function (data, status, e)
{
alert(e);
}*/
}
)
return false;
There is no command $.ajaxFileUpload in the core of jQuery.
So you are probably trying to use an external library and you have not included it in your <head> .
This can be happened if you have include jquery.min.js inside your page.After remove that file problem will be solved.
add this to your file. this method is removed form upper version of jquery.
jQuery.extend({
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error )
s.error( xhr, status, e );
// If we have some XML response text (e.g. from an AJAX call) then log it in the console
else if(xhr.responseText)
console.log(xhr.responseText);
}
});
this is my solution-----Follow the format of the official:
<script type="text/javascript">
$(document).ready(function() {
var interval;
function applyAjaxFileUpload(element) {
$(element).AjaxFileUpload({
action: "MyJsp.jsp",
onChange: function(filename) {
// Create a span element to notify the user of an upload in progress
var $span = $("<span />")
.attr("class", $(this).attr("id"))
.text("Uploading")
.insertAfter($(this));
$(this).remove();
interval = window.setInterval(function() {
var text = $span.text();
if (text.length < 13) {
$span.text(text + ".");
} else {
$span.text("Uploading");
}
}, 200);
},
onSubmit: function(filename) {
// Return false here to cancel the upload
/*var $fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
$("span." + $(this).attr("id")).replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
return false;*/
// Return key-value pair to be sent along with the file
return true;
},
onComplete: function(filename, response) {
window.clearInterval(interval);
var $span = $("span." + $(this).attr("id")).text(filename + " "),
$fileInput = $("<input />")
.attr({
type: "file",
name: $(this).attr("name"),
id: $(this).attr("id")
});
if (typeof(response.error) === "string") {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
alert(response.error);
return;
}
$("<a />")
.attr("href", "#")
.text("x")
.bind("click", function(e) {
$span.replaceWith($fileInput);
applyAjaxFileUpload($fileInput);
})
.appendTo($span);
}
});
}
applyAjaxFileUpload("#demo1");
});
</script>
at least ,no more this error. And the action will receive the request

BlockUI Ajax loading wrong moment

I know there's other post about this. but there's no answer.
Situation, I have an ajax command. It take time because I have somes things to get.
I want to include a loading between the execution of the ajax.
I want to use jquery BlockUI because its simple and good looking.
But I dont know why the visual effect not working until ajax load the entire data(like when "success" begin).
I try multiple way but not working.
here's my last code :
function from http://www.codeproject.com/Articles/382390/An-Example-to-Use-jQuery-Global-AJAX-Event-Handler
var AjaxGlobalHandler = {
Initiate: function(options) {
$.ajaxSetup({ cache: false });
// Ajax events fire in following order
$(document).ajaxStart(function() {
$.blockUI({
message: options.AjaxWait.AjaxWaitMessage,
css: options.AjaxWait.AjaxWaitMessageCss
});
}).ajaxSend(function(e, xhr, opts) {
}).ajaxError(function(e, xhr, opts) {
if (options.SessionOut.StatusCode == xhr.status) {
document.location.replace(options.SessionOut.RedirectUrl);
return;
}
$.colorbox({ html: options.AjaxErrorMessage });
}).ajaxSuccess(function(e, xhr, opts) {
}).ajaxComplete(function(e, xhr, opts) {
}).ajaxStop(function() {
$.unblockUI();
});
}
};
call ready
var options = {
AjaxWait: {
AjaxWaitMessage: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>',
AjaxWaitMessageCss: { backgroundColor: '#ffffff' }
},
AjaxErrorMessage: "<h6>Erreur!/h6>"
};
AjaxGlobalHandler.Initiate(options);
call execution
$.ajax({
type: "POST",
url: location.href.split('/').pop() + "?action=" + actionName + "&recherche=" + recherche,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
FillDataGridOnSuccess(response, gridId, dataTypeName);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("xhr.status : " + xhr.status);
alert("thrownError : " + thrownError);
}
});
I try also
var ajaxSettings = function(options) {
return $.extend(
{
beforeSubmit: function() {
//beforeSend: function() {
$.blockUI({ overlayCSS: { backgroundColor: '#ffffff' },
message: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>'
});
},
complete: function() {
$.unblockUI();
}
},
options
);
};
Every test that I did end with a loading who seems to only appear on ajaxSuccess.
I know there's sample on official blockUI site http://jquery.malsup.com/block/#demos
and they working there, but I cant on my own. did anybody see why?
tank you

Trying to access Instagram API using jQuery

I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}​

Resources