Web2py and Sencha - extjs

I'm new to Web2py and Sencha, and I would like to see a simple example using both frameworks. I have googled but I haven't found anything.
Many thanks for your help.

Finally I got everything working. To ensure that the js files are rendered it is necessary to paste them in the static folder of the web2py project. With Sencha Architect I have created a project in the mentioned location, so for example to call the controller from the js view an Ext.Ajax.request is made:
onDataRender: function(component, eOpts) {
Ext.Ajax.request
({
url: '/r/rec/getdata',
method: 'GET',
params: '',
success: function(response)
{
o=Ext.decode(response.responseText);
component.setSource(o);
console.log(response.responseText);
},
failure: function(response)
{
component.setSource({"Error" : "No data"});
console.log(response.responseText);
}
});
},
The controller then gets the resquested data from database, generates a json and returns it to the view layer:
def getdata():
jsondata="{"
data=db.song.find()
for s in data:
jsondata+="\""+str(s["_id"])+"\" : \""+str(s["name"]).replace("\"","")+"\","
return jsondata[:-1]+"}"
The getdata method gets all the data (it is a test example), to get a specific record the id can be passed as a parameter with request.args(0).

Related

ASP.Net MVC with Angular and Kendo UI

I'm new to ASP, Kendo and programming in general.
I’m trying to use Kendo Grid to CRUD the database; but I am kind of lost.
I have a simple class: Person, with Name and Surname.
The generated Controller and View works just fine, I can CRUD the database.
Then, using Angular I created this module:
`angular.module("KendoDemos2", ["kendo.directives"])
.controller("MyCtrl2", function ($scope) {
$scope.mainGridOptions = {
dataSource: new kendo.data.DataSource({
transport: {
read: { url: "/Person/Read", dataType: "json" },
create: { url: "/Person/Create", dataType: "json", type: "POST" },
update: { url: "/Person/Update", dataType: "json", type: "PUT" },
destroy: { url: "/Person/Delete", dataType: "json", type: "DELETE" },
parameterMap: function (options, operation) {
if (operation !== "read") {
console.log(options)
return kendo.stringify(options);
}
}
},
batch: false,
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Name: { type: "string },
Surname: { type: "string" } }
}
}
})`
The problem is:
First, When I create a new person on the Grid, when I press “Create”, I don’t know if the data is being passed to the controller.
Second, in the controller, I have no idea of how to receive this information (a json, I believe).
Sorry, I am a total beginner.
EDIT
I have this method on the Controller:
[HttpPost]
public ActionResult Create(Person model)
{
if (model != null)
{
return Json("Success");
}
else
{
return Json("An Error Has Occurred");
}
}
So, this is being sent to the Person/Create method:
{ Name: "John", Surname: "Doe"}
Which return Success;
But how do I get these properties from the Json, and populate the model?
Ok so.
POST = create
GET = well Get in the context of the type of request from
browser to server
PUT = Update
DELETE = exactly Delete
so those are the verbs associated with HTTP in which RESTFUL APIS reside, for the most part there are lot more to look at, behind the scope of this answer.
as a result of the nature of the call it already understands that certain things like the type of data that you sent was in Content-Type: application/json.
The one thing missing from that method which I am surprised it wasn't there was
[FromBody], unless you hand coded the Method yourself rather than scaffolded it. Understandable for someone starting out. :)
to see this placing one of those break points next to the if statement will allow you to see if model was indeed populated with the contents of the post call.
[HttpPost] //because we want to create (new Person(){}) right?
public ActionResult Create([FromBody] Person model){
if(model != null && model.IsValid){
//EntityFramework or what ever DB you are using
_context.Person.Add(model);
_context.SaveChanges();
//doing this returns to the client that it was created as well as the
//Id of the newly inserted record. model.Id was automagically updated with the Id.
return Created("api/person/create", model);
}
else{
//something was horribly wrong with the model sent
return BadRequest("Invalid Model");
}
}
I think that will cover the broad strokes of the question. I think you are using an older version of asp.net so JsonResult might be available as well, BadRequest and Created assume ApiController is being used or Controller in Asp.net Core
mvermef, thank you very much for all the explanation.
I’m using ASP.Net MVC 5, with EF.
I did as you told and it work perfectly.
I haven’t included Web API at first, but needed it to make the [FromBody] work.
Another small but important thing was include contentType on the kendo configuration:
create: { url: "/Person/Create", dataType: "json", type: "POST", contentType: "application/json; charset=utf-8" },

