Helper Helper - 3 months ago 8
Ajax Question

Posting data via JQuery Ajax

I am facing issue in Posting data using JQuery. It works fine when I do it through Chrome Extension Postman.

My Code

var request = $.ajax({
url: 'http://pankajserver.in/api/SaveRoleApi',
type: "POST",
data: {Role : "wsed"},
async: true,
contentType: "application/json; charset=utf-8",
"X-Requested-With": "XMLHttpRequest"
});

request.done(function(msg) {
debugger;
});

request.fail(function(jqXHR, textStatus) {
debugger;
});



Url: http://pankajserver.in/api/SaveRoleApi

contentType: "application/json; charset=utf-8"

X-Requested-With: "XMLHttpRequest"


Works fine when posted data with Postman Chrome Extension. Screenshot below

enter image description here

Answer

Please try this

$.ajax({
    "async": true,
    "crossDomain": true,
    "url": "http://pankajserver.in/api/SaveRoleApi",
    "method": "POST",
    "headers": {
        "content-type": "application/x-www-form-urlencoded",
        "x-requested-with": "XMLHttpRequest",
    },
    "data": {
        "Role": "wsed"
    },
    success: function (msg) {
        debugger;
    },
    error: function (jqXHR, textStatus) {
        debugger;
    }
});

I see error in console Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://pankajserver.in/api/SaveRoleApi. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

for that please allow cross origin by placig this code in your root .htaccess

<IfModule mod_headers.c>
   Header set Access-Control-Allow-Origin "*"
</IfModule>

for more info to allow cros origin please refer this link

Comments