0

I've searched the web and it seems like a lot of people have had this issue but I don't seem to have the same problem that I can find anyone else. The thing is that the code below works if I change the url to https://jsonplaceholder.typicode.com/posts/1 but it doesn't seem to work on my web api project. It doesn't work on the hosted one either.

I've set a debugger inside the api project but it won't get hit. If i call it from postman it works fine. So I seem to be able to make requests from this ajax call to another url. And I can also recieve requests to the api from postman. It's just from the site -> api that doesn't work for some reason.

Question:

Anyone got any clue why this will return error code 0 from my site calling my web api? Any help or input is highly appreciated, thanks!

$("#testbutton").click(function () {

$.ajax({
    type: "GET",
    url: "http://localhost:44834/api/test",
    dataType: "json",
    success: function(data) {
          alert(data); 
    },
    error: function (response) {
        alert("error " + response.status);
    }
});

return false;
});

EDIT

Enable CORS in Web API 2 helped me sort it out.

Mattias
  • 2,929
  • 5
  • 29
  • 46

1 Answers1

1

It seems like header issue. Its related to CORS. If you will put the following line to your main entry file like with php, index.php then your calls with ajax would work.

header("Access-Control-Allow-Origin: *");
Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33
  • This should be in the api or in the site? thank you for your answer – Mattias Jul 22 '17 at 12:02
  • Is the API developed in php ? – Himanshu Upadhyay Jul 22 '17 at 12:10
  • The api is developed in C# – Mattias Jul 22 '17 at 12:13
  • @mattias For ASP.net Web API you can use EnableCorsAttribute as described about halfway down this article https://msdn.microsoft.com/en-us/magazine/dn532203.aspx – Crowcoder Jul 22 '17 at 12:17
  • Oh, sorry, you have already written it. Well, you have to write that line of code in the very first file where the request hits first. And you also should try to put following header. The syntax of php but you can find relevant for c# 'allowedHeaders' => ['Content-Type', 'X-Requested-With'], – Himanshu Upadhyay Jul 22 '17 at 12:19
  • @HimanshuUpadhyay You pointed me in the right direction, it was due to the access-control.allow-origin. Thank you! will mark as correct since it solved my problem – Mattias Jul 23 '17 at 06:00