Access Wordpress ajax on external host - javascript

I'm building this HTML/JS app to turn into mobile with Phonegap that is based on my wordpress site (using its database, users, etc.).
So right now I have an index.html with a functions.js that tries to access a function created on my wordpress like
add_action('wp_ajax_nopriv_checking_email', 'checking_email');
what I want is to be able to access this with my JS code.
I've tried something like this:
jQuery.ajax({
type: 'POST',
url: 'http://myhost.com/wp-admin/admin-ajax.php',
data: { 'action': 'checking_email', 'email': 'email#example.com' },
success: function(request_data) {
console.log(request_data);
}
});
and I get
XMLHttpRequest cannot load http://myhost.com/wp-admin/admin-ajax.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
What can I do to access admin-ajax.php from an external host?

So, after testing a bit more I found that it was actually a pretty silly fix.
By changing the header on the server's script it allowed access to it from a different host.
header('Access-Control-Allow-Origin: *'); // for any host
header('Access-Control-Allow-Origin: myhost.com'); // specific host

Related

No 'Access-Control-Allow-Origin' header is present on the requested resource in simple html form

why this error is showing in my simple html form, I want to get xml data in my simple form to show news on my webpage, but this error is showing continuously, please help
$.ajax({
type: "GET",
url: "https://news.google.com/rss/search?q=Nigeria&hl=en-PK&gl=PK&ceid=PK:en",
dataType: "xml",
success: function(xml) {
console.log(xml)
}
});
It is up to the server that has the resource to allow cross origin access.
Probably there is API for what you are trying to do. API gets implemented by the resource owner and provides controlled access.
Or you can use RSS if there is one.
What you could potentially do is run your requests through a CORS proxy. For example:
$.ajax({
type: "GET",
url: "https://cors-anywhere.herokuapp.com/https://news.google.com/rss/search?q=Nigeria&hl=en-PK&gl=PK&ceid=PK:en",
dataType: "xml",
success: function(xml) {
console.log(xml)
}
});
You can see that this works by simply pasting this code snippet into the console.
This essentially bypasses the CORS issues for you. I would only recommend using this hosted version if you don't have a lot of traffic, otherwise you should host your own version of the CORS proxy.
This is because of CORS(Cross Origin Resource Sharing) policy implemented by browsers. Which means browsers doesn't allow certain requests to be sent from a domain to another domain. However this is not applicable to all type of requests.
Check this link to understand what all requests come under this policy
Inorder to make this work , the other server, in your case https://news.google.com, have to setup in such a way that it allows cross domain requests. This is achieved by servers telling the browser that it is ready to accept cross domain requests from your domain, by adding certain cors related headers. One such is Access-Control-Allow-Origin. But I am afraid you can't do it since you aren't the one managing this server.
Work-Around
Use your backend to send the request to google. So that your xhr request calls your server and your server calls google. No browser No Cors.
xhr---> yourdomain.com/news/get---> someotherdomain.com/news/get

Need to hardcode according to other domain configuration

