Fetching data through ajax using jQuery - ajax

I have two pages in different server.
Through ajax I would like to include some data: here is an example: link
The link is working through browser.
jQuery(window).ready(function() {
getPageWithAjax("http://www.betcatcher.com/index.php?page=valuebets&nr_row=6");
function getPageWithAjax(page)
{
//alert(page)
ajaxRequest = $.ajax(
{
url: page,
cache: false,
success: function(msg){ajaxResponse(msg)},
error: function(msg){ajaxResponse('Error loading data.'+msg.status)}
});
}
function ajaxResponse(msg)
{
$("#live_bet_ajax_content").html(msg);
}
});
But I'm getting error when I'm trying to get data.

I assume, that you call script from different domain. You should use JSONP which supports cross-domain calls. Read this article how to do this.

looks to me like a Same-Origin Policy problem. For new browsers you could enable Cross-Origin Resource Sharing (CORS) http://enable-cors.org/ for old browser you probably need to build a serverside proxy which rewrites the requests.

Related

Vue.js + Vue Resource No 'Access-Control-Allow-Origin'

Cross site ajax request with Vue.js 1.0 and Vue Resource. I get the following error: XMLHttpRequest cannot load http://dev.markitondemand.com/MODApis/Api/v2/Lookup/jsonp?input=NFLX&callback=handleResponse. No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have a basic understanding of the problem but not sure how to add a callback function with the request or if that is the best solution for this example. I put in the full request URL here just to make it easier to follow.
new Vue({
el: '#stockList',
data: function() {
return {
query: '',
stocks: []
};
},
ready: function() {
this.getStocks();
},
methods: {
getStocks: function() {
this.$http.get('http://dev.markitondemand.com/MODApis/Api/v2/Lookup/jsonp?input=NFLX&callback=handleResponse',
function(data) {
this.stocks = data;
}
);
}
}
})
I have almost zero understanding of networking, but I was able to get several remote apis to work using:
this.$http.jsonp
instead of
this.$http.get
"No Access-Control-Allow-Origin" header usually is a problem with the server. It means that the server is configured to only allow a person access to the API if the request comes from the same domain as the server. You either need to run the script from the website that you are requesting data from, or you need to change the server config to allow access to all domains.
If you don't have access to the server, and you don't want to run the script in the browser, then I think what you could do is use a headless browser like PhantomJS to navigate to the page, insert a script element into the dom that contains you script, execute the function and then return the data from the API. I could write the code out for you, but to be honest, it's a bit complex. You would have to know how to use node.js, and phantom.js. I've personally only used phantom.js for the Node 'html-pdf' package, but I'm sure with a little bit of reading you could figure out how to do it.
Set your local environment to http instead of https if you have no control over dev.markitondemand.com.

Ajax in Phonegap not working

I know this question has been address many times on Stack Overflow, but none of the solutions are working for me.
I can't get ANY ajax requests to complete within my phonegap application when running on the device (Android 4.4.2), yet everything works fine from desktop browsers.
First I tried AngularJS $http
Then I tried jQuery .get
Then I tried raw xhr
In all cases, the request immediately fails with no response. I've tried requesting data from my own servers, and from google servers, and elsewhere, all the same. I've tried whitelisting my domains in config.xml, in many forms, still no effect. I've even opened the console, and manually created an XHR and tried to GET on it, and the same thing happens. The request immediately fails. If anyone can please help me out, that would be great. I'm on the latest version of pretty much all my software, having set up my dev environment just today.
Cross domain request headaches. The browser allows the cross domain request but phonegap on the device kills it. I've been there and it took some work getting used to dealing with it. Try using jquery and jsonp in an ajax get request.
Try adding <access origin="*" /> to your config.xml for testing.
Here's an example of an jquery ajax request taken from working code.
$.ajax({
timeout: 5000,
url: 'https://yourdomain.com/yourfile.php',
dataType: "jsonp",
jsonpCallback: 'yourcallbackfunction',
type: "GET",
crossDomain: true,
data: {'somedata':'your data string'},
error: function(xhrObj,text,errorObj){
if(xhrObj.status !== 200) {
var errorTxt='Error Log: ';
errorTxt=errorTxt+"Error code specific:'"+xhrObj.status+"'\n";
errorTxt=errorTxt+"Error status specific:'"+xhrObj.statusText+"'\n";
errorTxt=errorTxt+"Error code general:'"+text+"'\n";
errorTxt=errorTxt+"Error status general:'"+errorObj.message+"'\n";
console.log(errorTxt);
}
}
});
function yourcallbackfunction(data) {
// do cool stuff here
console.log(data);
}
Be sure to handle the headers on your servers response so that the response gets back to your client. Here's a sample processing function I used to return data. Sorry if php isn't your server side scripting language but hopefully you'll get the idea.
`function SendResults($data) {
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
header("content-type: application/json");
$callback = filter_input(INPUT_GET, 'callback', FILTER_SANITIZE_SPECIAL_CHARS);
echo "$callback(" . json_encode($data) . ")";
}`
Good luck.. Hope this helps you.

ajax from same site as JS reference file?

