submit changes on extjs roweditor grid - extjs

I have a grid what update my database (via PHP) with JSON record.
I want to know, how the data writed - record or not. I have an answer from PHP (true or false) to the grid, but dont know how to use it. How my grid can use this answer? (success event?)
Now, for example, User added new record without id at database (and i need this id for the future update), php answer what record saved(true) and told me id of new record. How I should work with it?
And I saw somehere some beauty flowing from the top of screen windows - how do the called?
Sorry for typically questions, but I cant find answer for it.
Thanks.

If you are using Ext.Ajax.request to make the connection this is how you do it.
Ext.Ajax.request({
url: 'ajax_demo/sample.json',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
There is a success callback function you specify which gets the response from the server which is a JSON object. This is where you can send things back and then manipulate your roweditor grid however you like.
Success also doesn't mean that everything went ok, it just means the request did not produce an html error code 4xx or 5xx.
The failure callback function is what to do if the server returns an error code for the AJAX request.

Related

How does the data get updated in $HTTP.put

Currently I am working on an angularJS app. it reads an property file from a repository and output an xeditable table, so you can change all the properties.
The only question I have now is, how do I make http.put request to update data.
assume the properties file have:
var data = {'prop1' : 'this', 'prop2' : 'that'};
I currently have:
$scope.update = function(key,value){
$http.post('http://blabla.com/properties.json', $scope.data)
.success(function (data, status) {
//success code
})
So Assume I updated the prop1 from this to newProperty.
Is my code correct? does the file in remote repository get updated?
or do i have to do something like this
$scope.update = function(key,value){
$http.post('http://blabla.com/properties.json',
data: {
prop1: 'newProperty'
})
.success(function (data, status) {
//success code
})
I only changed prop1, do I need to include prop2 also inside the data bracket? What happen when i got like 30 properties, then how do I update only 1 of the values using Http.put?
thanks
That URL won't work. You need a server-side API that can handle file uploads. That's not possible with Angular alone.
e.g.
$http.put('http://blabla.com/properties_api', $scope.data);
Also you've written $http.post up there, and that will (and should) fail unless the data doesn't exist in your repository. Change it to put if you're updating, 'post' only if you're creating.
Generally, uploading the full object is the way to go, otherwise the server is likely to treat the lack of other data as an explicit intention to delete that data. If you've got 30 properties, upload all 30.
That depends on how your server code handles this upload. If you write it yourself it'll do whatever you want with the data you give it.
That being said, if you've got a lot of data it can be unfeasible to upload it all, so you can create multiple APIs that can each handle a particular type of data.
e.g.
$http.put('http://blabla.com/properties_api/prop1_handler', $scope.data);

Backbone model's fetch doesn't work when the page initially loads but on second attempt works fine

In my backbone project I am trying to fetch a model based on some search criteria submitted by the users from a form. In submit handler, I am trying to fetch the model by passing search criteria's via data option (following is the code).
var productType=$("#productType").val();
var customerId=$("#customerId").val();
var stateSelected=$("#selectedState").val();
var srbStatus=$("#stateReportingStatus").val();
var dateType=$("#dateType").val();
var fromDate=$("#fromDate").val();
var toDate=$("#toDate").val();
var billTypeInd=$("#billTypeIndicator").val();
var dataElement=$("#dataElement").val();
var ediFileName=$("#ediFileName").val();
var ediBillName=$("#ediBillNumber").val();
var billId=$("#billId").val();
var claimantFirstName=$("#claimantFirstName").val();
var claimantLastName=$("#claimantLastName").val();
var insurerName=$("#insurerName").val();
var insurerFEIN=$("#insurerFEIN").val();
var insurerZip=$("#insurerZIP").val();
var dashboardSearchResultModel= new dashboardSearchResult();
var dashboardSearchResultModel= new dashboardSearchResult();
dashboardSearchResultModel.fetch({
data:{
productType: productType,
customerId: customerId,
state:stateSelected,
srbStatus:srbStatus,
dateType:dateType,
fromDate:fromDate,
toDate:toDate,
billTypeInd:billTypeInd,
dataElement:dataElement,
ediFileName:ediFileName,
ediBillName:ediBillName,
billId:billId,
claimantFirstName:claimantFirstName,
claimantLastName:claimantLastName,
insurerName:insurerName,
insurerFEIN:insurerFEIN,
insurerZip:insurerZip
},
wait:true,
success: function(dashboardSearchResultModel)
{
alert("This is what we get for result"+JSON.stringify(dashboardSearchResultModel));
$('#dashboardResultArea').html(self.dashboardResultTemplate({results:dashboardSearchResultModel.get("results")}));
},
error: function (model, xhr, options) {
alert("Error: An error occurred while trying to fetch the dashboardSearchResultModel");
alert("Error got model"+JSON.stringify(model));
alert("options:"+JSON.stringify(options));
alert("xhr:"+JSON.stringify(xhr));
}
});
Initially when the page loads after providing the search criteria's if I click submit the fetch doesn't work and goes to the error handler. After that when I submit the from second time the fetch works and retrieves data from the backend server. Any idea what is wrong? Thanks in advance.
When error callback is called, it is because your XHTMLRequest to the server returned a error (HTTP status code). So, there is where your problem resides.
Who starts this code? As the erros does not occur on a second attempt, I would suggest that you area callind $('#id').val() when the DOM is not ready. This way you are sending null values to the server, and that's causing the error you are receiving.
To solve your problem, assure you DOM is ready when executing this script.
See if your request is leaving the browser and reaching the server (i.e., cross-domain request fail with status 0, not reaching the server).
And, if it is, debug your server-side, as it does not seem to be an client-side problem.
So after trying many things I finally decided to try $.ajax call rather the fetch method. This is what I came up with
$.ajax({
type: "GET",
url: "rest/dashboardResult",
dataTyp: 'json',
data: {
productType: productType,
customerId: customerId,
state:stateSelected,
srbStatus:srbStatus,
dateType:dateType,
fromDate:fromDate,
toDate:toDate,
billTypeInd:billTypeInd,
dataElement:dataElement,
ediFileName:ediFileName,
ediBillName:ediBillName,
billId:billId,
claimantFirstName:claimantFirstName,
claimantLastName:claimantLastName,
insurerName:insurerName,
insurerFEIN:insurerFEIN,
insurerZip:insurerZip
}
})
.done(function(response) {
alert( "Result is: " + response);
});
This works without any problem from the get go. Now my question is how to bind the response to the backbone model?
Finally I figured out what was wrong. The call was inside a submit click handler, and $.ajax call or fetch is asynchronous. So by the time the call got reply from the server default action of submit click already took place (which is to reload the page). So by the time success or .done got called the whole page was reloaded. So I put event.preventDefault() at the beginning of handler method and let the handler receive the call back from the server and display it at the template. Thanks everyone for your time.

Backbone js collection.create() how to only update view when server side save succeeds

I've looked for ages for this and have seen lots of similar posts and answers, but nothing that's exactly what I'm after. I may be approaching this the wrong way.
I'm trying to add a new model to a collection, but I want to do server side validation. If the server validation fails, I don't want the new model to be added in the (collection's) view.
NB. the situation is when I get a 200 success response code (my backend is cakephp, and cakephp receives the request and processes fine), but server validation means no save to database (i.e., I don't want to add to database because it would create an unwanted duplicate).
Here's my backbone code :
//
// Add the selected school as a school the user manages.
addTeacherSchool: function(view) {
attribs = view.model.attributes;
attribs.school_id = attribs.id;
delete attribs.id;
attribs.user_id = this.model.id;
this.teacherSchoolListView.collection.create(
attribs, {wait: true, success: this.addTeacherSchoolSuccess}
);
},
addTeacherSchoolSuccess: function(model, resp, options) {
// resp is false
},
In my backbone SchoolListView (this.teacherSchoolListView is an instance of SchoolListView) I have the code (in initialize:) :
this.listenTo(this.collection, 'add', this.render);
On the server side (cakephp), I return false if I already have a 'copy' of the model :
return new CakeResponse(array('body' => json_encode($error_count == 0)));
As you can see, I'm using wait: true in my collection.create() call. What that is doing atm is waiting until the response is back from the server before adding the 'item' to the view. BUT I don't want the item added if server side validation returns an error.
Also, addTeacherSchoolSuccess() is called (which should be happening because there is no error in the req. / resp. cycle, just in the server side validation.
Any ideas on how to achieve what I'm after?
NB. I can (and do actually - though I've removed it so my code snippets are simpler) do validation client side, but I also want my server side validation to function.

destroy always returns with the error callback (although everything seems to be ok)

I'm trying to delete a model on my backend and what I do is this (the code is adapted just to show you the issue, some parts could be missing):
attending= new Backbone.Model();
attending.url= this.url() + "/reject";
attending.set({
id: this.id
})
attending.destroy({
success: function(){
alert("yes");
},
error: function(){
alert("no");
}
});
but what I always obtain is a "no" alert. The fact is the backend seems to be updated correctly and what I obtain as a response too. Here it is:
so... what's wrong with the response I get? Why doesn't backbone recognizes it as a successful response? I get 200/OK and a "application/json" format as well!
Your backend should return something with 200
jQuery expect 200 with application/json to have some content
Have a look here: https://github.com/jashkenas/backbone/issues/2218#issuecomment-20991938
You might want to place a "debugger;" in the error callback and trace exactly why its coming that route vs the success route. That should atleast get your started on the right path...

BackboneJS model.fetch() unsuccessful

Hi I have this model :
window.shop = Backbone.Model.extend({
initialize: function () {
console.log('initializing shop');
},
urlRoot: "shopData.json",
});
and then i go :
var myShop = new shop();
myShop.fetch({
success: function (model, resp){
console.log(resp);
},
error: function (model, resp){
console.log("error retrieving model");
}}, {wait: true});
now I'm always getting the error message - never reaching success :-(
thanks for any help.
Edit 1:
As per your comment the server is sending the proper response but Backbone is still calling the error function. Add the following line at the beginning of the error callback:
error: function (model, resp){
console.log('error arguments: ', arguments);
console.log("error retrieving model");
}
The first line should print an array of objects. The first element in the array should the jqXhr object, the second should be a string representation of the error. If you click on the first object, the dev tools will let you inspect its properties. Read up on the properties of the object here http://api.jquery.com/jQuery.ajax/#jqXHR.
Using that information you can verify if the jQuery is receiving an error from the server.
If there is no server side error, then check the value of the responseText property. That holds the string data returned from the server. $.ajax will try to parse that data into JSON. Most likely the parsing is throwing an error and the error handler is being raised instead.
Copy the response text and paste it into http://jsonlint.com/. Verify that the response sent from the server is valid JSON. Do update your question with the output of the console.log statement and the responseText property of the jqxhr object.
-x-x-x-
You seem to be using the model independently. As the per the documentation, http://backbonejs.org/#Model-url,
Generates URLs of the form: "/[urlRoot]/id"
That means, you are making a request to shopData.json/id. Also, you haven't specified the id.
Insert a console.log(myShop.url()) before the myShop.fetch(). Let us know whats the output. Also, possibly share the details of the ajax request as seen in Firebug or Chrome Dev Tools. I am interested in two things, the request url and the response returned by the server. (http://getfirebug.com/network)

Resources