Issue with invokeasync in blazor - javascript

Actually I had called the script function from c# but without complete script function invokeasync return value but i need return value After complete js function excution
function ajax() {
    var isbool = false;
    let xhr = new XMLHttpRequest();     xhr.onload = function () {
        if (xhr.status == 200 && xhr.status < 300) {
            isbool = true;
        }
    }
    xhr.open('GET', "https://jsonplaceholder.typicode.com/posts", true);
    xhr.send();    
return isbool;
 }
I had called this function from c#
var isonline = await JSRuntime.InvokeAsync("ajax");
Isonline return false because invokeAsync return false before complete the Onload event.
I need return value after complete js function
please help me.
Thanks

Related

Undefined returned from file existence check

I'm checking if a file at a certain local URL exists via a XMLHttpRequest, kind of a workaround peek at the filesystem. Using the pingFile function described below, I try to see if I get a 200 or 404 for a given file and perform some actions depending on that result.
function pingFile(theURL, callback)
{
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (this.readyState === this.DONE) {
if (callback !== null) {
return callback(this.status);
} else {
return this.status;
}
}
};
req.open("HEAD", theURL);
req.send();
}
var q = pingFile('images/image1.png', null);
However, when I check the value of q, it is always undefined. I'm missing something about the asynchronous nature of an XHR here, I think, but I haven't been able to find where to wait so that this.status has either of the values I would expect from a file check.
EDIT: I've tried adding return 4; after req.send(); and that always gives q the value 4 regardless of whether the file is there.
How do I get the status value of a XMLHttpRequest back from the function it's in?
For async operations you could use callbacks or promises. Here is a simple example with callbacks:
(function () {
function pingFile(theURL, success, error) {
var req = new XMLHttpRequest();
req.onload = function (e) {
if (this.status === 200) {
success(e);
} else {
error(e);
}
};
req.open("HEAD", theURL);
req.send();
}
function fileExist(e) {
alert('File exist!');
}
function fileNotExist(e) {
alert('File does not exist!');
}
pingFile('images/image1.png', fileExist, fileNotExist);
}());

Ajax Class error with accessing class variable in onreadystatechange function

I am currently writing a JavaScript Ajax class and have encountered an error. In the function processRawData() I can't seem to access the class variable xhr by using this.xhr. I get "cannot read property of readyState of undefined. I have currently fixed this problem by passing in the xhr value when setting the reference to the onreadystatechange function however that seems unneeded as I should be able to access the xhr value without doing so.
function Ajax()
{
this.xhr = this.createXmlHttpRequest();
}
Ajax.prototype.createXmlHttpRequest = function()
{
if (window.XMLHttpRequest) {
try {
return new XMLHttpRequest();
} catch (e) {
throw new Error("Couldn't create XmlHttpRequest : " + e);
}
} else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
throw new Error("Couldn't create XmlHttpRequest : " + e);
}
}
}
Ajax.prototype.request = function(type, url, params, dataType, callback)
{
if (this.xhr.readyState === 0 || this.xhr.readyState === 4) {
var isGetWithParams = (type === "GET") ? ((params !== null) ? url + params : url) : url
this.xhr.open(type, isGetWithParams, true);
this.xhr.onreadystatechange = this.processRawData(dataType, callback);
var passInParams = (type === "GET") ? null : ((params !== null) ? params : null);
this.xhr.send(passInParams);
}
}
Ajax.prototype.processRawData = function(dataType, callback)
{
return function()
{
if (this.xhr.readyState === 4 && this.xhr.status === 200) {
switch (dataType) {
case "text":
var data = this.xhr.responseText;
break;
case "xml":
default:
var data = this.xhr.responseXML;
}
callback(data);
}
}
}
Looks like your problem might be because in processRawData() you are returning another function and referencing this.xhr.readyState, but 'this' now references the returning function and not the Ajax class. Try:
Ajax.prototype.processRawData = function(dataType, callback){
var that = this; //'that' references the current Ajax instance
return function()
{
if (that.xhr.readyState === 4 && that.xhr.status === 200) {...

innerHTML showing the function, not the return value of the function

Trying to DRY up some old javascript I wrote.
test()
function test() {
var output = function() {
return ajaxPost("test.php", "testvar=bananas");
}
document.getElementById("main").innerHTML = output;
}
ajaxPost()
function ajaxPost(file,stuff) {
var xmlhttp;
var actionFile = file;
var ajaxVars = stuff;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
return xmlhttp.responseText;
} else {
// Waiting...
}
}
xmlhttp.open("POST", actionFile, true);
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(ajaxVars);
}
The output that I am receiveing is this:
<div id="main">
function () { return ajaxPost("test.php", "testvar=bananas"); }
</div>
I can't figure out why it's sticking the function in the div instead of what the function is supposed to actually do. Any thoughts?
You have to execute the function by adding () to it, else you receive the function body!
function test() {
var output = function() {
return ajaxPost("test.php", "testvar=bananas");
}
document.getElementById("main").innerHTML = output();
}
Furthermore you try to return a value from the AJAX call here
return xmlhttp.responseText;
This wont work as in an asynchronous call there is nothing that catches the returned value!
You should call some kind of callback, which uses the returned value.
EDIT
This would be a callback approach similar to your code:
function test( data ) {
document.getElementById("main").innerHTML = data;
}
function ajaxPost(file,stuff,cb) {
// ...
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb( xmlhttp.responseText );
} else {
// Waiting...
}
}
// ...
}
// make the actual call
ajaxPost("test.php", "testvar=bananas", test);

