1

I am making an HTTP request in Angular JS.

This works fine in the browser and returns the data successfully. However, when I test on a device for Phonegap usage, it returns an error.

The data for the request is passed to a factory from a controller, below is an example of the code I am using to make the request.

HTML

<ul>
    <li ng-repeat="story in stories" ng-click="setUser(story.name)">
        <img ng-src="{{ story.img }}" width="120" height="108" />
            <div>
                <h2>{{ story.name }}'s Story</h2>
                <p>{{ story.title }}</p>
            </div>
    </li>
</ul>

This HTML calls the function setUser(story.name) on ng-click, which passes in the current name of the user in the ng-repeat.

CONTROLLER

$scope.setUser = function (story) {
    $scope.chosenStory = story;
    dataFactory.setUser($scope.chosenStory); // HTTP call
}

The controller above gets the value from the HTML's ng-click="setUser(story.name)" and sends it to a factory to make the HTTP request.

FACTORY

setUser : function (val) {
    window.alert(val);
    var username = val;
    window.alert(val);
    $http.get('./js/json/scenarios/' + username + '.json')
        .success(function (data) {
            window.localStorage.setItem("users", JSON.stringify(data));
            $location.path('/story');
        })
        .error(function (data, status) {
            window.alert(val);
            window.alert(data);
            window.alert(status);
        });
    },

In Google's console it logs the success content from the HTTP request. However, when I test on a device for Phonegap, it always returns the error content of the HTTP request. E.g. it always returns the window.alert from the error function of the HTTP request.

What I am doing wrong / not doing? Thanks in advance.

Alan
  • 362
  • 3
  • 9
  • 18
  • Did you find a solution ? I face the same problem here http://stackoverflow.com/questions/36985470/angularjs-ionic-return-404 – user1269586 May 02 '16 at 15:00

1 Answers1

1

I'm 99.9% sure this is because of cross domain ajax loading. Try to enable Access-Control-Allow-Origin as suggested here How to enable CORS in AngularJs or try enabling a whitelist for cross domain of your app as suggest here Phonegap-Javascript sending cross-domain ajax request

Ultimately, if nothing works and you control the service, you could try changing the response headers, but it's likely that one of those will make it for you.

Community
  • 1
  • 1
joe
  • 1,359
  • 14
  • 19