linn
linn

Reputation: 81

My rest api works with curl,but fails in ajax

With curl my rest api works

curl -d "id=insertCustomer&customerName=Linoy&[email protected]&city=goa&address=test&country=INDIA"    http://localhost:7275

When we try it with ajax, its returning the status code as 200 ok.But no response

$.ajax({
    type: 'POST',
    url: 'http://localhost:7275',
    data: JSON.stringify({"id":"insertCustomer","Name":"LINOY","AGE":23}),
    success: function(data, textStatus, jqXHR){
        alert('Stock updated successfully Status: '+textStatus); },
    error: function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
    }
});

In Rest server, I have a httpd.conf file which redirect to Api.php which

contains the function insertCustomer

Upvotes: 0

Views: 3804

Answers (3)

Himanshu Shekhar
Himanshu Shekhar

Reputation: 314

Problem is of 'Access-Control-Allow-Origin' header that is required to be set in response of api from server side. But setting it to 'Access-Control-Allow-Origin : * ' is dangerous rather specify particular domains.

Upvotes: 1

linn
linn

Reputation: 81

Rest class has been included with the following code :

                    header('Access-Control-Allow-Origin: *');

This worked....:)

Upvotes: 2

Niko
Niko

Reputation: 6269

because you use JSON.stringify the resulting call (in curl) would look like:

curl -d '{"id":"insertCustomer","Name":"LINOY","AGE":23}' http://localhost:7275

So if your api really works with json, then the above call should work fine as well.

Based on your working curl call, it looks like the api does not accept json, but rather normal parameters. If that is the case then you need to adjust the ajax request and send a url-encoded parameter string instead:

$.ajax({
    type: 'POST',
    url: 'http://localhost:7275',
    data: "id=insertCustomer&Name=LINOY&AGE=23",
    success: function(data, textStatus, jqXHR){
        alert('Stock updated successfully Status: '+textStatus); },
    error: function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
    }
});

If the api function allows both, you might need to set a different content type in your request (without knowing the Api.php its impossible to know):

$.ajax({
type: 'POST'
contentType: 'application/json; charset=UTF-8',
....

Just try loosing the "stringify" and it should be fine.

Upvotes: 1

Related Questions