Syncronous XMLHTTPRequest deprecated crash browser? - javascript

I have to read information as below from a microprocessor hardware
var save_it = '';
$.ajax({
type: "GET",
url: 'http://www.micro-processor-server/?ROBOT=arm_controle',
async: false,
success:function(m) {
save_it = m;
}
}).responseText;
console.log(save_it);
While doing so, it works, but my browser console gives very scary warning as below, also several times I have noticed web-browser Google chrome get hang:
Can anyone please show an alternative way how to make my Ajax query compatible? (I can't change codes in Micro-processor its third party robot)

Put the code that needs the response in the success function. You could also use $.get if this is all you're needing to do.
$.get('http://www.micro-processor-server/?ROBOT=arm_controle', function(data) {
console.log(data);
});

call another function with return data.
$.get('http://www.micro-processor-server/? ROBOT=arm_controle',function(data){
myfun(data);
});
myfun(data){
console.log(data);//here you might be able get rid of asynchronous behaviour.
}

Related

Use data from ajax call without using async: false

I'm pretty new to JS/ajax and was a bit confused on ajax data/success returns.
I have the following ajax code. I want it to run the code in succes: after the ajax call has received the json from the imgur api.
It is only working for me with async: false. I thought the bit in success: would only run after the data has been retrieved, but for some reason data is null if aysnc is true.
I've read a lot of SO answers/jQuery documentation but I can't seem to figure out how to get it to not hang the browser with async: false
This code might be running 100+ times on a page (i.e. reddit.com/r/pics with 100 links loaded on one page), so async: false is not only bad practice but also renders the page unusable for 5 to 6 seconds, which is unacceptable.
I've tried making ajax a var then calling that var .success(function(data) ...); but it still does not work. I've also tried replacing success with complete.
It all only ever works with async: false
Any suggestions would be greatly appreciated!
Thanks!
$.ajax({
type: "GET",
url: "https://api.imgur.com/3/gallery/" + hash,
dataType: "json",
headers:{
'Authorization':'Client-ID c606aeeec9ca098'
},
async: false,
success: function(data) {
if(data.data.is_album == true) {
if(data.data.images_count == 1){
el[j].href = el[j].href.replace(/(http(s)?:\/\/)?(www\.)?(m\.)?imgur.com\/gallery\/.*/, data.data.images[0].link);
}else{
el[j].href = el[j].href.replace(/(http(s)?:\/\/)?(www\.)?(m\.)?imgur.com\/gallery\//, "https://imgur.com/a/");
}
}
else{
el[j].href = el[j].href.replace(/(.*)?(http(s)?:\/\/)?(www\.)?(m\.)?imgur.com\/.*/, data.data.link);
}
}
});
You might find the jQuery Deferred object (Promises interface) to be helpful. It allows you to do stuff like:
var promise = $.ajax("/myServerScript1");
function getStuff() {
return $.ajax("/myServerScript2");
}
promise.then(getStuff).then(function(myServerScript2Data){
// Do something with myServerScript2Data
});
Resource (this is well written and a necessary read for anyone using AJAX):
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
I can't see what doesn't work on your code but I can tell you what is not recommended.
Always have a failure handler : You have to put a function in the fail field of your request object. If you don't, you will not be able to see any errors.
Keep the test simple : You should begin by only displaying the value of the request result instead making some calculation with it. This way you can debug ONLY the request call and you are sure that the problem doesn't came from the calculation code
Use Promises API : As previously pointed by the #gibberish, the modern way to do what you want is to use Promises. You can use jQuery's promises or any other like ES6 Promises (that one requires a compilation time for most of browsers)

JavaScript ajax, JSONP, Callback function to do something with data

Fellas,
I'm trying to do an ajax call to get some JSON. I can get around the cross origin issues in Chrome very easily but in IE the only way I got it working without throwing an error is using JSONP. My problem is that i don't know how to process the response. I can see that the call executes and it returns JSON in fiddler but how do i catch it and play with it in my code that's below.
$.support.cors = true;
function callAjaxIE(){
$.ajax({
type: 'GET',
async: true,
url: usageUrl,
dataType: 'jsonp',
crossDomain: true,
jsonp: false,
jsonpCallback: processDataIE,
// cache: false,
success: function (data) {
alert('success');
//processData(data)
},
error: function (e){
console.log(e);
}
}).done(function (data) {
alert('done');
});
function processDataIE(){
alert('processing data ie');
}
It works when i run it, it displays a message box saying 'processing data ie' but so what. How do i play with the results?
UPDATE:
So I've updated the code as per Quentin. It doesn't go into the 'success' block. It errors out with the following.
When i look at fiddler. The JSON is there. How do i get it?
Don't force the function name. That's a recipe for race conditions. Remove jsonpCallback: processDataIE. Let jQuery determine the function name.
Don't remove the callback parameter from the URL. Make the server read callback from the query string to determine which function to call. Remove jsonp: false,.
Use the success function as normal. (Get rid of processDataIE, that's what success is for).
Asides:
crossDomain: true is pointless. It tells jQuery that when it is using XHR (which you aren't) and the URL is pointing to the same origin (which it isn't) then it should not add extra headers in case the server does an HTTP redirect to a different origin.
async: true is pointless. That's the default, and JSONP requests can't be anything other than async anyway.
$.support.cors = true; is pointless at best and can be harmful. Remove it.
Don't override jQuery's detection of support for CORS by the browser. You can't make ancient browsers support CORS by lying to jQuery. You're using JSONP anyway, so CORS is irrelevant.
The above is the sensible, standard, robust solution.
If you want the quick hack that maintains all the bad practises you have in play, then just look at the first argument to processDataIE.

Ajax call keeps getting blocked by browser

I am a bit stuck with an issue.
I am developing a small mobile website. I am trying to call a webservice using an ajax call, but the browser keeps blocking my call. If I start up Chrome using the tags... "--allow-file-access-from-files --disable-web-security​​" Then the call works perfectly. I have no issues whatsoever.
Now my problem is if I host the website, the browser is going to block my ajax call and the user cannot for example login or retrieve information. I present my ajax call below...
$.ajax({
async: true,
beforeSend: function () {
},
complete: function () { },
type: 'POST',
url: 'https://MySecretUrl.com/login?format=json',
contentType: 'application/json',
dataType: 'json',
data: '{"UserId":"mySecretUserId","Password":"mysecretPassowrd"}',
success: function (resultMessage) {
if (resultMessage.WasSuccessful == true) {
alert('YAY');
} else {
alert('Semi Yay');
}
},
error: alert('OOOOPS')
});
Does anybody know a workaround for getting information from the webservice without any browser blocking the ajax call ?
Any suggestions would be greatly appreciated.
Thanks in advance for the help.
EDIT
Hi Guys, Ok so I did some more digging and discovered the following.
When the request is made with browser security, the call changes the POST to a OPTIONS. this is called a preflighted request. One workaround that I have found is if you are making a GET call, then you can use jsonp as your data type. But now my problem is that it is incompatible with POST. Is there any fix that does not require the webservice to be changed ?
Is there any fix that does not require the webservice to be changed ?
No. If changing the webservice isn't an option, your only option is to not use the browser to make this request.
You must either make the server return the data in a format that can be accepted cross-domain, or don't make cross-domain requests with the browser.

Javascript Synchronization with JSON Requests

How can I make sure that a piece of code has executed completely before executing another? I am sending some ajax requests to a server and then using the returned data to generate the rest of the webpage. the things is, is that i need to have all that data in the webpage to proceed with the rest of the code as that code will affect what has been generated and, that code, runs before the json requests and all of that have finished... is there any way I can make sure this does not happen? I managed to solve it by performing the requests and then asking the user to press a button but that is a total no-sense way of doing it.
Any ideas?
Here is some code: The problem is that the second line is executed before the first (there are many calls to similar JSON functions).
$.getJSON(url, function(data){ $("#mycontent").append("..... stuff here...... create loads of dibs with class set to mydivclass"); });
...
$("div.mydivclass").hide();
Unforunately I cannot use the ajax synchronous property because: "dataType: "jsonp" requests do not support synchronous operations"
If you are using jQuery 1.5+ you can make use of deferreds to solve your issue:
function first_ajax_request() {
return jQuery.ajax(
// Your settings here
success: success_function_1
);
}
function second_ajax_request() {
return jQuery.ajax(
// Your settings here
success: success_function_2
);
}
function final_sucess_callback() {
// Do all your display work.
}
jQuery.when(first_ajax_request(),
second_ajax_request()).then(final_success_callback);
There is an excellent article on the topic that you should read up on as well by Eric Hynds. He gives some examples of exactly the kind of problem you are trying to solve.
jquery requests are asynchonize by default , so your code does not wait for the response , so you have no guarantee that code after request will execute after the response , so you can set the request synchronize by set the async property false , now the request is synchronize and you can gurantee the rest of the code will execute after the response from the server ,
like this .
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument,,
async:false,
success: handleResponse
});

Jquery .Get() pulls NULL in Internet Explorer

I have a problem with an AJAX call in JQuery. It works on Chrome, FF, and Safari, but not IE. In fact in IE nothing happens at all, no errors, no data loaded.
Here is the code:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
$.get("ShoppingCart2.aspx", { }, function(data) {
//query the jq object for the values
alert(data);
alert($(data).find('#Items').text());
var intI = parseInt(($(data).find('#Items').html()));
With the alert data I find all the data from the page I am making a call from, but unfortunately my data.find methods pull up null for IE. I'm not sure if it's the code or the browser, but I am really stuck. Thank you for the help.
Edit: I did add in the cache: false command, but still I have no luck. I really cannot understand why this won't work in IE.
Try this (once in your page/external js, before your AJAX calls):
$.ajaxSetup({ cache: false });
IE likes to cache the hell out of things, and if you were testing and had no content there at one point, chances are IE is holding onto it. Using $.ajaxSetup() and and telling it by default to not cache AJAX results should resolve this. If you're curious, it's sticking a timestamp on the URL as a cache breaker under the covers, use fiddler to see this happening.
Is it perhaps caching the AJAX? What happens if you put this before your code:
$.ajaxSetup({ cache:false });
A quick solution without coding it could be to press CTR+F5 to clear the cache upon refresh.
Well I was unable to make the .find part of the .get work in internet explorer, but I did find a way to get the ajax information I needed:
var information = $.ajax({ type: "GET", dataType: "html", url: "ShoppingCart2.aspx", data: querystring, async: false }).responseText + " ";
This passes a query string to the website then gets information from the website back into one big string. I then
manipulated that string to get what I needed. Unfortunately it is a lot slower than the .get command, but it is a fix.
Thanks for the help everyone!

Categories