how to write get method using ng resource

hi in my requirement i tried to write post method using ngresource but now i want to change that into get method. can anyone help me to solve this problem. i am new to angularjs thanks in advance
$scope.clickresult = {};
var Call = $resource('../api/Home', {}, { query: { method: 'POST', isArray: true} });
$scope.click = function () {
//alert("hi");
$scope.selected = "";
var x = $('#txtSearch').val();
var _ReqObj = new Object();
_ReqObj.id = x;
_ReqObj.Meth = "CD";
// alert(x);
Call.query({}, _ReqObj,
function (response) {
if (response == '') {
// alert('no data');
window.location.replace("#/");
}
else {
//alert("daata");
$scope.message = response;
}
},
function (error) {
window.location.replace("#/");
}
);
};
Here is some initial help so you can solve your future problems on your own.
1. Use developer tools to see errors, requests and responses: https://developers.google.com/web/tools/chrome-devtools/
Open the tools from the menu or use cmd+alt+I on Mac or ctrl+shift+I on Windows.
In the "Network" tab of the developer tools you can see the communication with your server (E.g. request method = GET, response from the server). In the "Preview" tab you can see the json the server sent you. Tell me if you have problems finding this, because it is very important to find bugs in your code.
2. Use logging!
In angular you can add $log to your code and with $log.log("message", object) you can output debug messages and the current state of objects from your code. You can see the logging messages in the developer tools in the "Console" tab.
3. Read the documentation
Angular provides documentation and examples for their functions. Read this about the $resource service https://docs.angularjs.org/api/ngResource/service/$resource
Read about the difference between GET and POST method.
4. Try a simple example from a tutorial and try to adapt it to your needs
Copy a simple resource example from the internet and make it work. If that works change it step by step until it is what you need.
5. For your example:
How does your server side script work? In your question I can only see the angular code. If you want to use the GET method the server has to provide a function that reacts to GET.
The $resource service already provides a query method:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
Normally you don't need to add "{ query: { method: 'POST', isArray: true}" to your code. The query function is already there!
To send a GET request with the query function you just need:
var Call = $resource('../api/Home', {});
Now open your developer tools, go to the Network tab and then execute the function $scope.click in your website. What do you see in the Network tab? The request should be fired with "request method: GET". What is the answer from the server? The problem is maybe not in your angular code but in your server code.
Try these things and tell me if you need more help.

angularjs PATCH method 404 response

