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;
Related
I have been using the following code to successfully read the contents of an external webpage as a string - I haven't used this program in a month or so but it has suddenly stopped working even though the code has not been changed. I suspect the YQL API has been updated but I couldn't find any documentation that I could understand on this. (I am a beginner at JS). If someone could point me to how to update my code it would be much appreciated!
Code:
function formSubmitted(raceID) {
if(raceID.length < 4 && raceID > 0){
savedRaceID = raceID;
raceUrl = "http://www.bbk-online.net/gpt/lap"+raceID+".htm";
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0].replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
//THE ERROR IS COMING FROM ABOVE - REPLACE IS BEING CALLED ON A NULL OBJECT??
//SUGGESTS NO DATA RETURNED?
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: raceUrl,
type: 'GET',
success: function(res) {
processData(res.responseText);
}
});
}
else{
alert("Please enter a valid race number...");
}
}
I have highlighted where the error is coming from - it appears that the function is not returning any data?
Let's say I have couple of input fields - their combination must be unique.
Each of them causes remote validation method triggering - and it's the same method for both fields. If combination is unique - it returns true.
The problem is following: when after validation error I change the field, that is not marked as erroneous, the erroneous field keeps being considered erroneous, even if method returns true (the couple is unique)!
I even don't need to make extra request to server, because the couple is unique! I just need to clear error for field, marked erroneous. However, I have not managed to do this - seems like jquery does not offer functionality for this.
Any ideas?
The relevant code is pretty huge, but the key parts are here:
this.clearErrors = function ($elements) {
var $validator = $elements.first().closest('form').validate();
$elements.each(function(index, item) {
var $parent = $(item).parent();
var element = $(item).get(0);
if ($parent.is('td')) {
$parent.removeClass(window.resources.errorCellClass);
}
$parent.find('span.' + window.resources.errorSpanClass).remove();
$validator.successList.push(element);
delete $validator.invalid[element.name];
delete $validator.submitted[element.name];
});
};
//Fixing remote method, since original one returned "pending" status all the time, as reported in other stackoverflow question
$.validator.addMethod('synchronousRemote', function (value, element, param) {
if (this.optional(element)) {
return 'dependency-mismatch';
}
var previous = this.previousValue(element);
if (!this.settings.messages[element.name]) {
this.settings.messages[element.name] = {};
}
previous.originalMessage = this.settings.messages[element.name].remote;
this.settings.messages[element.name].remote = previous.message;
if (typeof param == 'string') {
param = { url: param }
}
if (previous.old === value) {
return previous.valid;
}
previous.old = value;
var validator = this;
this.startRequest(element);
var data = {};
data[element.name] = value;
var valid = 'pending';
$.ajax($.extend(true, {
url: param,
async: false,
mode: 'abort',
port: 'validate' + element.name,
dataType: 'json',
data: data,
success: function (response) {
validator.settings.messages[element.name].remote = previous.originalMessage;
valid = response === true || response === 'true';
if (valid) {
var submitted = validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted = submitted;
validator.successList.push(element);
delete validator.invalid[element.name];
validator.showErrors();
} else {
var errors = {};
var message = response || validator.defaultMessage(element, 'remote');
errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
validator.invalid[element.name] = true;
validator.showErrors(errors);
}
previous.valid = valid;
validator.stopRequest(element, valid);
}
}, param));
return valid;
});
$root.filter(':input[data-excluded-values-method]:not([readonly])').add($root.find(':input[data-excluded-values-method]:not([readonly])')).each(function () {
var $element = $(this);
$element.validate({
onkeyup: false
})
var $entityContainer = $element.closest('[data-entity]');
var $keyFields = $entityContainer.filter('INPUT[data-is-key]:not([disabled])').add($entityContainer.find('INPUT[data-is-key]:not([disabled])'));
var localizedNames = [];
$keyFields.each(function () {
localizedNames.push($(this).attr('localized-name'));
});
$element.rules('add',
{
synchronousRemote: function () {
var key = [];
var keyIsUnique = true;
$keyFields.each(function () {
key.push($(this).val());
});
return {
url: $element.attr('data-excluded-values-method'),
type: 'POST',
async: false,
data: JSON.stringify({
key: key,
entityType: $entityContainer.attr('data-entity')
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
dataFilter: function (isUnique) {
keyIsUnique = isUnique;
return isUnique;
},
complete: function () {
if (keyIsUnique === 'true') {
window.commonUtils.clearErrors($keyFields.filter('[name!="' + $element.attr('name') + '"]:input[data-excluded-values-method]:not([readonly])'));
}
}
}
},
messages: {
synchronousRemote: $.validator.format(window.resources.notUniqueValidationError)(localizedNames.join(' + '))
}
});
});
I've debugged jquery validate method and found what yet should be set to clear validation error:
$validator.previousValue(element).valid = true;
Now everything works.
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);
});
});
The signature for casper.base64encode is given as:
base64encode(String url [, String method, Object data])
... and the docs give examples of how to pass form values using the data argument. But is it possible to pass header strings? In my case, I need to pass Authentication possibly Accept strings.
No, you cannot use base64encode(), because it doesn't support headers in any way. The underlying __utils__.sendAJAX() only supports the "Content-Type" request header. You can implement your own. Here is a step in the right direction by copying the necessary functions from the clientutils module and adjusting them:
casper.base64encodeWithHeaders = function(url, method, data, headers) {
return this.evaluate(function(url, method, data, headers){
function getBinaryWithHeaders(url, method, data, headers) {
try {
return sendAjaxWithHeaders(url, method, data, false, {
overrideMimeType: "text/plain; charset=x-user-defined",
headers: headers
});
} catch (e) {
if (e.name === "NETWORK_ERR" && e.code === 101) {
__utils__.log("getBinary(): Unfortunately, casperjs cannot make cross domain ajax requests", "warning");
}
__utils__.log("getBinary(): Error while fetching " + url + ": " + e, "error");
return "";
}
};
function sendAjaxWithHeaders(url, method, data, async, settings) {
var xhr = new XMLHttpRequest(),
dataString = "",
dataList = [];
method = method && method.toUpperCase() || "GET";
var contentType = settings && settings.contentType || "application/x-www-form-urlencoded";
xhr.open(method, url, !!async);
__utils__.log("sendAJAX(): Using HTTP method: '" + method + "'", "debug");
if (settings && settings.overrideMimeType) {
xhr.overrideMimeType(settings.overrideMimeType);
}
if (method === "POST") {
if (typeof data === "object") {
for (var k in data) {
dataList.push(encodeURIComponent(k) + "=" + encodeURIComponent(data[k].toString()));
}
dataString = dataList.join('&');
__utils__.log("sendAJAX(): Using request data: '" + dataString + "'", "debug");
} else if (typeof data === "string") {
dataString = data;
}
xhr.setRequestHeader("Content-Type", contentType);
}
if (settings && settings.headers) {
for(var header in settings.headers) {
if (settings.headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, settings.headers[header]);
}
}
}
xhr.send(method === "POST" ? dataString : null);
return xhr.responseText;
}
return __utils__.encode(getBinaryWithHeaders(url, method, data, headers))
}, url, method, data, headers);
}
You can use it like this:
casper.then(function(){
var response = this.base64encodeWithHeaders("http://example.com", "GET", null, {
"Accept": "text/plain",
"Authentication": "let me in!"
});
this.echo(response);
});
For some reasons I have a javascript that create an entity record and a plugin will fire on post create. If the pugin throw an exception, it does NOT display to the user as the javascript is involved. I am wondering if there is a way to pass the exception from the plugin to javascrit so it can display it to the user.
Thanks.
Do you receive any http status code error like 40*, 500, 50* , if you use Odata, you have a callback to get the error. Javascript exception may not be throw.
Example:
.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8″,
datatype: “json”,
url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
success: function (data, textStatus, XmlHttpRequest) {
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert(“Error on the creation of record; Error – “+errorThrown);
}
});
}
Checking the XMLHttpRequest readyState and status should do the trick:
function createRecord(eObject, eName) {
var jsonEntity = window.JSON.stringify(eObject);
var u = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var rec = new XMLHttpRequest();
var p = u + ODATA_ENDPOINT;
rec.open('POST', p + "/" + eName, false);
rec.setRequestHeader("Accept", "application/json");
rec.setRequestHeader("Content-Type", "application/json; charset=utf-8");
rec.send(jsonEntity);
if (rec.readyState == 4) {
if (rec.status == 200) {
var r = JSON.parse(rec.responseText).d;
return r;
}
else {
var error;
try {
// To get the exception from the responseXML
// I get an error when trying to use JSON.parse(rec.response)
// Unexpected token <
// I would much rather use JSON.parse
// than fiddling with the XML
// Please let me know if you find how to
// get the error message with JSON.parse
var xmlDoc = rec.responseXML;
var error = xmlDoc.childNodes[0]
.childNodes[0]
.childNodes[0]
.childNodes[1]
.childNodes[0].nodeValue + "."; // The error message
}
catch (e) {
// unable to get error message from response
error = "General Error";
}
return error;
}
}
// there is a problem
// maybe return general error message
return "General Error";
}
Thanks for all of you. I did resolve the issue by modifying part of my code to the following:
rec.send(jsonEntity);
if (rec.readyState == 4) {
if (rec.status >= 200) {
var newRecord = JSON.parse(rec.responseText).d;
return newRecord;
}
else {
var error;
var er;
try {
error = rec.responseText.toString();
error = error.substring(error.lastIndexOf("value\": ")+9,error.lastIndexOf("\""));
alert(error);
}
catch(e) {
error = rec.responseText.toString();
error = encodeURIComponent(error);
er = error.substring(error.lastIndexOf("value%22%3A%20%22")+17,
error.lastIndexOf("%22%0D%0A%7D%0D%0A%7D%0D%0A%7D"));
er = decodeURIComponent(er);
return er;
}
}