jsonp Unexpected token : (backbone) - backbone.js

I am trying to do api call from my localhost to a different domain (https://xyz)
my solution:
<script> // ajax prefilter
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.crossDomain ={
crossDomain: true
};
options.xhrFields = {
withCredentials: true
};
options.url = 'https://xyz' + options.url;
});
</script>
<script> // collection
var KCollection = Backbone.Collection.extend({
url: '/api/s/y/',
});
</script>
<script> // view
var DataAgesView = Backbone.View.extend({
render: function(){
var that = this;
mycollecion = new KCollection();
mycollecion.fetch({
dataType: 'jsonp',
success: function(){
console.log('success!');
},
error: function() { console.log('Uh Oh!'); },
})
}
});
</script>
This will send a GET request to "https://xyz/api/s/y"
and I can see the data came back to my browser by looking at the dev tool/network.
But there is this error: Uncaught SyntaxError: Unexpected token :
I am very new to web and backbone.js. I used jsonp to just be able to call cross domains, and I am open to use any other solutions for that (as long as I understand it).
Note that my server returns "json" and I can not change anything from server side.

Related

How to make a loading (spin) while requesting to server by $http on angularJS

$http({
method: 'POST',
url: '',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
if(response.data == 'true'){
swal("Good job!", "New case has been created", "success");
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I want to show a progress bar or spin on bootstrap while http request on angularjs
Sugessting you to use this angular-loading-bar
Steps
Include the script references and css as mentioned in the above
github, you can use cdn as well as mentioned.
Add these two functions in your controller
$scope.start = function() {
cfpLoadingBar.start();
};
$scope.complete = function () {
cfpLoadingBar.complete();
}
Include the 'angular-loading-bar', 'ngAnimate' as dependencies.
Add the below code for the app configurations
If you are looking for the progress bar
app.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
cfpLoadingBarProvider.includeSpinner = false;
}])
If you are looking for a spinner
app.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
cfpLoadingBarProvider.includeSpinner = true;
}])
Finally, In your $http request call the $scope.start() function and in your success method call the $scope.complete()
LIVE DEMO
A simple way:
html:
<div class="spinner" ng-show="loading"></div>
js :
$scope.loading = true
$http.post(...).then(function(response){
$scope.data = response.data // or whatever you needs...
$scope.loading = false
},function(){
$scope.loading = false
console.log("error")
})
If you want to generalize, you can also have a look to http interceptor : https://docs.angularjs.org/api/ng/service/$http#interceptors

AngularJS Request payload is always empty

I have created a Angular resource that sends POST data to a web service. Here is my factory:
appServices.factory('Foo', function($resource) {
var data = $resource(
'http://localhost:3000/api/v1/foo.json',
{},
{
'save': {
method: 'POST',
cache: false
}
});
return data;
});
Here's my Controller:
appControllers.controller('FooCtrl', function($scope, Foo, $location) {
$scope.memberData = {};
$scope.create = function() {
var member = new Foo();
member.$save( {}, { bar: bar });
$location.url("/");
};
});
When I submit the form in my client, it returns a 500 status. Looking into Firebug, I can see that my POST data payload always remains empty for some reason.
What am I doing wrong?
PS. I've added this to my config: $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
If you want to issue a POST request to the member resource, you can use save() (without the $) and pass in your body as the first argument:
Foo.save({bar: 'bar'}, function () {
// Callback
});
However, when creating a new resource instance, it is augmented with a $save() method (note the $). When you invoke this method, the instance itself is sent as the body. So you should change your code to:
var member = new Foo();
member['bar'] = 'bar';
member.$save(function () {
// Callback
});
Check this article for more information.

Error in Success callbackId ... ReferenceError: Can't find variable: $http

