-2

My code is relatively simple. I have a URL, which is defined before the request is sent, I then have a $.get() request, which I expect to return back a JSON object. The code is below.

var url = "url"; //Removed for clarity

$.get(url, function (data) {
        alert("hi");
});

The url being used within the request is correct. I have copied and pasted the code into my browser and I receive the response that I expect from the endpoint.

However when this JQuery code is executed, the callback function is not called and the alert is not fired. Why is this happening?

Edit: Forgot to post the error message I found in the console.

I'm receiving this:

2Initial%20Loan#:1 Access to XMLHttpRequest at 
'-snip url-' from 
origin 'https://localhost:44358' has been blocked by CORS policy: No 
'Access-Control-Allow-Origin' header is present on the requested resource.

Will it have anything to do with the GET request not working?

Jake12342134
  • 1,539
  • 1
  • 18
  • 45

2 Answers2

0

There might be some problem with the url. The syntax specified by you is correct and the same is checked

var url = "https://jsfiddle.net/"; //Removed for clarity

$.get(url, function (data) {
    alert("hi");
});

working code

user979331
  • 11,039
  • 73
  • 223
  • 418
  • As mentioned in the OP, the URL is correct and returns a 200 and JSON data. – Jake12342134 Jan 16 '19 at 11:34
  • as per your OP, the server from which you are requesting data does not allow request for another server. Check this https://stackoverflow.com/questions/25923796/cors-error-with-jquery for more info – Gaurav Desai Jan 16 '19 at 11:38
0

This is a classic example of CORS, which stands for Cross origin resource sharing. Browsers prevent sending AJAX request to domain other than where the javascript file originated from.

As the error message says you have to set 'Access-Control-Allow-Origin' http response header from your server code. Read more about CORS here [enter link description here CORS MDN

recnac
  • 3,744
  • 6
  • 24
  • 46
Nirbhay Jha
  • 491
  • 5
  • 13