$http.get and $http.JSONP failed to get the google api response - javascript

I tried to get api response for "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true&region=USA" using angularjs $http .get method and $http.JSONP method. But it doesnt work properly it returns nothing. When i tried this api via REST client and browser , it provides the JSON data with status code 200.
Here is my code ...
index.html
<html ng-app="myApp">
<body ng-controller="MyCtrl">
<button ng-click="getlocation()">Get Location</button>
</body>
</html>
app.js
var app = angular.module('myApp',[]);
app.controller('MyCtrl', ['$scope','$http',function ($scope,$http) {
$scope.getlocation=function(){
$scope.method = 'JSONP';
$http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true&region=USA"}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
alert(JSON.stringify(data));
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
alert($scope.data+$scope.status);
});
}
}]);
while run this code in browser it returns nothing. Throws error.
Could you please help me to get out from this problem??

to work with jsonp in angular, you need... ?callback=JSON_CALLBACK passed to the get call..
e.g.
$http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true&region=USA&callback=JSON_CALLBACK"}).
read more about it here

The only problem your code has is that there isno such HTTP method as JSONP. In your case you need GET. So use this instead:
$scope.method = 'GET';
Demo: http://plnkr.co/edit/I6qAMbsvLwM3vgZFQa0S?p=preview

you have to change your request method from JSONP to GET.
$scope.getlocation=function(){
$scope.method = 'get';
$http({method: $scope.method, url: "http://maps.google.com/maps/api/geocode/json?address=Canada&sensor=true&region=USA"}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
alert(JSON.stringify(data));
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
alert($scope.data+$scope.status);
});
}
I have tested it from my side and its returns
Object {results: Array[1], status: "OK"}
Hope you get what you are looking for.

Related

HTTP JSONP request issue with $http in AngularJS

I get the bellow error when I try to use the JSONP method in angularJS.
Uncaught SyntaxError: Unexpected token : http://example.com/getSomeJson?format=jsonp&json_callback=angular.callbacks._0
What am I doing wrong here, this is my AngularJs controller with the http request:
UPDATED QUESTION DETAILS
See below with code snipit which reproduces my problem, I've commented some of the .js to illustrate what I've tried so far.
var app = angular.module('app', []);
app.controller('mainController', ['$http', 'mainService', function($http, mainService){
mainCtrl = this;
mainCtrl.test = "If you can see this the mainController works"
var promise = mainService.getJson();
promise.then(function (data)
{
mainCtrl.json = data;
});
}]);
app.service("mainService", function ($http, $q)
{
var deferred = $q.defer();
/*
// Method to Grab JSON that has CORs enabled:
// JSON resource with CORs enabled
var url = 'https://jsonplaceholder.typicode.com/posts/1';
$http({
method: 'GET',
cache: true,
url: url,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
}).
success(function(response) {
//your code when success
deferred.resolve(response);
console.log('HTTP CORS SUCCESS!');
}).
error(function(response) {
//your code when fails
console.log('HTTP CORS ERROR!');
});
*/
/* */
// Method to Grab JSON that has CORs enabled:
// JSON resources without CORs enabled
var url = 'http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json' // does not work?
// var url = 'http://samcroft.co.uk/json-data/sample' // this one works
$http({
method: 'jsonp',
url: url + '?callback=JSON_CALLBACK',
}).
success(function(response) {
//your code when success
deferred.resolve(response);
console.log('JSONP SUCCESS!');
}).
error(function(response) {
//your code when fails
console.log('JSONP ERROR!');
});
this.getJson = function ()
{
return deferred.promise;
};
});
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-route.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="mainController as mainCtrl">
<p>{{mainCtrl.test}}</p>
<hr />
<p>You should also see the JSON obeject below:</p>
{{mainCtrl.json}}
</body>
</html>
ORIGIONAL QUESTION DETAILS
app.controller('testController', ['$scope', '$http', function($scope, $http){
var url = 'http://example.com/getSomeJson';
$http({
method: 'JSONP',
url: url,
params: {
format: 'jsonp',
json_callback: 'JSON_CALLBACK'
}
}).
success(function(data) {
//your code when success
$scope.data = data;
console.log('SUCCESS!');
}).
error(function(status) {
//your code when fails
console.log('ERROR!');
});
}]);
When I look at the json in the chromes sources panel I see where the error is highlighted.
Any idea what I'm doing wrong? Or could it be an issue with how the API service is configured?
Here you go :-)
The code you tried with the jsonp request looks good but the url you used is not supporting the jsonp request, that's why you got an error.
If you try the same url with $http.get, it will work fine.
To support the jsonp call, the response should be wrapped with the JSON_CALLBACK () as below
JSON_CALLBACK ({ /* JSON */ })
Hence, I changed this to valid jsonp url and it worked!
https://angularjs.org/greet.php?callback=JSON_CALLBACK
You can try this url in the browser and see the response, how it is wrapped with JSON_CALLBACK ().
But if you try the below url, you can just see the json without any wrapping.
http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json?callback=JSON_CALLBACK
That's the difference to find whether the api supports jsonp.
Also, I have changed the service below with the same syntax as in another SO question answer,
https://stackoverflow.com/a/41030976/7055233
Working snippet:
var app = angular.module('app', []);
app.controller('mainController', ['$http', 'mainService', function($http, mainService){
mainCtrl = this;
mainCtrl.test = "If you can see this the mainController works"
var promise = mainService.getJson();
promise.then(function (data)
{
mainCtrl.json = data;
});
}]);
app.service("mainService", function ($http, $q)
{
var deferred = $q.defer();
var url = 'https://angularjs.org/greet.php';
//var url = 'http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json';
/*
// Method to Grab JSON that has CORs enabled:
// JSON resource with CORs enabled
var url = 'https://jsonplaceholder.typicode.com/posts/1';
$http({
method: 'GET',
cache: true,
url: url,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
}).
success(function(response) {
//your code when success
deferred.resolve(response);
console.log('HTTP CORS SUCCESS!');
}).
error(function(response) {
//your code when fails
console.log('HTTP CORS ERROR!');
});
*/
/* */
// Method to Grab JSON that has CORs enabled:
// JSON resource without CORs enabled
function getJson() {
// $http.jsonp(url + "?callback=JSON_CALLBACK"). // this does not work either
$http.jsonp(url + '?callback=JSON_CALLBACK').
then(function(response) {
//your code when success
deferred.resolve(response);
console.log('JSONP SUCCESS!');
}, function(response) {
//your code when fails
console.log('JSONP ERROR!');
deferred.reject(response);
});
return deferred.promise;
}
this.getJson = getJson;
});
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular-route.js"></script>
<!--<script src="app.js"></script>-->
</head>
<body ng-controller="mainController as mainCtrl">
<p>{{mainCtrl.test}}</p>
<hr />
<p>You should also see the JSON obeject below:</p>
{{mainCtrl.json}}
</body>
</html>
JSONP callback must be specified by jsonpCallbackParam
BREAKING CHANGE
You can no longer use the JSON_CALLBACK placeholder in your JSONP requests.
Instead you must provide the name of the query parameter that will pass the callback via the jsonpCallbackParam property of the config object, or app-wide via the $http.defaults.jsonpCallbackParam property, which is "callback" by default.
-- Added to AngularJS v1.6.0-rc.2
UPDATE
The OPs example code does not work because the http://run.plnkr.co API does not support JSONP.
JSONP is available only on some sites with an API that pre-date ACCESS-CONTROL headers.
For more information, see JSONP Demystified