XMLHttpRequest not adding header - "X-Requested-With: XMLHttpRequest"

I have an ajax call where I used jQuery.ajax() to make a request to an mvc action. This all worked fine. However due to some forms having a file control I changed it from using jQuery.ajax() to using the XMLHttpRequest to send it using the HTML5 File API.
Since making this change the MVC action method no longer see's it as an ajax request. Using Fiddler2 I have noticed that it no longer adds the "X-Requested-With: XMLHttpRequest" to the request and I assume this is the problem.
The form I am trying to send does not have a file input in it, only normal textboxes etc, but I was trying to keep the method generic to deal with both. The following is the code I am using to send the ajax request:
// get the edit tender form
var $Form = $Button.closest('form');
var Url = $Form.attr('action');
var AjaxRequestObject = new XMLHttpRequest();
var FormDataToSend = new FormData();
$Form.find(':input').each(function () {
if ($(this).is('input[type="file"]')) {
var files = $(this)[0].files;
if (files.length > 0) {
FormDataToSend.append(this.name, files[0]);
}
} else {
FormDataToSend.append(this.name, $(this).val());
}
});
AjaxRequestObject.open('POST', Url, true);
AjaxRequestObject.onreadystatechange = function () {
if (AjaxRequestObject.readyState == 4) {
// handle response.
if (AjaxRequestObject.status == 200) {
if (!AjaxErrorExists(AjaxRequestObject.responseText, )) {
alert("success");
console.log(AjaxRequestObject.responseText);
}
else {
alert('failure');
}
}
else {
alert('failure');
}
}
};
AjaxRequestObject.send(FormDataToSend);
This code was provided following a problem I had which Darin Dimitrov provided the solution to, so I could send the file inputs by ajax.
Any ideas why this request would not send the header for an ajax call?
X-Requested-With is automatically added by jQuery. You can just as easily add it yourself with AjaxRequestObject.setRequestHeader(). Docs
I was having troubles with detecting if my request was ajax. So, maybe this sample will save someone a minute or two:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', URL, true); // `true` for async call, `false` for sync.
// The header must be after `.open()`, but before `.send()`
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlhttp.onreadystatechange = function() {
// 4th state is the last:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { ... }
};
xmlhttp.send();
Tested with Flask.
You can override natively all XMLHttpRequest.open method calls and add in it X-Requested-With header like:
(function () {
// #author https://github.com/stopsopa jfdsa78y453cq5hjfd7s877834h4h3
if (window.XMLHttpRequest.prototype.onOpen) {
return console.log('XMLHttpRequest.onOpen is already defined');
}
function over(method, on, off) {
var old = window.XMLHttpRequest.prototype[method];
if (!old.old) {
var stack = [];
window.XMLHttpRequest.prototype[on] = function (fn) {
if (typeof fn === 'function') {
stack.push(fn);
}
}
window.XMLHttpRequest.prototype[off] = function (fn) {
for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
if (stack[i] === fn) {
stack.splice(i, 1);
break;
}
}
}
window.XMLHttpRequest.prototype[method] = function () {
var args = Array.prototype.slice.call(arguments);
var ret = old.apply(this, args);
for (var i = 0, l = stack.length ; i < l ; i += 1 ) {
stack[i].apply(this, args);
}
return ret;
}
window.XMLHttpRequest.prototype[method].old = old;
}
}
over('open', 'onOpen', 'offOpen')
XMLHttpRequest.prototype.onOpen(function () {
this.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
});
}());

