Extjs callback function to controller - extjs

I have the following base class which handles all request
makeRequest: function(mydata) {
Ext.Ajax.request({
url: './handler.php',
method: 'GET',
scope: this,
params: {
data: mydata
},
callback: this.myResponse,
success: function(xhr, params) {
console.log('Success');
},
failfure: function(xhr, params) {
console.log('Failure');
}
});
}
In my controller I have
.............
requires: [
'Test.libs.Request'
],
............
onItemClick: function() {
var objCallback = Ext.create('Test.libs.Request', {
scope: this
});
objCallback.makeRequest(1);
},
myResponse: function(options, success, response) {
console.log(response);
}
After success executes, how can I get to the controller's myResponse as a callback?

You need to pass along the fn and the scope, something like:
Ext.create('Test.libs.Request', {
callback: this.myResponse
scope: this
});
// You need to get a reference to those passed params inside your request method.
Ext.Ajax.request({
url: './handler.php',
method: 'GET',
scope: passedScope,
params: {
data: mydata
},
callback: passedCallback
});

Related

How to post an array to mvc controller

I want to post java script object to mvc controller
$(document).ready(function () {
var table = $('#my_table_1').DataTable({
"paging": true,
"ordering": true,
"info": true,
"search": true,
"pageLength": 100
});
var d = '';
var data3 = table.on('search.dt', function () {
//number of filtered rows
// console.log(table.rows({ filter: 'applied' }).nodes().length);
//filtered rows data as arrays
d = table.rows({ filter: 'applied' }).data()
});
console.log(table.rows({ filter: 'applied' }).data());
$('#excel2').click(function (e) {
//var data3 = table.on('search.dt', function () {
// console.log(table.rows({ filter: 'applied' }).data());
// console.log(data3);
//});
console.log(d);
$.ajax({
url: '/Administrator/TestDownload',
type: 'POST',
data: {data:d},
cache: false
}).done(function (response) {
alert(d);
});
});
});
//Controller code:
public JsonResult TestDownload(String[] data)
{
return Json(data,JsonRequestBehavior.AllowGet);
}
I am getting null in controller as a data parameter
Expected: Want to get data object from view to controller as a parameter in controller.
Actual: Data parameter in controller is null
You must check your d variable correct array format.
I tested in my side with var d = ["test",2,3] and in controller it get correct data.
$('#excel2').click(function (e) {
//var data3 = table.on('search.dt', function () {
// console.log(table.rows({ filter: 'applied' }).data());
// console.log(data3);
//});
d = ["test",2,3]
console.log(d);
$.ajax({
url: '/Administrator/TestDownload',
type: 'POST',
data: {data:d},
cache: false
}).done(function (response) {
alert(d);
});
});
});
An example that works:
var test = ["This", "is", "a", "test"];
$.ajax({
type: "POST",
traditional: true,
url: "Administrator/TestDownload",
data: { array: test }
}
});
The controller(in VB.net):
Function TestDownload(array As String()) As ActionResult
//do something
End Function
Why not try stringifying the data and setting the contentType
$.ajax({
url: '/Administrator/TestDownload',
data: JSON.stringify({data:d}), // use JSON stringify
type: 'POST',
contentType: "application/json; charset=utf-8", //add this
cache: false
}).done(function (response) {
alert(d);
});
});

How to make the URL of $resource generic?

I am new to AngularJS and I have a question here.
I am using $resource for my CRUD actions.
I currently have the code like this,
angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
function ($resource) {
return $resource("api/UserRoleApi", {}, {
query: { method: "GET", isArray: true },
create: { method: "POST" },
get: { method: "GET" },
remove: { method: "DELETE" },
update: { method: "PUT" }
});
}]);
//below is the code in my controller
UserRoleService.query(function (data) {
vm.UserRoleLookups = data;
});
I would like to make my UserRoleService generic, which means I don't want to provide the specific URL for the API in the factory level.
I now modify my code a little bit,
angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
function ($resource, url) {
return $resource(url, {}, {
query: { method: "GET", isArray: true },
create: { method: "POST" },
get: { method: "GET" },
remove: { method: "DELETE" },
update: { method: "PUT" }
});
}]);
My question is what I should do in my controller?
So, instead of directly returning $resource, we can encapsulate it with a function that accepts url as a param.
Something like this:
myApp.factory('UserRoleService', function($resource) {
return {
query: function(url) {
return $resource(url, {}, {
query: {
method: "GET",
isArray: true
},
get: {
method: "GET"
}
});
}
}
});
Now, in controller, you can call it like:
UserRoleService.query('//httpbin.org').get()
example fiddle

Dynamic URL for $resource in an angular factory without using global variable

