iamjustcoder
iamjustcoder

Reputation: 4852

Access-Control-Allow-Origin error sending a jQuery Post

I read lot of the forums for "Access-Control-Allow-Origin" issue. Most of the forum asks to use dataType:'jsonp', but typically jsonp will hit GET request, i want to do POST request. Eventually GET request also not works.

Actually i converting iPhone app to PhoneGap, so re-writing objective-c code to HTML-5 & Jquery mobile. The url which i am trying to hit works very well in objective-c.

Here is objective-c code

NSString *username=[self urlEncodeValue:[userNameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSString *password=[self urlEncodeValue:[passWordField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSString *params = [[NSString alloc] initWithFormat:@"username=%@&password=%@",username,password];

NSData *paramData = [params dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[params release];
NSString *paramsLength = [NSString stringWithFormat:@"%d", [paramData length]];

NSString *urlString=[[NSString alloc] initWithFormat:@"%@?",[dict valueForKey:@"LoginAuthentication"]];

NSURL *authURL = [NSURL URLWithString:urlString];
[urlString release]; 

NSHTTPURLResponse *authenticationResponse= nil; 
NSMutableURLRequest *authenticationRequest = [NSMutableURLRequest requestWithURL:authURL];
[authenticationRequest setHTTPMethod:@"POST"];
[authenticationRequest setValue:paramsLength forHTTPHeaderField:@"Content-Length"];
[authenticationRequest setHTTPBody:paramData];
NSError *error = nil;
int errorCode;

NSData *responseData = [NSURLConnection sendSynchronousRequest:authenticationRequest  
          returningResponse:&authenticationResponse 
             error:&error]; 

if ([authenticationResponse respondsToSelector:@selector(allHeaderFields)]) {
    //success
}

The above code works very well.

Here's the code which i converted to javascript which gives "Access-Control-Allow-Origin" error

$(document).ready( function() {
    $.ajax({
        type: "POST",
        crossDomain: true,
        //dataType:'jsonp',
        //callback: '?',
        url : "https://externalserver.com/loginAuth?", 
            data : {'username' : 'username', 'password' : 'password'},
        success : function (response) {
            alert('login failed');
        }, 
        error: function(e){
            console.log(e);              
        }
    });
});

I tried with GET/POST request, and tried to run this local file in some local server. Nothing works.

I am getting below error message

XMLHttpRequest cannot load https://externalserver.com/loginAuth?. Origin null is not allowed by Access-Control-Allow-Origin.

XMLHttpRequest cannot load https://externalserver.com/loginAuth?. Origin null is not allowed by Access-Control-Allow-Origin.

Upvotes: 1

Views: 4919

Answers (2)

codemonkey
codemonkey

Reputation: 5267

A PhoneGap app is treated as a mobile app, not a browser so cross-origin is fine. You need to change your server code to add this header

Access-Control-Allow-Origin: *

This will allow null origins which is what the PhoneGap request gets sent as. This should work for both GET as well as POST requests without needing to use JSONP.

Upvotes: 1

Gajotres
Gajotres

Reputation: 57309

Browsers do not allow you to request resources from another domain (images and script files are the notable exceptions to this rule).

This can be solved in few ways.

  1. First way is by using JSONP call (the current standard for cross-domain access), and yes JSONP only allows GET. But this is just a part of the solution. Server side also needs to be changed to allow cross domain calls.

    In order to be able to access an external resource from javascript. The remote resource MUST include access-control-allow-origin in the response header. If you have control over that resource, you need to add this response header to * (or your domain if you want a more restricted access control). Of course this part od solution will depent on your server side architecture (PHP, ASP.NET, JSP ...)

    Here's a PHP/jQuery solution described in details: http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/

    Also return result must be wrapped into jsonpCallback function, so return should look liek this:

    someFunction("{...}");
    

    someFunction is the name of callback function and classic JSON is {....}. You can see, it is wrapped with someFunction(.

    jQuery side should look like this:

    $.ajax({url: server_url,
        type: "GET",       
        data: save_data,
        dataType: "jsonp",
        jsonpCallback: 'successCallback',
        async: true,
        beforeSend: function() {
    
        },
        complete: function() {
    
        },
        success: function (result) {
    
        },
        error: function (request,error) {
    
        }, 
        successCallback:function(){
    
        }
    });
    

    http://devlog.info/2010/03/10/cross-domain-ajax/

  2. Or a Proxy solution. I am not going to write about it because I never tested it. Use this solution only if you don't have access to server side code:

    http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html http://developer.yahoo.com/javascript/howto-proxy.html

Upvotes: 1

Related Questions