How to acces XML data in response

I have this method
angular.module('RDash')
.controller("SipsCtrl", ['$scope','$http', function($scope, $http){
'use strict';
$http({
method: 'GET',
url: 'http://192.168.2.35/SIPSWS/SIPSWS.asmx/HelloWorld'
}).then(
//OK
function (response) {
$scope.btnCUPS = "Exito",
},
//KO
function (response) {
$scope.btnCUPS = "Error",
});
}]);
I have a server status 200 ok, but y donĀ“t see the response.
I should receive XML data response with the next structure
<string xmlns="http://tempuri.org/">Hola a todos</string>
How can I put de response in my view?
See if you are really getting the data by: console.log(response);
If you are, the generaly comes a data inside response, in the controller:
$scope.data = response.data;
In the view:
<div>{{data}}</div>

Angular http json request issue

Hello I have a simple question but I'm running into problems. I edited some code that I found on line. I'm trying to utilize an Angular http service to retrieve JSON data but it doesn't seem to be working
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
My code example is below
http://codepen.io/jimmyt1001/pen/dPVveN
You spelled wrong sucess should be success
CODE
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
you should use a service for this:
json.service('getJson', ['$http', function ($http) {
var promise = null;
//return service
return function () {
if (promise) {
return promise;
} else {
promise = $http.get('url');
return promise;
}
};
}]);
function MainCtrl($scope, getJson) {
getJson().success(function (data) {
$scope.json = data;
});
};
Remember to inject the service name in your controller.
tl;dr
It should be like this:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http)
{
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config)
{
$scope.posts = data;
})
.error(function(data, status, headers, config)
{
// log error
});
});
I.e. you're missing a dot (.) before success and your success is incorrectly typed (you type sucess).
Original
Your code should be structured like this:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
As explained in the docs.
Yours is like this:
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
Wherea you're missing a dot (.) before the success, and your success is spelled wrong (yours is sucess).
It's decent practice to copy existing demos until you're certain on how they're really setup. Also, use your developer tools to catch easy bugs like this.
It's also possible that your dropbox call is simply invalid, but if you fix your code accordingly then the error method should be able to catch it and you should be able to see the error.