I am trying to find the size of the file in another domain
when I paste the link in the text box and hit save I need to find the size of the file...now it's working for same domain URL
so what I am trying to do is hard code the values in my request.
for example, I hard coded type: "HEAD", to type:'GET' since the other domain was using type GET.
but now I am getting a new error. is there any way I can hard code domain too
Can you guys tell me how to fix it.
providing my code below.
https://jsfiddle.net/9k1cs9ou/
input http://www.pdf995.com/samples/pdf.pdf
Mixed Content: The page was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint. This request has been blocked; the content must be served over HTTPS.
request = $.ajax({
type: "HEAD",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
url: $("#fname").val(),
success: function () {
alert("Size is " + request.getResponseHeader("Content-Length"));
var resp = JSON.parse(response)
alert(resp.status);
// 10485760 -10MB
if(request.getResponseHeader("Content-Length") <= 10485760/2){
alert(request.getResponseHeader("Content-Length") <= 10485760/2);
Http access control or CORS will prevent access from other domains unless the header is presented on the destination not on origin.
For instance, if you have your app hosted on www.mysite.com and you try to fetch a document from https://stackoverflow.com it will block your request because your website www.mysite.com isn't allowed access ON https://stackoverflow.com.
HTTP Access Control (CORS)

How to set up CORS in an AJAX request

I have been working on a personal webapp and have hit a little snag. My API calls only work for some APIs and not for others. For the ones it doesn't work with I will usually get an error message like so.
XMLHttpRequest cannot load https://api.meetup.com/2/cities. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
After doing some research I know it is to do with CORS not being setup. I was wondering if it would be possible to set this up in the client when making an AJAX request. The current way I am doing this is like so
var handleRequest = function(request){
$.ajax({
type: "GET",
url: request,
success: function(data) {
var rawJSON = JSON.stringify(data, null, 2);
editor.setValue(rawJSON);
},
dataType: 'json'
});
The server you're trying to access has to grant you permission to access it. An IT admin has to provide you with a URL that grants you permission to hit their external server. The server you are trying to hit has to setup CORS. http://enable-cors.org/
According to their docs they support JSONP.
https://www.meetup.com/meetup_api/
This is your way around CORS.

slideshare oembed api and Access-Control-Allow-Origin

I'd like to embed a slideshare iframe based on its URL. http://www.slideshare.net/developers/oembed says I should be able to get a JSON object about the resource and within that is the embed code to use. E.g. if I open
Reference Link
in the browser, I get JSON. If I open the same via jquery
$.getJSON('http://www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/lyndadotcom/code-drivesworld12&format=json', function (obj) { console.log(obj) });
then I get
XMLHttpRequest cannot load http://www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/lyndadotcom/code-drivesworld12&format=json&callback=myFunction. No 'Access-Control-Allow-Origin' header is present on the requested resource.
Ideally I'd like to also control slideshare from an external link - which this page - http://www.slideshare.net/developers - says is possible if you follow the SlideShare Player API - which is a 404 page.
Googling for slideshare developer just links me to many shared slideshows, not actual help that exists or works ... grrr
When you try to load JSON from another domain, it fails because there is a domain boundary you can not cross.To avoid this, you have to use JSON with Padding. JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. Try this following code mate.Hope this might help you. :)
$.ajax({
type: "GET",
url: 'http://www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/lyndadotcom/code-drivesworld12&format=jsonp',
dataType: 'jsonp',
success: function (data) {
$('.dynamic').html(data.html);
}
});
Fiddle here

How to make an AJAX request to Dictionary.com's REST API using jQuery?

Dictionary.com provides absolutely no documentation on how to grab data from them. I'm trying to use jQuery's ajax requests, but those are not working.
They provide a URL through which I'm supposed to be able to use. I'll provide this below.
http://api-pub.dictionary.com/v001?vid=<VID>&type=random&site=dictionary
They also provide a key, which I assume that I place in the <VID> spot.
Could someone please tell me what I'm doing wrong with this? I'll provide the code I'm using below:
$("#btnGetData").click(function() {
$.ajax({
url: "http://api-pub.dictionary.com/",
type: "GET",
data: "v001?vid=<VID>&type=random&site=dictionary",
success: function() { alert("success") },
});
});
Could someone please tell me what I'm doing wrong?
You are not passing the data correctly. Also the request url is http://api-pub.dictionary.com/v001. Try this:
$("#btnGetData").click(function() {
$.ajax({
url: "http://api-pub.dictionary.com/v001",
type: "GET",
dataType: "jsonp", //For external apis
data: {"vid": <VID>,
"type":"random"
"site": "dictionary"},
success: function() {
alert("success") },
});
});
UPDATE: Maybe you're being blocked by the same origin policy as #thordarson note, in that case add:
dataType: "jsonp" to your ajax call.
Possibility 1
You don't have access to their API. According to their API page they're very selective about who they give access to their API.
We are selective about our API partners and approve use as well as
develop terms on a case-by-case basis. If you are interested in using
our API, please contact us directly [...].
Possibility 2
You're being blocked by the same origin policy. Browsers are generally very strict about requests made by JavaScript across different domains. This can be bypassed using Cross-origin resource sharing. This requires configuring the server you're requesting, so in this case it's not viable.
Your best bet would be to create a server-side script that requests the URL and then using AJAX to request the file.
Example in PHP, let's call this request_dictionary.php:
<?php
$vid = "Your API key";
$type = $_GET['type'];
$site = $_GET['dictionary'];
$request_url = "http://api-pub.dictionary.com/v001?vid=$vid&type=$type&site=$site";
echo file_get_contents($request_url);
?>
Note: You probably need to change this to fit your needs (error handling, 404s, caching etc.). This code is untested.
Then change your jQuery so that it requests your file.
$("#btnGetData").click(function() {
$.ajax({
url: "/request_dictionary.php",
type: "GET",
data: "type=random&site=dictionary",
success: function() { alert("success") },
});
});
Warning
Using an AJAX call without a proxy (as explained in possibility 2) will expose your API key. This is against Dictionary.com's API Terms of Service.
2.1 Dictionary.com will assign and deliver to your Customer Application an Application Key to access the API. All Calls must
contain such Application Key. The Application Key is uniquely
associated with each Customer Application and all versions, upgrades
and updates thereof. The Application Key is Confidential Information
as defined in these Terms and Conditions. You must maintain and keep
the Application Key in a secure, embedded manner not accessible by any
third party. The Application Key is fully revocable by Dictionary.com
at any time. Dictionary.com may block attempts to access the API with
an invalid or revoked Application Key.
I've updated the code in possibility 2 to conceal the API key by keeping it in the PHP file.
Update/Note: Simply passing dataType: 'jsonp' to enable cross-origin calls is not enough. The responding server needs to respond with an Access-Control-Allow-Origin header containing your domain (or a rule that includes your domain). Any configuration of this kind is out of your hand as the requester.
Update/Note 2: Upon investigating the returned headers from your request URL, I can see no evidence of Access-Control-Allow-Origin. This means that even if you had access to their API, you wouldn't be able to access it using AJAX. Full headers below:
GET /v001?vid=%3CVID%3E&type=random&site=dictionary HTTP/1.1[CRLF]
Host: api-pub.dictionary.com[CRLF]
Connection: close[CRLF]
User-Agent: Web-sniffer/1.0.44 (+http://web-sniffer.net/)[CRLF]
Accept-Encoding: gzip[CRLF]
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8[CRLF]
Accept-Language: en-US,en;q=0.8[CRLF]
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
Cache-Control: no-cache[CRLF]
Referer: http://web-sniffer.net/[CRLF]

Categories