Backbone fetch hitting the wrong url - backbone.js

I'm have the following backbone model
define(["jquery", "underscore", "backbone"],
function ($, _, Backbone) {
var file_upload = Backbone.Model.extend({
url: 'http://localhost:8080/rest/customForms'
});
return file_upload;
}
I have a view loaded at
localhost:38559/app/forms.html
which tries to do a post with the following code
var fd = document.getElementById('fileToUpload').files[0];
var file = new file_upload();
file.fetch({data: $.param({fileToUpload: fd}),
type: 'POST',
success: function(d){
console.log('success');
}
});
but this seems to just do a get request to forms.html passing fd as a param. I've also tried overriding the sync method in file_upload
sync: function (method, model, options) {
var self = this;
options = _(options).clone();
var error = options.error;
options.error = function (jqXHR, textStatus, errorThrown) {
alert('error');
if (error)
error(jqXHR, textStatus, errorThrown);
};
var success = options.success;
options.success = function (data, textStatus, jqXHR) {
if (success && data) {
alert("Success uploading form.");
success(data, textStatus, jqXHR);
}
else
alert("Error uploading form. Please try entering again.");
};
var params = {
type: 'POST'
};
$.ajax(_.extend(params, options));
}
}
I'm doing posts in other parts of the app with similar code so can't figure out why with this code the fetch does a get request to the page it's called on rather than a post to the url specified in the model. Does anyone have any ideas?
Thanks,
Derm

Ugh - finally found the issue coming back to this. The file upload was been done on a button click event. I needed to call preventdefault to force the use of the models url rather than the pages url. Annoying issue - dunno how I missed it! Code now is
uploadForm: function (e) {
e.preventDefault();
var self = this;
var fd = document.getElementById('fileToUpload').files[0];
var file = new file_upload();
file.fetch({data: $.param({fileToUpload: fd}),
type: 'POST',
success: function(d){
console.log('success');
}
});
},

Related

How to delete file in dropzone?