Memory-leak at a wrapped XMLHttpRequest function

I wrote the following :
function ao(){
this.count=0;
this.flag=0;
this.tmr=0;
var self = this;
this.make=function(){
//log("before: "+this.url+" "+this.xhr);
self.xhr = (window.XMLHttpRequest)
? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//log("after: "+this.xhr);
}
this.request = function (method, url, sendStr, delay){
this.delay=delay;
if(delay && self.tmr==0){
self.start();
}
if(self.flag==0){
this.method = method;
this.url = url;
this.sendStr = sendStr;
self.make();
this.xhr.open(method, url, true);
this.xhr.onreadystatechange = this.stateChange;
this.xhr.onabort=this.rrr;
this.xhr.onerror=this.rrr;
this.xhr.setRequestHeader("Cache-Control","no-cache");
this.xhr.send(sendStr);
}
};
this.repeat=function(){
if(this.flag==0){
this.flag=1;
this.count++;
this.xhr.open(self.method, self.url+"?"+this.count, true);
this.xhr.onreadystatechange = this.stateChange;
this.xhr.onabort=this.rrr;
this.xhr.onerror=this.rrr;
this.xhr.setRequestHeader("Cache-Control","no-cache");
this.xhr.send(self.sendStr);
}
return 0;
}
this.stop=function(){
window.clearInterval(this.tmr);
this.tmr=0;
this.flag=0;
}
this.start =function(){
self.tmr=window.setInterval(function(){self.repeat();},self.delay);
}
this.stateChange = function(){
if (self.xhr.readyState <= 1){
return;
self.log("404 errors");
} else {
if (self.xhr.readyState == 4 && self.xhr.status == 200){
self.resp = self.xhr.responseText;
if (self.callback != null)
self.callback(self.xhr.readyState, self.xhr.status);
else {
if (self.getHTML) {
self.getHTML(self.resp);
this.xhr=null;
} else {
if (self.xhr.readyState == 4 && self.xhr.status == 200){
self.parseJSON();
self.traverse();
this.ro=null;
this.xhr=null;
}
}
}
}
}
self.flag=0;
return 0;
};
and in windows ff there is a memory leak. I spent days trying to fix it, but I'm stumped.
The following works :
var x=new ao();
ao.request("POST","/cgi-bin/sdf.cgi","text",1000)
and after every 1000 miliseconds if previous request is done, it makes new request.
Developers should also take precautions when it comes to using the
onreadystatechanged event of an XMLHttpRequest object. If the handler
is a closure that closes over a reference to the same XMLHttpRequest
object, another circular dependency can be created. This isn't
necessairly detected by the above tool because the object is not part
of the DOM.
Link

Categories