asynchronous call in angular js

Hi all I am new to angular js,here I want to fetch the json from server to the controller so that I can handle the data,but whats happening here is the first alert -11 is called then alert 2 is called and in the end alert 1 is being called ,I read about promise so I tried it but still not working,I want it to happen one after another please help me .Thanks in advance
sampleApp.controller('firstpage', function ($scope, $q, $http, $templateCache, onlinedata, offlinedata) {
$scope.message = 'This is Add new order screen';
var defer = $q.defer();
defer.promise.then(function () {
$scope.method = 'POST';
$scope.url = 'http://ncrts.com/ncrtssales_compadmin/webservices/user_login';
$scope.fetch = function () {
$scope.code = null;
$scope.response = null;
alert($scope.response + 11) //alert11
$http({
method: $scope.method,
url: $scope.url,
cache: $templateCache
}).
success(function (data, status) {
$scope.status = status;
$scope.message = data;
alert($scope.message + 1) //alert1
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.fetch();
})
.then(function () {
alert($scope.message + 2); //alert 2
})
defer.resolve();
//alert($scope.remember)
});
You have to use the resolve and reject functions to handle the response with the promise. You can find more information about promise in the AngularJS documentation. I made a little change in your code to show you how you can achieve what you want.
sampleApp.controller('firstpage', function ($scope, $q, $http, $templateCache, onlinedata, offlinedata) {
$scope.message = 'This is Add new order screen';
var defer = $q.defer();
$scope.method = 'POST';
$scope.url = 'http://ncrts.com/ncrtssales_compadmin/webservices/user_login';
$scope.fetch = function () {
$scope.code = null;
$scope.response = null;
alert($scope.response + 11) //alert11
var defer = $q.defer();
$http({
method: $scope.method,
url: $scope.url,
cache: $templateCache
}).
success(function (data, status) {
//$scope.status = status;
$scope.message = data;
alert($scope.message + 1) //alert1
defer.resolve({
status: status,
message: data
});
}).
error(function (data, status) {
var data = data || "Request failed";
//$scope.status = status;
defer.reject({
status: status,
message: data
});
});
return defer.promise;
};
$scope.fetch().then(function (data) {
alert('Status: ' + data.status);
alert('Message: ' + data.message);
});
});
I am very confused by the formatting of your code. It may help you to write the asynchronous call in a service and then inject the service into your controller. Keeping that in mind, here is some general advice that I've learned regarding asynchronous calls and promises in AngularJS:
Your service should initially return a deferred promise. This promise
should then be resolved on success() of the asynchronous call.
After $http() returns, but before success() returns, you have an
unresolved promise. If you have code that you want to run after the
promise is resolved, you need to use then() to indicate that you
want to execute the code within the then() block once you've
received data (and resolved the promise).
Not using then() for this
situation will cause errors because you will be attempting to access
data that doesn't yet exist.
It seems from your code that you are aware of the necessary coding strategy for what you need, but it will always help to isolate asynchronous calls into services so that the framework can make your life easier. Good luck.

Sending JSON using $http cause angular to send text/plain content type

I just want to send the following JSONobjects to my API backend:
{
"username":"alex",
"password":"password"
}
So I wrote the following function, using Angular $http:
$http(
{
method: 'POST',
url: '/api/user/auth/',
data: '{"username":"alex", "password":"alex"}',
})
.success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});
I read in documentation for POST method that Content-Type header will be automatically set to "application/json".
But I realized that the content-type I receive on my backend (Django+Tastypie) api is "text/plain".
This cause my API to not respond properly to this request. How should I manage this content-type?
The solution I've moved forward with is to always initialize models on the $scope to an empty block {} on each controller. This guarantees that if no data is bound to that model then you will still have an empty block to pass to your $http.put or $http.post method.
myapp.controller("AccountController", function($scope) {
$scope.user = {}; // Guarantee $scope.user will be defined if nothing is bound to it
$scope.saveAccount = function() {
users.current.put($scope.user, function(response) {
$scope.success.push("Update successful!");
}, function(response) {
$scope.errors.push("An error occurred when saving!");
});
};
}
myapp.factory("users", function($http) {
return {
current: {
put: function(data, success, error) {
return $http.put("/users/current", data).then(function(response) {
success(response);
}, function(response) {
error(response);
});
}
}
};
});
Another alternative is to use the binary || operator on data when calling $http.put or $http.post to make sure a defined argument is supplied:
$http.put("/users/current", data || {}).then(/* ... */);
Try this;
$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post('/api/user/auth/', data).success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});

Categories

Resources