YQL AJAX cross domain request stopped working - javascript

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?

Related

Mixed Content: The page at 'https://localhost:44387/Home/Index' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint

I have been trying to make an AJAX request from localhost (which is onfigured for https) to a server that is over http. everytime i receive an error from the browser saying it has been blocked since there is some "mixed content" in the call.
How can i avoid such error? sometimes in the browser I can see the JSON response I need but it never makes it to the page due to the error.
Here is the code when i click on a button to request data:
$(document).ready(function () {
var gallery = null;
$("#getSubscriptionWorkflows").click(function () {
gallery = new Gallery($("#apiLocation").val().trim(), $("#apiKey").val().trim(), $("#apiSecret").val().trim());
gallery.getSubscriptionWorkflows(function (workflows) {
var listStr = "";
var len = workflows.length;
if (len === 0) {
listStr = "There are no workflows in the subscription associated with the given api key";
}
for (var i = 0; i < len; i++) {
listStr += "<li>" + workflows[i].metaInfo.name + " - " + workflows[i].id + "</li>";
}
$("#workflowList").html(listStr);
}, function (response) {
$("#workflowList").html(response.responseJSON && response.responseJSON.message || response.statusText);
});
});
});
And here is the API code:
Gallery = function(apiLocation, apiKey, apiSecret) {
this.apiKey = apiKey;
this.apiSecret = apiSecret;
this.apiLocation = apiLocation;
this.getSubscriptionWorkflows = function (success, error){
var type = "GET",
url = this.apiLocation + "/workflows/subscription/",
params = buildOauthParams(this.apiKey),
//add any user parameters before generating the signature
signature = generateSignature(type, url, params, this.apiSecret);
$.extend(params, {oauth_signature: signature});
$.ajax({
type: type,
url: url,
data: params,
success: success,
error: error
});
};

How to Send Ajax Request After A Specific Time

How to Send Ajax Request in specific time and only that particular event
I m User Time Interval But it’s not Working.
i want get data in request 1 for use in request 2 but it get null data in request 2
setInterval()
it's not Working for me.
I want To send Request 2 After the some time of Request 1
Request 1:-
$(document).on("change", ".supplyItem", function (event) {
var id = $(this).attr("data-id");
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospital = $("#hospital").val();
var physician = $("#physician").val();
var category = $("#category").val();
var manufacturer = $("#manufacturer").val();
var project = $("#project").val();
if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
data: {
supplyItem: supplyItem,
hospital: hospital,
project: project,
},
success: function (data) {
console.log(id);
if (data.status) {
var html_data = '';
var item = data.value;
console.log(item);
$('.hospitalPart[data-id=' + id + ']').val(item.hospitalNumber);
$('.mfgPartNumber[data-id=' + id + ']').val(item.mfgPartNumber);
// $('.mfgPartNumber[data-id='+id+']').text('something');
} else {
$('.hospitalPart[data-id=' + id + ']').val('');
$('.mfgPartNumber[data-id=' + id + ']').val('');
}
$('.quantity[data-id=' + id + ']').val('');
$('.purchaseType[data-id=' + id + ']').val('');
$('#serial-text' + id).val('');
$('#serial-drop' + id).val('');
$('#serial-drop' + id).empty();
}
});
}
});
Request 2:-
$(document).on('change', '.supplyItem', function (event) {
var timer, delay = 2000;
var id = $(this).attr("data-id");
var client = $("#hospital").val();
timer = setInterval(function(){
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospitalPart = $(".hospitalPart[data-id=" + id + "]").val();
var mfgPartNumber = $(".mfgPartNumber[data-id=" + id + "]").val();
alert(supplyItem);
alert(hospitalPart);
alert(mfgPartNumber);
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
data: {
supplyItem: supplyItem,
hospitalPart: hospitalPart,
mfgPartNumber: mfgPartNumber,
client: client,
},
success: function (data) {
if (data.status) {
var html_data = '';
var check = data.value;
if (check == 'True') {
html_data += "<option value=''>Purchase Type</option><option value='Bulk'>Bulk</option><option value='Consignment'>Consignment</option>";
$('.purchaseType[data-id=' + id + ']').html(html_data);
} else {
html_data += "<option value=''>Purchase Type</option><option value='Consignment'>Consignment</option>";
$('.purchaseType[data-id=' + id + ']').html(html_data);
}
}
}
});
}, delay);
clearInterval(timer);
});
You can move Request 2 into a function and this JS code will call the Request2 function after given interval of time (milliseconds), I have set it to 5 seconds for now.
setInterval(function () { Request2(); }, 5000);
function Request2(){
console.log("Request 2 called");
//add request 2 code here
}
jQuery's $.ajax method returns a promise, which is passed the result of the server-side call. You can chain these calls together so that you can build the result of multiple ajax calls. When you use it this way you do away with success callbacks as they are no longer necessary.
Applied to your code it might looks something like this:
$(document).on("change", ".supplyItem", function (event) {
var id = $(this).attr("data-id");
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospital = $("#hospital").val();
var physician = $("#physician").val();
var category = $("#category").val();
var manufacturer = $("#manufacturer").val();
var project = $("#project").val();
if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
data: {
supplyItem: supplyItem,
hospital: hospital,
project: project,
})
.then(function(data1){
// process result of call1 and make call2
var item = data1.value;
return $.ajax({
url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
data: {
supplyItem: supplyItem,
hospitalPart: value.hospitalPart, // note using result from 1 directly
mfgPartNumber: value.mfgPartNumber,
client: hospital
}
});
})
.then(function(data2){
// process result of call2
});
};
});
The point here is that you don't need to stash the result of call1 into some elements and re-read them before making call2, and trying to wait enough time before making call2. You just chain it all together with then.
Ok first though: Instead of using setInterval and then clearing the interval after it has run a single time, why not just use
setTimeout(function, delay);
Then personally I prefer to use XMLHttpRequest instead of Jquery AJAX, Jquery uses XMLHttpRequest at its base anyway,I just prefer it so I dont have to use Jquery, but if your already using Jquery in your site then it should be no more heavy. Here is a quick example of XMLHttpRequest so u can use it if you prefer.
var xhr = new XMLHttpRequest();
xhr.open("POST", 'URL::to("admin/repcasetracker/getdevicedata")', true);
xhr.setRequestHeader("Content-Type", "application/json charset=utf8");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// content is loaded...
if (xhr.responseText) {
//Some code to run after the server responds and it was successfull
}
}
};
xhr.send(JSON.stringify({test:'test'})); //This is the data you are handing to the server
Notice the use of xhr.responseText, JQuery uses the same variable and this is usually the response from the server. One sure way to know is use your browser's debugging engine (F12 on Chrome and Firefox, have no idea on other browsers) to inspect the variables, it is very easy to ascertain the correct variable to use.
And then one last thought: I see you are not declaring the content-type and not JSON.stringify'ing() your data when you send it to the server.
Best way to debug a situation like this is 'proccess of elimation' so find out if the server is receiving the data then if the server is proccessing the data correctly and then check if the server is sending the data correctly.
If you are using Nginx use the /var/log/nginx/error.log to see if it throws any errors ( tip: tail -f /var/log/nginx/error.log | Apache uses /var/log/http/error.log on most distros ) and if you are using .NET just debug it in Visual Studio.
And read up on the Jquery success event there is 2 more arguments that gets passed - String textStatus and jqXHR jqXHR
http://api.jquery.com/jquery.ajax/
So to summarize:
Make sure to declare the dataType: 'json'
Use the correct variable, should be responseText
when passing the server data and using 'json' make sure to JSON.stringify() it
And I don't quite see why you want to use setTimeout in the first place.
If you are simply waiting for the server to respond then using any type of delay will be a terrible idea, instead use the events that gets fired after the server responds.
So in Jquery that is success: function() {} and error: function() {}
and in XMLHttpRequest its the xhr.onreadystatechange = function () { }

