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.

2

1 Answer 1

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: *");
Sign up to request clarification or add additional context in comments.

6 Comments

This should be in the api or in the site? thank you for your answer
Is the API developed in php ?
The api is developed in C#
@mattias For ASP.net Web API you can use EnableCorsAttribute as described about halfway down this article msdn.microsoft.com/en-us/magazine/dn532203.aspx
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'],
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.