I have a JS file running on my site, it works fine.
Now I want to put on another site with the full url of the script back to my site.
<script src="http://www-js.mydomains.com/some/path/file.js"></script>
now is it really still cross domain to an xml request on my server?
so in the file.js I have something like
dojo.xhrGet({url: '/some/path/file.xml', sync: true, handleAs: 'xml', error: function(result,args){alert(result.responseText+'-'+args.responseText)}, load: function(result){ ....
this just dies on other sites (great dojo response of undefined)... is there away around it
I think you should use "script" dojo/request/script instead of xhr.
require(["dojo/request/script", "dojo/dom", "dojo/dom-construct", "dojo/json", "dojo/on", "dojo/domReady!"],
function(script, dom, domConst, JSON, on){
on(dom.byId("startButton"), "click", function(){
domConst.place("<p>Requesting...</p>", "output");
script.get("helloworld.jsonp.js", {
jsonp: "callback"
}).then(function(data){
domConst.place("<p>response data: <code>" + JSON.stringify(data) + "</code></p>", "output");
});
});
});
http://dojotoolkit.org/reference-guide/1.9/dojo/request/script.html
now is it really still cross domain to an xml request on my server?
Yes. The origin is based on the URI of the HTML document hosting the script, not the URI the script was sourced from.
You should send the HTTP headers defined in the CORS specification to allow other sites to use your script (or their own scripts) to access content on your server.
Additionally, URIs accessed by JS are also relative to the document and not the script, so you will need to use an absolute or scheme relative URI instead of the server root relative URI you are presently using.

jQuery ajax POST from local file to access a cross domain not working

As the title says, I'm trying to access (POST) using jQuery AJAX call to a web url, http://host:port/... or http://localhost:8080/... from a local HTML file, c:\home.html. I can't get it to work.
I did Google and also saw several questions here but I can't get it to work. I need some help here. Here is what I've tried so far.
dataType: jsonp
crossDomain: true
Setting the header in my response:
response.setHeader("Access-Control-Allow-Origin", "*");
None of the three browsers are working - IE, FF or Chrome. The request is never reaching the server. Here are some of the errors I'm seeing.
No Transport (IE) if not jsonp is used.
NS_BINDING_ABORTED / Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED) in FF
This is my code. I would appreciate any help. I'm using jquery-1.8.2.min.js.
var http_host = "http://localhost:8080";
function su (pc, p) {
var suUrl = http_host + "/ps/api/v2/authorize.json";
$.ajax({
type: 'POST',
url: suUrl,
data: {
phone_cell: pc,
password: p,
},
dataType: "json",
crossDomain: true,
success: osu,
error: oe
});
return false;
}
function osu (d) {
console.log(d);
}
function oe(xhr, ts, et) {
alert("ServerError: " + et);
}
An example would be a perfect pointer.
I suppose my code got messed up w/ all the different solutions that I was trying. I was finally able to get it to work w/ setting the header (solution that was recommended and worked for others). All that I had to do to get it to work is add the following to my REST service response.
response.setHeader("Access-Control-Allow-Origin", "*");
Update:
I thought I figured this out but I've not. There is more it than just setting the header. Anyways, in my specific situation. I was trying to run my app (html, js) off of the hard drive specifically on chrome and trying to access web services available on the cloud.
Here is how I finally solved the problem. I started the chrome w/ the following parameters.
--disable-web-security -–allow-file-access-from-files
Like I mentioned earlier, this app is really a desktop application that will be run as part of the chromium embedded framework.
Thanks every one for your input.
You can't make a cross-domain request from a local file because it's not on a domain. You need to host C:\home.html on a local webserver instance in order for it to work.

AJAX/JSONP Question. Access id denied using IE while requesting corss domain

Ok, Here we go. I have already searched the Stack for the answer i have found some useful info but i want to clear up some more things. I also search the net for the answer but no real help.
I have worked with some api (yelp, ouside.in). In yelp i use to inject the script to head with the url request to the api with a callback funcion. I worked fine in all browsers. But while using outside.in api when i call the url the callback in not working.
In yelp they have a url field can be used like that callback=callbackfuncion so the callback will automatically called.
But in outside.in there is not such field available. Is there are any standard command for callback function which will work regardless of any server/api?
I also tried a standard ajax request using jQuery $.ajax() function. It worked for my local pc for both IE and other browser but did not working in IE showing the error: access denied, other borwser seems ok. Firebug in my FF also don't notice any errors.
Outside.in has an javascript example but it is too hard to me to understand
github.com/outsidein/api-examples/tree/master/javascript/browser/
site i am working: http://citystir.com
yelp: yelp.com
outside.in: outside.in
Techniqual info:
i am using: wampserver in local, wordpress for hosting, Godaddy, apache for remote with linux.
Codes:
Using Jquery $.ajax
url is like: "http://hyperlocal-api.outside.in/v1.1/states/Illinois/cities/chicago/stories?dev_key="+key+"&sig="+signeture+"&limit=3
function makeOutsideRequest(url){
$.ajax({
url: url, dataType: 'json', type: 'GET',
success: function (data, status, xhr) {
if (data == null) {
alert("An error occurred connecting to " + url +
". Please ensure that the server is running and configured to allow cross-origin requests.");
}else{
printHomeNews(data);
}
},
error: function (xhr, status, error) {
alert("An error occurred - check the server log for a stack trace.");
}
});
}
Thanks!
This question was asked in the Outside.in developer forums this morning as well (presumably by the same person). Here's a link to that discussion: http://developers.outside.in/forum/read/97053
To summarize, the Outside.in API does not support JSONP, but CORS support is included in the next release of the API, which will hit in the near future.

Resources