Trouble building FB.api query

OK so I'm working on a Facebook Group Feed that loads more results, but I'm having trouble building the initial query for it all to work.
In the first if statement below, you can see where I put the parts of the query into variables and then call the function, passing those variables. This all works fine...
if (response.status === 'connected') {
// Logged into your app and Facebook.
console.log('Welcome! Fetching your information.... ');
var path = '/',
method = 'POST',
params = {
batch: [
{method : 'GET', name : 'user', relative_url : '/me?fields=id,name,picture'},
{method: 'GET', name : 'post-ids', relative_url: '/group-id/feed?fields=fields{with field expansion}',omit_response_on_success : false}
]
};
loadFeed(path, method, params);
}
The funciton below is where I'm having trouble. The first time the function is called, I need to put those three variables together into one, and call it with FB.api. You can see the function here:
function loadFeed(path, method, params) {
console.log('------------------');
console.log(path + ', ' + method + ', ' + params);
if(path != 'undefined') {
if(method != 'undefined') {
if(params != 'undefined') { var query = '{\'' + path + '\', \'' + method + '\', ' + params + '}'; }
}
else { var query = path; }
}
$('#load-more').css('display', 'hidden');
FB.api(query, function (response) {
console.log(response);
// first time page loads, response[0] is the login, and response[1] is the feed
// each time after that, response[0] is the feed
if(response.length > 1) {
var membody = JSON.parse(response[0].body),
feed = JSON.parse(response[1].body);
} else {
var feed = JSON.parse(response);
}
if(feed.paging) {
if(feed.paging.next) {
var load_more = '<div id="load-more"><center>Load more</center></div>',
method = '',
params = '';
$('#feed').append(load_more);
$('#load-more').click( function() {
loadFeed(feed.paging.next);
});
}
}
});
}
On the first call of this function, I get this error:
error: Object
code: 2500
message: "Unknown path components: /', 'POST', [object Object]}"
type: "OAuthException"
This seems to tell me that I've basically put the query together wrong, but I've tried a few different things and none of it is working. You can see in the error message that there's a missing single quote at the beginning of the query, and I've not been able to figure out how to keep the single quote there.
Does anyone have any ideas on how I can fix this problem?
Also, if you know a better way to do all this then I'd appreciate that as well!
It seems you are building your Javascript API call with HTTP API parameters.
To query JS API for user:
FB.api(
"/me", // or "/99999999999" the user's id
function(response) {
if (response && !response.error) {
/* handle the result */
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/user
To query JS API for group:
FB.api(
"/{group-id}",
function(response) {
if (response && !response.error) {
/* handle the result */
}
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/group

jquery ajax call is not working in IE9

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;

jsonp request receives 401 unauthorized

I'm using the select2 plugin to connect with LinkedIn's company search API. What I need is for it to work with jsonp so that I can avoid the "Access-Control-Allow-Origin" error I get with a regular json request [I've confirmed that the json request works when I disable the default security settings in Chrome.]. By "work" I mean I want the jsonp request url to authenticate me just as the json request url is, but I continue receiving a 401 unauthorized error.
I think my problem lies with the "callback" parameter in my url set by jsonp. For instance, the LinkedIn-authenticated company-search url created by json is:
http://api.linkedin.com/v1/company-search?keywords=mcdonalds&oauth_consumer_key=xxx&oauth_nonce=xxx&oauth_signature=xxx&oauth_signature_method=xxx&oauth_timestamp=xxx&oauth_token=xxx
With jsonp it is something like:
http://api.linkedin.com/v1/company-search?callback=jQuery19107866718948353082_1365690327081&keywords=mcdonalds&oauth_consumer_key=xxx&oauth_nonce=xxx&oauth_signature=xxx&oauth_signature_method=xxx&oauth_timestamp=xxx&oauth_token=xxx
The only apparent difference is the "callback=jQuery..." parameter. Here is my JavaScript:
function generateUrl(term) {
(function ($) {
var apiKey = 'xxx';
var apiSecret = 'xxx';
var memberToken = 'xxx';
var memberSecret = 'xxx';
var action = 'GET';
var path = 'http://api.linkedin.com/v1/company-search';
var nonce = '1234';
var timestamp = Math.floor((new Date()).getTime()/1000);
var version = '1.0';
var args = "keywords=" + term;
// var format = 'json';
if (args != '') { args += '&'; }
args += "&oauth_nonce=" + nonce + "&oauth_timestamp=" + timestamp + "&oauth_version=" + version;
OAuthSimple().reset();
this.results = (new OAuthSimple()).sign({
path:path,
action:action,
parameters:args,
signatures:{
'consumer_key':apiKey, 'shared_secret': apiSecret,
'access_token':memberToken,'access_secret':memberSecret}
}
);
}
(jQuery));
return results.signed_url.slice(results.signed_url.indexOf('?') + 1);
}
$("#linkedin").select2({
placeholder: "Search for a company.",
minimumInputLength: 1,
allowClear: true,
ajax: {
url: 'http://api.linkedin.com/v1/company-search',
dataType: 'jsonp',
data: function (term, page) {
return generateUrl(term);
},
results: function (data, page) {
return { results: data.companies.values };
}
},
formatResult: companyFormatResult,
formatSelection: companyFormatSelection,
dropdownCssClass: "bigdrop_3"
});
function companyFormatResult(company) {
return company.name;
}
function companyFormatSelection(company) {
return company.name;
}
Could it have something to do with the syntax of my url parameters? I was having problems when the "keywords" parameter wasn't immediately after "company-search?" in the normal json request, but moving the callback parameter in the jsonp request to the end of the url doesn't seem to help.
Thank you in advance.

Categories

Resources