init: function() {
dzClosure = this;
document.getElementById("place-order").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("key", $scope.formData.order_id);
});
this.on('success', function(file, resp) {
console.log(resp); //result - {error:false, file_id:10}
file_ids.push(resp.file_id);
});
},
removedfile: function(file) {
console.log(file_ids);
x = confirm('Do you want to delete?');
if (!x) return false;
var name = file.name;
$.ajax({
type: 'POST',
url: 'orders/fileDelete.php',
data: {"file_id": file_ids},
dataType: 'json'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
Above my code working fine. But I want to delete my mysql row while clicking on the "Remove" button in dropzone. I am unable to get the current file_id in my removedfile function. Please help me and let me know how I will get resp.file_id in my removedfile function?
You could set an id property to file on success event, then on removal just get it as file.id. Hope this helps you.
init: function() {
dzClosure = this;
document.getElementById("place-order").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("key", $scope.formData.order_id);
});
this.on('success', function(file, resp) {
file.id = resp.file_id;
});
},
removedfile: function(file) {
x = confirm('Do you want to delete?');
if (!x) return false;
//send delete to backend only if file was uploaded.
//Dropzone will cancel requests in progress itself.
if(file.id) {
$.ajax({
type: 'POST',
url: 'orders/fileDelete.php',
data: {"file_id": file.id},
dataType: 'json'
});
}
}
After lots of research I found where was error in my code.
Actually my ajax responded JSON. But here is dropzone.js not getting json data. So I have converted my dynamic String data to JSON format.
Code:
this.on('success', function(file, resp) {
console.log(resp); // result - {error:false, file_id:10}
var response = JSON.parse(resp);
file.file_id = response.file_id;
});

Authintication Error in Ionic WooCommerce using Angular

I am implementing Woo Commerce Rest API in my Angular/Ionic project on Cordova Platform. While I am making $http request to get product list or any other data, I am getting error Message. Here is my Service code:
angular.module('services.serverRepo', [])
.service("serverRepo",
['$q','$http','errorHandler','$ionicLoading',function($q,$http,errorHandler,$ionicLoading){
var baseUrl="www.abc.com/wc-api/";
var self=this;
this.products=function(){
var deff=$q.defer();
$http({
method:"GET",
url:baseUrl+"v3/products",
headers: {
"Content-Type":"application/JSON",
"oauth_consumer_key":"gjdfjkbgbdhh645h6bh456b45hbhbgdfhgbdfhgbdfhgbhgbdhfghhfhf",
"consumer_secret":"cs_97d74bbf5e9052ee053a05cbb1a53eec19c0847c"
}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
alert('error:- '+objE);
errorHandler.serverErrorhandler(objE);
deff.reject("server Error");
});
return deff.promise;
};
}])
.service('errorHandler',['$q',function($q){
this.serverErrorhandler=function(error){
alert("ERROR ::"+JSON.stringify(error));
console.log("ERROR ::"+JSON.stringify(error));
};
}
])
and in my controller.js file code is:
$scope.rentaldeptt = function(){
//$ionicHistory.clearCache();
serverRepo.products().then(function(objS){
},function(err){
});
}
I am calling $scope.rentaldeptt on a button click. In response I am getting error message
{"data":{"errors":[{"code":"woocommerce_api_authentication_error","message":"oauth_timestamp parameter is missing"}]},"status":404,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"www.abc.com/v3/products","headers":{"Accept":"application/json, text/plain, /"},"params":{"oauth_consumer_key":"gjdfjkbgbdhh645h6bh456b45hbhbgdfhgbdfhgbdfhgbhgbdhfghhfhf","consumer_secret":"cs_97d74bbf5e9052ee053a05cbb1a53eec19c0847c"}},"statusText":"Not Found"}
Any Idea what I am doing wrong?
Please try to following steps to resolve the isue,
Here, I have Created the service in angularjs to handle the calling of woocommerce api with the oauth,
angular.module('myapp.restservices', [])
.service("serverRepo",['$q','$http','errorHandler','$ionicLoading',function($q,$http,errorHandler,$ionicLoading){
var self=this;
//Request Url and method
var request = {
url: 'http://www.example.com/wc-api/v3/products',
method: 'GET'
};
//OAuth Protocol authentication parameters
var oauth = new OAuth({
consumer: {
//Consumer Public Key
public: 'ck_50xxxx',
//Consumer Secrete Key
secret: 'cs_b4xxxx'
},
//oauth1.0a protocol signature method
signature_method: 'HMAC-SHA1'
});
//Service Function to get products
this.products=function(){
$ionicLoading.show({
template: '<ion-spinner class="light"></ion-spinner>'
});
//OAuth Parameters to call woocommerce api
var oauth_data = {
oauth_consumer_key: oauth.consumer.public,
oauth_nonce: oauth.getNonce(),
oauth_signature_method: oauth.signature_method,
oauth_timestamp: oauth.getTimeStamp()
};
//Oauth signature
oauth_data.oauth_signature = oauthSignature.generate(request.method,request.url,oauth_data,oauth.consumer.secret );
console.log("Params : "+ JSON.stringify(oauth_data));
var deff=$q.defer();
$http({
method:"GET",
url:request.url,
headers: {
"Content-Type":"application/JSON",
},
params: oauth_data
}).then(function(objS){
$ionicLoading.hide();
alert('Success :- '+JSON.stringify(objS));
},function(objE){
$ionicLoading.hide();
alert('error:- '+JSON.stringify(objE));
errorHandler.serverErrorhandler(objE);
deff.reject("server Error");
});
return deff.promise;
};
}])
.service('errorHandler',['$q',function($q){
this.serverErrorhandler=function(error){
alert("ERROR ::"+JSON.stringify(error));
console.log("ERROR ::"+JSON.stringify(error));
};
}
])
Write controller to call the service function as like follows,
angular.module(myapp.categorycontrollers, [])
.controller('MainCtrl', function($scope,woocommerce) {
//Method to get all Products
$scope.getAllProducts = function(){
woocommerce.products().then(function(objS){
},function(err){
});
}
//calling to function
$scope.getAllProducts();
}
Hopes this will help you !

AngularJS Controller function - TypeError: object is not a function

I am creating an email application that makes RESTful calls to Google APIs. I am using AngularJS and Java. I have had some success so far but I am unable to delete an email because I keep getting this error: TypeError: object is not a function.
My Angular knowledge is limited.
In my html I call the function deleteEmail and pass an email id.
Here is the controller:
app.controller('InboxController', function($rootScope, $scope, $cookies,
$location, InboxService) {
$rootScope.loggedIn = true;
$scope.emails = InboxService.getMessages().success(function(jsonData) {
$scope.emails = jsonData;
});
$scope.deleteEmail = function(id) {
$scope.id = {
'id' : id
};
// Parse to JSON
var responseJSON = angular.toJson($scope.id);
// Make call to InboxService
var response = InboxService().del(responseJSON).success(
function(jsonData) {
response = jsonData;
if (response == 'success') {
alert('Message deleted');
} else {
alert('Message not deleted');
}
});
}
});
The method $scope.emails works fine. It is the $scope.deleteEmail that is giving the error.
Here is the service:
app.factory('InboxService', function InboxService($http) {
var exports = {};
// Get a list of all emails
exports.getMessages = function() {
return $http.get('resources/inbox/get').error(function(data) {
console.log('There was an error!', data);
});
};
// Delete an email
exports.del = function(id) {
console.log('id ' + id);
return $http({
method : 'POST',
url : 'resources/inbox/delete',
data : id,
headers : {
'Content-Type' : 'application/json'
}
});
};
return exports;
});
I don't think I am getting as far as the service though. The problem seems to be with the controller.
Console output:
TypeError: object is not a function
at Scope.$scope.deleteEmail (http://localhost:8080/NewProject/js/controllers.js:64:18)
at Parser.functionCall (http://localhost:8080/NewProject/bower_components/angular/angular.js:10903:21)
at ngEventDirectives.(anonymous function).compile.element.on.callback (http://localhost:8080/NewProject/bower_components/angular/angular.js:19259:17)
at Scope.$get.Scope.$eval (http://localhost:8080/NewProject/bower_components/angular/angular.js:12811:28)
at Scope.$get.Scope.$apply (http://localhost:8080/NewProject/bower_components/angular/angular.js:12909:23)
at HTMLButtonElement.<anonymous> (http://localhost:8080/NewProject/bower_components/angular/angular.js:19264:23)
at http://localhost:8080/NewProject/bower_components/angular/angular.js:2853:10
Pls be sure you called deleteEmail(id) from within html with right syntax without $scope
I got it working. I changed the Controller delete method to this:
$scope.delete = function (id) {
InboxService.delete(id).success(function() {
$scope.loadInbox();
});
};
And the Service method to this:
// Delete an email
exports.delete = function(id) {
console.log('id ' + id);
return $http({
method : 'DELETE',
url : 'resources/inbox/delete',
data: id,
headers : {
'Content-Type' : 'application/json'
}
});
}

Is it possible so send just a part of an object by angular resource?

I have a resource where the get is receiving an object like {metadata : {}, data : {}}. But when I save, I just want to send the data and not metadata.
.factory("$profile", function($resource) {
return $resource("service/profile/:profileid");
})
.controller('ProfileController', function($scope, $routeParams, $profile) {
$scope.profile = new $profile();
$scope.doSave = function() {
// need to send profile.data only << ----------
$scope.profile.$save($routeParams, function(data) {
console.log("saved profile");
});
}
What I have done right now is the following:
.controller('ProfileController', function($scope, $routeParams, $profile) {
$scope.profile = new $profile();
$scope.doSave = function() {
$scope.profile.data.$save = $scope.profile.$save;
$scope.profile.data.$save($routeParams, function(data) {
console.log("saved profile");
});
}
This works but I am sure there is a much cleaner way to do what I need to do. Ideally I would tell the resource to look for a data property on "save".
Yes, you can do that. The properties you need are 'transformResponse' (on GET) and 'transformRequest' (on Post).
.factory("$profile", function($resource) {
return $resource("service/profile/:profileid",
{},
{
get: {
method: 'GET',
transformResponse: function(response, headers){
return response.data;
}
},
post: {
method: 'POST',
transformRequest: function (request, headers) {
var result = request.data; // << This line might not be exactly what you need.
return result;
}
}
});
})
I actually suspect that the transformRequest part isn't needed at all (but you did ask for it).
$scope.profile.$save($routeParams, function(data) {
console.log("saved profile");
});

Backbone base64 encoding

I don't get how to make Backbone.sync suitable for my case.
That's why I still use this usual Ajax-Request for my project:
$.ajax({
url: request,
status: status,
type: 'GET',
dataType: 'json',
beforeSend: function (req) { req.setRequestHeader("Authorization", auth) },
success: function (data, status) {
//update the model
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//do stuff
}
});
I need to add a base64 encoded authorization to the request header and update a model. The data I get from the server contain more information than my model needs. That's why I can't refer the model directly to an url like this:
var MyApp.myModel = Backbone.Model.extend({
url: '/someResourceUrl'
});
MyApp.myModel.fetch();
I need to do sth. like:
var MyApp.myModel = Backbone.Model.extend({
url: 'anyurl',
sync: myOwnSpecificSync,
});
//Define the sync function:
myOwnSpecificSync = function(method, model, options) {
//add header
//return only specific parameters of the success data
};
//let the model fetch the data from the server
MyApp.myModel.fetch();
But I have no idea how to implement the functions .. or if it's correct at all.
var AuthSync = function(method, model, options) {
options.beforeSend = function () {
console.log('add auth header here');
};
return Backbone.sync(method, model, options);
};
var Model = Backbone.Model.extend({
url : 'http://fiddle.jshell.net/echo/json/',
sync : AuthSync
});
new Model().fetch();

Resources