WORK AROUND IS AT THE BOTTOM
Original problem
There are question like this all over the web and none of them really have answer for me. I can't get an http PATCH operation to work using angular to save my life. I've implemented $http, with shortcut $http.patch and without using the config object method:PATCH. I've used $resource by adding a custom method. And I've implemented Restangular using their patch and I'm getting the same error. I have the correct Content-Type as suggested in other posts. I think it's safe to say at this point, it's something I'm missing. I'm getting the same "404" message via postman when trying to patch. I can PUT, GET, POST, and DELETE, but not PATCH.
In the following images you can see that the resource exists for GET. But when trying to patch I get 404. Browsing to that endpoint shows the record. Which is stored in Mongodb.
Here's some code snippets:
Resangular GET:
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
Restangular Patch:
var data = {
corporiumId: $scope.newBlock
};
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.patch(data).then(function(res) {
console.log(res)
}, function(err) {
console.log('Restangular failed: ', err)
});
$http attempt using config object:
controller code:
httpCorporiumSrv.updateCorporiumId('/corporium-mgmnts/' + $scope.params.id, data)
.then(handleUpdateSuccess)
.catch(handleUpdateError);
service code, tried forcing the content-type header but got same result
with or without it:
function updateCorporiumId(url, data) {
return $http({
method: 'PATCH',
url: url,
data: angular.toJson(data),
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
//transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Using the .patch shortcut:
function updateCorporiumId(url, data) {
return $http.patch(url, data, {
transformRequest: transformUpdateData
})
.then(handleUpdateSuccess)
.catch(handleUpdateErrors);
}
Thing is I've tried this every which way I know how. I don't even know how to start debugging any more. I'm just getting 404 on a resource that does exist. Any suggestions on what might be happening to my request would be great.
Resolution:
For anyone having this issue, if you could post the fix or what's going on here to this point or PM me that would be awesome I'd like to know. I ended up just using PUT to fix this.
Quick Restangular solution:
Build the url template for findByOne like function using Restangular.one(url, _id) where '_id', is the id of the resource you're looking for. .get() goes out and finds that one resource by said id, which you can populate dynamically however you like. Once you have the one resource with GET copy it with Restangular.copy() which is different from angular.copy as it doesn't bind 'this' to the new object. Change what needs to be changed or added in the new object and then perform a .put() on it.
var corporiumRecord = Restangular.one('corporium-mgmnts', $scope.uuid);
corporiumRecord.get().then(function(res) {
var update = Restangular.copy(res);
// update date corporiumId
update.corporiumId = $scope.newBlock;
// submit new doc with altered value
update.put().then(function() {
console.log('updated')
});
console.log(update)
}, function(err) {
console.log('Restangular failed: ', err)
});
Also because mongo uses _id and Restangular uses id you have to add this to your module
angular.module('corporium-mgmnts').config(function(RestangularProvider) {
RestangularProvider.setMethodOverriders(['put', 'patch']);
// setRestangularFields is required for mongodb
RestangularProvider.setRestangularFields({
id: "_id"
});
});

Retrieve data from a JsonP proxy in sencha touch

I am trying to get the data from a JSONP proxy in sencha touch 2.3(I am using sencha architect 3 to develop). I was successfully able to place jsonp call and get the data back. But I am not getting how to separate every single element of json response. Here is my json Response:-
{"data":[{ "PLANTNUM": "1557", "ROUTEID": "90625", "DELIVERYDATE": "2014-02-12T00:00:00-06:00", "MESCOD": "15", "MESFCT": "DLV", "ORIGID": "HH", "JMSTIME": "02/11/2014 00:11:21", }],"success" : true}
Here is my function
success: function(response){
console.log(response);
var temp=response.data.PLANTNUM;
console.log(temp);
}
I can see below in my console:-
Here is my jsonP request
Ext.data.JsonP.request({
url: 'http://localhost:12608',
callbackKey: 'cbfn',
params: {
method: 'sapout',
type: 'sap',
ordnum: '1034986850'
}
I tried using response.PLANTNUM but that is also not working. It always shows undefined
Can anyone help me out here.
Thanks
data is an array, so you want response.data[0].PLATINUM.

Post values to cakePHP controller action and display it

I am using Facebook Javascript API for Facebook authentication and implementing other Facebook features, in a cake PHP based site. Now I am using API for fetching the Facebook friends and I need to do some operations with the friends list. So I am posting the JSON object array to the corresponding controller action. Later on this page is loaded using another AJAX call . In between I am loosing the posted data. What I need is, I need to compare frien's list with existing Facebook IDs. I am using the below code
FB.api('/me/friends', function(response) {
$.ajax({
type: 'post',
url: baseUrl+'/user_details/userlist',
data: response,
dataType: 'json',
success: function() {
}});
});
How can I achieve this ? or I need to use PHP based SDK ?
Change your data option to this format:
data: { "data" : response },
Then check $this->request->data on your Cake controller (assuming Cake 2.x).

Resources