A part of my chrome extension tests to see if the user is connected to the internet. It works once perfectly but after it runs, $.ajax === undefined and I don't know why. I don't see any setters which could modify $.ajax
var testInternet = function(callback) {
"use strict";
var testURLs, doCallback, i, failCount;
if (! callback) {
callback = function(){};
}
doCallback = true;
failCount = 0;
testURLs = [
"http://clients5.google.com/pagead/drt/dn/dn.js"
];
for (i= 0; i < testURLs.length; i++) {
testConnection(testURLs[i], function(success){
if (success && doCallback) {
doCallback = false;
callback(true);
return;
} else {
failCount += 1;
if (failCount === testURLs.length) {
callback(false);
return;
}
}
});
}
}
var testConnection = function(url, callback) {
"use strict";
$.ajax({
url: url,
timeout: 10000,
cache: false,
success: function(data) {
callback(true);
return;
},
error: function(data) {,
callback(false);
return;
}
});
}
It looks like because you are getting a .js file, jQuery automatically defaults the dataType to script, which will cause jQuery to evaluate the script being loaded. Specifying dataType: 'text' should prevent that unwanted behavior.
Related
I have one function with AJAX Call(Below Code):
function get_type(Name) {
var field_name;
$.ajax({
type: "GET",
url: "../home/Asset/MR/MR.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('pub').each(function() {
if (Name == $(this).find('pro').text()) {
$(this).find('metadata field').each(function() {
field_name = $(this).find('name').text();
if (field_name == "little") {
type = "L";
} else if (field_name == "Big") {
type = "b";
}
});
}
});
}
});
}
This code works well but the problem is it run after all the functions finished. I want to run this code first I need to get data from the XML. I need to stop the loop of $(xml).find('pub').each(function() this once the Name== $(this).find('pro').text() text is matched. Because this loop execute even I get the answers.
Calling Function codes:
var rd = new FileReader();
rd.onload = function(e) {
var xmlDoc = $.parseXML(this.result);
var $xml = $(xmlDoc);
var J_Name = $xml.find('meta').text();
get_type(J_Name);
//check allowed child of front tag
check_allowed_direct_child("places", "Tirunelveli,Tiruchendur,Alwar", "RULE_002", "Fail");
};
rd.readAsText(this.files[i]);
Callbacks to the rescue!
function get_type(name, cb) {
cb = cb || function () {};
var field_name;
var type;
var types_map = {
'little': 'L',
'Big': 'b'
};
$.ajax({
type: 'GET',
url: '../home/Asset/MR/MR.xml',
dataType: 'xml',
success: function (xml) {
$(xml)
.find('pub')
.each(function () {
if (name == $(this).find('pro').text()) {
$(this)
.find('metadata field')
.each(function () {
field_name = $(this)
.find('name')
.text();
if (types_map.hasOwnProperty(field_name)) {
type = types_map[field_name];
return false; // break out of each()
}
});
return false; // break out of each()
}
});
cb(type); // execute provided callback
}
});
}
var rd = new FileReader();
rd.onload = function (e) {
var xmlDoc = $.parseXML(this.result);
var $xml = $(xmlDoc);
var J_Name = $xml.find('meta').text();
get_type(J_Name, function (type) {
// do stuff once get_type() resolves, type being either matched type or undefined
check_allowed_direct_child('places', 'Tirunelveli,Tiruchendur,Alwar', 'RULE_002', 'Fail');
});
};
rd.readAsText(this.files[i]);
If interested, read on how to make use of Promises, to make callback code a lot more digest: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
If still interested, read on how to use async / await to make Promises code a lot more digest: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
I'm using a call back function which will check for 60secs. If file avaible then will return true else will return false. The call back function I'm calling after ajax call.. Here is code below :
$.ajax({
type: '..',
url: '..',
data: '..',
success: function(data) {
window.loadFile(data);
}
})
window.loadFile = function(filePath) { // I'm getting the data. Now passing to call back function
$.when(window.waitTillFileExistsAndLoad(filePath)).done(function(data) {
alert(data) // here data is giving me undefined..
});
}
var timer = 0;
window.waitTillFileExistsAndLoad = function(fileName) {
var checkFile;
return $.get(fileName, function(data) { // If file found..
timer = 0;
return true;
}).error(function() { // If file not found..
timer += 1;
if(timer == 30) {
timer = 0;
clearTimeout(checkFile);
return false;
} else {
console.log('error occured');
checkFile = setTimeout(function() {
window.waitTillFileExistsAndLoad(fileName);
}, 2000);
}
});
}
The issue is that when I'm using $.when() it's giving me undefined. Please suggest me what's wrong in my code.
I can’t seem to get this simple Parse query to work in my cloud code then() it works outside of this but when i place the code inside of this then function nothing happens. The variables are just placeholders for now in terms of testing but i have the default TestObject class you get when you start Parse from the beginning but for some reason it just keeps on returning nothing.
Here is the full function that i am currently using.
// Function which will get the data from all the links passed into the function
Parse.Cloud.define("myNews", function (request, response) {
var promises = _.map(import_io_keys, function (news_api_key) {
return Parse.Cloud.httpRequest({
method: 'GET',
url: "https://api.import.io/store/connector/" + news_api_key + "/_query?input=webpage/url:https%3A%2F%2Fwww.designernews.co%2Fnew&&_apikey=xxxxxxxxxxxxxxxxxx",
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then(function (httpResponse) {
result = JSON.parse(httpResponse.text);
var success = false;
var news_icon = "";
var news_source_name = "";
var query = new Parse.Query("TestObject");
query.find({
success: function(results) {
success = true;
news_icon = results[0].get("foo");
news_source_name = results[0].get("foo");
response.success("done" + news_icon);
},
error: function() {
success = false;
response.error("Query lookup failed");
}
});
for (var story in result.results) {
if(story.length > 0){
if (story["article_link/_text"] !== "" && story["article_link"] !== "" && story["article_time"] !== "") {
if(success){
// Do the stuff later
}
}
}
}
});
});
Parse.Promise.when(promises).then(function () {
console.log("Got all the stories");
response.success(newsJsonData);
}, function () {
response.error("No stories");
console.log("API KEY IS: " + request.params.keys);
});
});
I am having some trouble with the code below. It will not run in IE9. It works fine in other browsers though.
I have placed an alert inside the code but that piece of code is not reached.
anyone has got any idea how to solve this issue?
NWF$.ajax({
url: 'http://pdfservice/training/',
data: JSON.stringify(dataJSON),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
cache: false,
success: function (fileName) {
alert('ok!');
window.location.href = 'http://pdfservice/training/?meeting=' + fileName;
},
error: function (result) {
alert(JSON.stringify(result));
}
});
I just changed the fail to error and this is the error that I get:
{"readyState":0,"status":0,"statusText":"No Transport"}
Jquery w Ajax for IE9 is broken.
This is supported through a jquery plugin
"Implements automatic Cross Origin Resource Sharing support using the XDomainRequest object for IE8 and IE9 when using the $.ajax function in jQuery 1.5+."
This happens because your JSON data is corrupt.
Fix your JSON data, you can use JSONLint to validate your JSON response to make sure it's valid JSON.
Old post, figured I'd add my findings from AJAX POST request on IE fails with error "No Transport"?
I'm adding the code in the event it gets deleted:
if (!jQuery.support.cors && window.XDomainRequest) {
var httpRegEx = /^https?:\/\//i;
var getOrPostRegEx = /^get|post$/i;
var sameSchemeRegEx = new RegExp('^'+location.protocol, 'i');
var xmlRegEx = /\/xml/i;
// ajaxTransport exists in jQuery 1.5+
jQuery.ajaxTransport('text html xml json', function(options, userOptions, jqXHR){
// XDomainRequests must be: asynchronous, GET or POST methods, HTTP or HTTPS protocol, and same scheme as calling page
if (options.crossDomain && options.async && getOrPostRegEx.test(options.type) && httpRegEx.test(userOptions.url) && sameSchemeRegEx.test(userOptions.url)) {
var xdr = null;
var userType = (userOptions.dataType||'').toLowerCase();
return {
send: function(headers, complete){
xdr = new XDomainRequest();
if (/^\d+$/.test(userOptions.timeout)) {
xdr.timeout = userOptions.timeout;
}
xdr.ontimeout = function(){
complete(500, 'timeout');
};
xdr.onload = function(){
var allResponseHeaders = 'Content-Length: ' + xdr.responseText.length + '\r\nContent-Type: ' + xdr.contentType;
var status = {
code: 200,
message: 'success'
};
var responses = {
text: xdr.responseText
};
try {
if (userType === 'json') {
try {
responses.json = JSON.parse(xdr.responseText);
} catch(e) {
status.code = 500;
status.message = 'parseerror';
//throw 'Invalid JSON: ' + xdr.responseText;
}
} else if ((userType === 'xml') || ((userType !== 'text') && xmlRegEx.test(xdr.contentType))) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = false;
try {
doc.loadXML(xdr.responseText);
} catch(e) {
doc = undefined;
}
if (!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length) {
status.code = 500;
status.message = 'parseerror';
throw 'Invalid XML: ' + xdr.responseText;
}
responses.xml = doc;
}
} catch(parseMessage) {
throw parseMessage;
} finally {
complete(status.code, status.message, responses, allResponseHeaders);
}
};
xdr.onerror = function(){
complete(500, 'error', {
text: xdr.responseText
});
};
xdr.open(options.type, options.url);
//xdr.send(userOptions.data);
xdr.send();
},
abort: function(){
if (xdr) {
xdr.abort();
}
}
};
}
});
};
jQuery.support.cors = true;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return Value from inside of $.ajax() function
I'm working on a CakePHP app that makes use of widespread AJAX calls to controllers. I'm stuck with one particular AJAX call in which I'm trying to assign the response from the controller to a JS global variable. Here is the code:
window.errors = "";
function setErrors(err) {
window.errors = err;
}
function ajaxCall(u, t, d, dt) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
var success = false;
var err = "";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
console.log(err); //<=== displays correct value
setErrors(err); //<=== but somehow this seems to be failing??
}
else {
if(d.success === "1") {
success = true;
}
}
}
});
return success; //<=== I suspect this might be the culprit
}
And this is how ajaxCall() is used:
function register() {
var data = {};
var $inputs = $("#regForm :input");
$inputs.each(function(){
data[this.name] = $(this).val();
});
data = {"User" : data }; //CakePHP compatible object
data = JSON.stringify(data);
//Here's the AJAX call
if(ajaxCall('https://localhost/users/add', 'post', data, 'json')) {
alert("Registered!");
}
else {
alert(window.errors); // <=== empty string
console.log("window.errors is: " + window.errors); // <=== empty string
}
}
But on the Chrome JS console, window.errors returns the correct value (non-empty, validation error string).
I found a similar question that possibly might be addressing my issue (the return success immediately following the $.ajax() is being executed before the success: callback). How can I fix this without drastically changing the code (also, I don't want to make this a synchronous call)?
Yes, you are right that the return statement runs before the success callback. You can't return the result from the function, as the function has to return before the success event can be handled.
Add a callback to the ajaxCall function, and call that instead of setting the success variable:
function ajaxCall(u, t, d, dt, callback) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
callback(false, err);
} else {
callback(d.success === "1", "");
}
}
});
}
Send the code for handling the result into the ajaxCall function:
ajaxCall('https://localhost/users/add', 'post', data, 'json', function(success, err){
if (success) {
alert("Registered!");
} else {
alert(err);
}
});