I am trying to build a hybrid mobile app with ionic (angular). For this app, I am making an oAuth call which is jQuery dependent so have both libraries loaded, as well as the script for the oAuth and my and my app.
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="cordova.js"></script>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/auth.js"></script>
<script src="js/app.js"></script>
The call to initiate the authentication is done in the ionic ready event in app.js as shown below:
$ionicPlatform.ready(function(){
oAuthProcess.authorize({
client_id: 'client',
client_secret: 'secret',
scope: 'scope',
redirect_uri: 'fake url'
}).done(function(data){
localStorage.setItem('accessToken', data.access_token);
localStorage.setItem('refreshToken', data.refresh_token);
var accessToken = localStorage.getItem("accessToken");
alert(accessToken);
}).fail(function(data){alert(data.error);});
});
The oAuthProcess function is in the auth.js file which looks like below. It opens the inAppBrowser to perform the authentication and should then close it returning the access token to the app to allow calling APIs:
var oAuthProcess = {
authorize: function(options) {
var deferred = $.Deferred();
var authUrl = 'some url' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
//Open inAppBrowser with authUrl
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');
authWindow.addEventListener('loadstart', function(e) {
var url = '' + e.url + '';
//Upon opening in
var code = url.match(/\?code=(.+)$/);
var error = url.match(/\?error=(.+)$/);
if (code != null || error != null) {
authWindow.close();
}
if (code) {
$http({
method: 'POST',
url: 'some url',
data: {code: code[1], client_id: options.client_id, client_secret: options.client_secret, redirect_uri: options.redirect_uri, grant_type: 'authorization_code'}
}).success(function(data) {
deferred.resolve(data);
}).error(function(data){
deferred.reject(response.responseJSON);
});
} else if (error) {
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
The app is able to load the inAppBrowser and create a token, however the following error is given which stops the token from getting back to the app after the inAppBrowser is closed.
2015-01-09 16:48:04.299 myApp[2146:483400] Error in Success callbackId: InAppBrowser85303841 : ReferenceError: Can't find variable: $http
Any help is resolving this or an alternative approach will be very much appreciated.
Thanks in advance.
I'll just type it here so I can show you the code example rather than comment...
Assuming the example you gave is your entire auth.js file, add that example PSL gave you, so the file now looks like this:
var $http = angular.injector(['ng']).get('$http');
var oAuthProcess = {
authorize: function(options) {
var deferred = $.Deferred();
var authUrl = 'some url' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
//Open inAppBrowser with authUrl
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');
authWindow.addEventListener('loadstart', function(e) {
var url = '' + e.url + '';
//Upon opening in
var code = url.match(/\?code=(.+)$/);
var error = url.match(/\?error=(.+)$/);
if (code != null || error != null) {
authWindow.close();
}
if (code) {
$http({
method: 'POST',
url: 'some url',
data: {code: code[1], client_id: options.client_id, client_secret: options.client_secret, redirect_uri: options.redirect_uri, grant_type: 'authorization_code'}
}).success(function(data) {
deferred.resolve(data);
}).error(function(data){
deferred.reject(response.responseJSON);
});
} else if (error) {
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}

AngularJS service with express error: [$resource:badcfg] object

I'm using external mongodb and wrote a node/express server for fetching the data on my localhost.
I query localhost like this:
http://localhost:8888/api/bonsais
And I'm getting the correct results from my mongodb collection # mongolab.
[{"name":"test,test2","_id":"536be2e2ae54668818000001","__v":0},{"name":"testname","_id":"536fd2df41f84a581c000001","__v":0}]
I wrote a service to fetch the data like this:
angular.module('bonsaiService', ['ngResource']).
factory('bonsaiService', function($resource) {
return $resource('http://localhost:8888/api/bonsais',{'query': {method: 'GET', isArray: true }});
});
I'm getting a Error: [$resource:badcfg] object, which is referring to these error docs
.factory('Bonsai', function($q, $resource){
var bonsaiResource = $resource('http://localhost:8888/api/bonsais', {}, {
get: {
method: 'GET',
isArray: true
}
});
return {
get: function() {
var q = $q.defer();
bonsaiResource.get({
},
function(resp) {
q.resolve(resp);
}, function(httpResponse) {
q.reject(httpResponse);
});
return q.promise;
} };
})
try to write it this way.
Then you can call it with Bonsai.get()
Thanks #thesearentthedroids, your responds fixed it for me!
Just to follow up, I've used the following to retrieve the data in my controller:
bonsaiService.get($scope.trees).then(
function(data){
$scope.trees = data;
});

Backbone.js - XMLHttpRequest cannot load

I'm using backbone.js as my javascript framework for my project. I got this error when retrieve data through API.
XMLHttpRequest cannot load https://izify.com/api/izify-api/user/get_all_categories.php?merchantId=74718912a2c0d82feb2c14604efecb6d. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://staging.revivalx.com' is therefore not allowed access. staging.revivalx.com/:1
error SidebarView.js:23
XMLHttpRequest cannot load https://izify.com/api/izify-api/user/get_all_products.php?merchantId=74718912a2c0d82feb2c14604efecb6d. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://staging.revivalx.com' is therefore not allowed access. staging.revivalx.com/:1
error HomeView.js:23
SidebarView.js
define(['jquery', 'underscore', 'backbone','models/global/GlobalModel','collections/category/CategoryCollection', 'text!templates/sidebar/sidebarTemplate.html'], function($, _, Backbone,GlobalModel,CategoryCollection, sidebarTemplate) {
var SidebarView = Backbone.View.extend({
el: $("#sidebar"),
initialize: function() {
this.$el.off();
},
render: function() {
var that = this;
var global = new GlobalModel();
this.collection = new CategoryCollection();
var formValues = {
merchantId: global.merchantId
};
this.collection.fetch({
data: formValues,
success: function(collection, response) {
var template = _.template(sidebarTemplate,{
categories: that.collection.models
});
$("#sidebar").append(template);
},
error: function(collection, response) {
console.log("error");
}
});
}
});
return SidebarView;
});
HomeView.js
define(['jquery', 'underscore', 'backbone','models/global/GlobalModel','collections/product/ProductCollection','views/sidebar/SidebarView','text!templates/home/homeTemplate.html'], function($, _, Backbone,GlobalModel,ProductCollection,SidebarView, homeTemplate) {
var HomeView = Backbone.View.extend({
el: $("#page"),
initialize: function() {
this.$el.off();
},
render: function() {
var that = this;
var global = new GlobalModel();
this.collection = new ProductCollection();
var formValues = {
merchantId: global.merchantId
};
this.collection.fetch({
data: formValues,
success: function(collection, response) {
var template = _.template(homeTemplate, {
products: that.collection.models
});
that.$el.html(template);
},
error: function(collection, response) {
console.log("error");
}
});
var sidebarView = new SidebarView();
sidebarView.render();
},
});
return HomeView;
});
My API header
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
I already upload my source code in github : https://github.com/datomnurdin/izify-template
Demo: http://staging.revivalx.com/izify-template/
Thanks a lot in advance.
Seems like CORS problem, you could not sove this with client side only.
To test API CORS support you can use test CORS
So you can solve this by:
Implement CORS support on API server side.
Proxy requests from your app server side to API.
Use another techics to cross-origin policy like(JSONP, etc..)

Resources