7

Consider this code:

$.ajax({
           url: "http://x.com/api/AnnouncementCategory/Save",
           type: "Post",
           success: function (data) {
               //Grab our data from Ground Control
               alert(data);
           },
           error: function (event) {
               //If any errors occurred - detail them here
               alert("Transmission failed. (An error has occurred)");
           }
       });

With above code we can post data cross domain an everything is ok. But when i use this code:

$.post(' http://x.com/AnnouncementCategory/Save')

I get this error:

OPTIONS http://x.com/AnnouncementCategory/Save Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers. jquery-1.9.1.js:8526 XMLHttpRequest cannot load http://x.com/AnnouncementCategory/Save. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.

I see the jquery source code:

function ( url, data, callback, type ) {
        // shift arguments if data argument was omitted
        if ( jQuery.isFunction( data ) ) {
            type = type || callback;
            callback = data;
            data = undefined;
        }

        return jQuery.ajax({
            url: url,
            type: method,
            dataType: type,
            data: data,
            success: callback
        });
    }

Jquery also use ajax in post. **I know what is my error and just want to know:**What is the difference between $.ajax with type: post and jquery post?

Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60

2 Answers2

2

jQuery's $.ajax method always sends the "x-requested-with" header for any cross domain requests, unlike the $.post. The error you are getting is because of the way external server is handling the external request. Please look here to get more info how the CORS (Cross Origin Resource Sharing – i.e. cross domain Ajax) is being handled. Also here you will find the similar problem and the solution.

Community
  • 1
  • 1
Patryk
  • 618
  • 7
  • 17
0

The simple answer to the question you have asked is, a shorthand version of $.ajax, as described in the documentation:

http://api.jquery.com/jQuery.post/

The docs do state that:

Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

The question that you didn't ask, but perhaps is what you would really like to ask, is "why does cross-domain request work for me using $.ajax with a simple POST type, but not with $.post?". For that you would probably need to provide a bit more information.

Adam Marshall
  • 3,010
  • 9
  • 42
  • 80