How can I define a dynamic factory in such a way that the URL is passed from the controller without using $rootScope?
.factory('getData', function ($resource,$rootScope) {
return $resource($rootScope.url, {id:'#id'}{
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET',
isArray: true,
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
})
Controller
var data = [];
$rootScope.url='/userDetails/userId?userId=userID'
getData.get({id:'123'}).$promise.then(function(data){
angular.forEach(data,function(dataVal){
//
},data)
You should create a function in your factory and then pass the URL and id as parameters to that function when you invoke it.
For your code the factory should look something like this:
.factory('getData', function($resource, $rootScope) {
return {
query: function(url, id){
return $resource(url, {userId: id}, {
'query': {
method: 'GET',
isArray:true
},
'get': {
method: 'GET',
isArray:true,
transformResponse: function(data) {
console.log(data);
data = angular.fromJson(data);
return data;
}
}
}).get();
}
}
})
And then you would invoke it like this getData.query(url,id) in the controller.

DELETE Restful method with angularjs $resource

I'm attemping to call a RESTful method via $resource as following:
Resource:
angular.module('secure',['ngResource']).factory('Vehicle', function ($resource) {
return $resource('/secure/vehicle/index', { id: '#id' }, {
query: {
method: 'GET',
isArray: true
},
delete: {
method: 'DELETE',
isArray: false,
url: '/secure/vehicle/delete/:id'
}
});
});
Then, from other service I inject the above factory and I call DELETE method in this way:
factory.delete = function (procedureId) {
var vehicle = new Vehicle();
vehicle.$delete({id: procedureId}, function () {
//success
deferred.resolve();
}, function (errResponse) {
// fail
console.log(errResponse);
});
return deferred.promise;
};
(Don't pay attention to deferred things, it doesn't work with or without it)
Unfortunately, I always get the same answer:
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/secure/vehicle/delete/21
Request Method:DELETE
Status Code:422 Unprocessable Entity
The call itself is set up properly (secure/vehicle/delete/21). In fact, if I do the same, but instead of using $resource variable, using $http, everything works!
$http({
'method': 'DELETE',
'url': '/secure/vehicle/delete/' + procedureId,
'headers': {
'Content-Type': 'application/json'
},
'data': ""
})
.success(function () {
// success
})
.error(function (data, status) {
console.log(data.errors);
});
So, I guess something is missing in $resource-way, but what? Any help, it will be appreciated!
EDIT:
It seems it's a backend problem when it reads the entire url call. If I call DELETE resource, using $http, adding the data: "" as I show above, the backend initializes itself properly.
But if I try the $resource-way, the required params are pre-configured and that doesn't like to the backend, so I need to find the way to say to $resource how to add something like data: "", any ideas?
Test proof that it works:
angular.module('secure', ['ngResource']).factory('Vehicle', function($resource) {
return $resource('/secure/vehicle/index', {
id: '#id'
}, {
query: {
method: 'GET',
isArray: true
},
delete: {
method: 'DELETE',
isArray: false,
url: '/secure/vehicle/delete/:id'
}
});
});
angular.module('secure').factory('VehicleFactory', function(Vehicle, $q) {
var factory = {}
factory.delete = function(procedureId) {
var deferred = $q.defer();
var vehicle = new Vehicle();
vehicle.$delete({
id: procedureId
}, function(r) {
deferred.resolve(r);
}, function(errResponse) {
console.log(errResponse);
});
return deferred.promise;
};
return factory;
});
describe('VehicleFactory', function() {
var $httpBackend, VehicleFactory
beforeEach(module('secure'));
beforeEach(inject(function(_$httpBackend_, _VehicleFactory_) {
$httpBackend = _$httpBackend_
VehicleFactory = _VehicleFactory_
}))
it('deletes vehicle - vehicle.$delete()', function() {
var r = {
data: 'correct response'
}
$httpBackend.when('DELETE', '/secure/vehicle/delete/123').respond(r)
VehicleFactory.delete(123).then(function(response) {
expect(response.data).toBe(r.data)
})
$httpBackend.flush();
});
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation()
$httpBackend.verifyNoOutstandingRequest()
})
})
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>
Some much cleaner way to write delete functionality without $q:
angular.module('secure').factory('VehicleFactory', function(Vehicle) {
var factory = {}
factory.delete = function(procedureId) {
return (new Vehicle()).$delete({
id: procedureId
})
}
return factory;
});

ngResource treating POST like GET

I noticed that although I specify "post" on my ngResource factory, it is passing parameters as GET.
Example of a user factory:
myApp.factory('facUser',['$resource', function ($resource) {
return $resource('/api/User/:route', {}, {
EditUser: { method: 'POST', isArray: true, params: { route: "EditUser", cid: '#cid', objEditUser: '#objEditUser' } }
})
}]);
And this is the call to edit the user:
$scope.Edited_User = facUser.EditUser({
cid: $stateParams.company_id, objEditUser: TempUserInfo
}, function success(data, status, headers) {
console.log(data);
}, function err(data, status, headers, config) {
});
Thus, when I call that, for some reason I see all my values being passed on the header of the API as if it was a GET.
I am having trouble figuring out how to use $save() or how to post/put this as form.
The params keyword will resolve any route variable and the rest will be in the request query.
To send values in the request body you can do:
var user = new User( {
cid: $stateParams.company_id,
objEditUser: TempUserInfo
}) ;
user.$EditUser();
And change your resource to be something like:
$resource('/api/User/:route', {}, {
EditUser: { method: 'POST', isArray: true, params: { route: "EditUser" } }
})
}]);
myApp.factory('facUser',['$resource', function ($resource) {
return $resource('/api/User/:route', {}, {
EditUser: { method: 'POST', isArray: true, params: { route: '#route'} }
})
}]);
And then...
$scope.Edited_User = facUser.EditUser({
route: "EditUser"
}, {cid: $stateParams.company_id, objEditUser: TempUserInfo}, function success(data, status, headers) {
console.log(data);
}, function err(data, status, headers, config) {
});
Essentially the first part is parameters.
The second part is post values.

Resources