72

I'm writing a simple site that takes as input an idiom, and return its meaning(s) and example(s) from Oxford Dictionary. Here's my idea:

I send a request to the following URL:

http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=[idiom]

For example, if the idiom is “not go far”, I'll send a request to:

http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=not+go+far

And I'll be redirected to the following page:

http://www.oxfordlearnersdictionaries.com/definition/english/far_1#far_1__192

On this page, I can extract the meaning(s) and the example(s) of the idiom.
Here's my code for testing. It will alert the response URL:

<input id="idiom" type="text" name="" value="" placeholder="Enter your idiom here">
<br>
<button id="submit" type="">Submit</button>
<script type="text/javascript">
$(document).ready(function(){
    $("#submit").bind('click',function(){
        var idiom=$("#idiom").val();
        $.ajax({
            type: "GET",
            url: 'http://www.oxfordlearnersdictionaries.com/search/english/direct/',
            data:{q:idiom},
            async:true,
            crossDomain:true,
            success: function(data, status, xhr) {
                alert(xhr.getResponseHeader('Location'));
            }
        });
        
    });
});
</script>

The problem is I've got an error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=by+far. This can be fixed by moving the resource to the same domain or enabling CORS.

Can anybody tell me how to resolve this please?
Another approach is fine too.

wittich
  • 2,079
  • 2
  • 27
  • 50
Newbie
  • 939
  • 1
  • 8
  • 14

12 Answers12

29

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. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on script tags. Note that for JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results.

http://en.wikipedia.org/wiki/JSONP

Good answer on StackOverflow: jQuery AJAX cross domain

$.ajax({
  type: "GET",
  url: 'http://www.oxfordlearnersdictionaries.com/search/english/direct/',
  data:{q:idiom},
  async:true,
  dataType : 'jsonp',   //you may use jsonp for cross origin request
  crossDomain:true,
  success: function(data, status, xhr) {
    alert(xhr.getResponseHeader('Location'));
  }
});
xxx
  • 1,153
  • 1
  • 11
  • 23
G.F.
  • 779
  • 10
  • 17
  • 7
    jsonp should not be encourage since it's vulnerable to cross site attacks. Any server implementing jsonp now days are a fool for not using CORS headers – Endless Sep 13 '16 at 15:37
  • This didn't work for me. Instead of getting a CORS error, this code just gives me a 401 unauthorized error. – Cerin Nov 25 '20 at 21:19
19

Place below line at the top of the file which you are calling through AJAX.

header("Access-Control-Allow-Origin: *");
Brian Burns
  • 20,575
  • 8
  • 83
  • 77
AndyPHP
  • 361
  • 2
  • 5
11

We can not get the data from third party website without jsonp.

You can use the php function for fetch data like file_get_contents() or CURL etc.

Then you can use the PHP url with your ajax code.

<input id="idiom" type="text" name="" value="" placeholder="Enter your idiom here">
<br>
<button id="submit" type="">Submit</button>
<script type="text/javascript">
$(document).ready(function(){
    $("#submit").bind('click',function(){
        var idiom=$("#idiom").val();
        $.ajax({
            type: "GET",
            url: 'get_data.php',
            data:{q:idiom},
            async:true,
            crossDomain:true,
            success: function(data, status, xhr) {
                alert(xhr.getResponseHeader('Location'));
            }
        });

    });
});
</script>

Create a PHP file = get_data.php

<?php
  echo file_get_contents("http://www.oxfordlearnersdictionaries.com/search/english/direct/");
?>
Raju Singh
  • 750
  • 8
  • 21
10

Is your website also on the oxfordlearnersdictionaries.com domain? or your trying to make a call to a domain and the same origin policy is blocking you?

Unless you have permission to set header via CORS on the oxfordlearnersdictionaries.com domain you may want to look for another approach.

jsmartfo
  • 975
  • 7
  • 8
  • 1
    My site is not on the same domain with oxfordlearnersdictionaries.com and I don't know any way to getdata from that site but this – Newbie May 31 '14 at 00:37
  • 1
    then its not really possible - if your not on same domain and you cannot set webserver header/CORS, there are some workarounds/hacks see here for an example [iframe x-domain](http://stackoverflow.com/questions/1378433/how-do-i-implement-cross-domain-url-access-from-an-iframe-using-javascript) – jsmartfo Jun 02 '14 at 21:23
  • This said, if the server of your site can perform the request instead of the browser, and pass the results to the browser, you can work around this limitation. – Joseph Van Riper Apr 12 '23 at 11:20
8

add these in php file where your ajax url call

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
Er Sahaj Arora
  • 852
  • 8
  • 13
4

Add the below code to your .htaccess

Header set Access-Control-Allow-Origin *

It works for me.

Thanks

Shafiq
  • 963
  • 8
  • 4
3

If your website also on the oxfordlearnersdictionaries.com domain, USE the following into the oxfordlearnersdictionaries.com .htaccess file:

<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin "*"
</IfModule>
xxx
  • 1,153
  • 1
  • 11
  • 23
Nikhil Gyan
  • 682
  • 9
  • 16
1

This also need.

<?php
header("Access-Control-Allow-Origin: *");
Jay Bharat
  • 691
  • 7
  • 6
1

I used the header("Access-Control-Allow-Origin: *"); method but still received the CORS error. It turns out that the PHP script that was being requested had an error in it (I had forgotten to add a period (.) when concatenating two variables). Once I fixed that typo, it worked!

So, It seems that the remote script being called cannot have errors within it.

Arya
  • 566
  • 2
  • 9
  • 22
0

I had the same problem when I was working on asp.net Mvc webApi because cors was not enabled. I solved this by enabling cors inside register method of webApiconfig

First, install cors from here then

public static void Register(HttpConfiguration config)
{
  // Web API configuration and services

  var cors = new EnableCorsAttribute("*", "*", "*");
  config.EnableCors(cors);

  config.EnableCors();
  // Web API routes
  config.MapHttpAttributeRoutes();

  config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
  );
}
xxx
  • 1,153
  • 1
  • 11
  • 23
TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66
0

I think setting your header to Access-Control-Allow-Origin: * would do the trick here. Had the same issue and I resolved it like that.

Vu Tuan Hung
  • 167
  • 1
  • 4
0

More safer way to use

Access-Control-Allow-Origin: https://myrequestingwebsite.com

There is a nice article here

Avoid using Access-Control-Allow-Origin: * you are exposing to everyone

Khalid Lakhani
  • 179
  • 2
  • 10