this.store.create wont fire inside ajax call - sencha-touch

I simply am trying to update local storage but inside the Ext.Ajax.request I cant call this.store.create(). How do I call the this.store.create function inside the success: area of the Ajax call. Many thanks for your help.
login: function(params) {
params.record.set(params.data);
var errors = params.record.validate();
if (errors.isValid()) {
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
//now check if this login exists
Ext.Ajax.request({
url: '../../ajax/login.php',
method: 'GET',
params: params.data,
form: 'loginForm',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
myMask.hide();
//success they exist show the page
if(obj.success == 1){
//this doesn't work below
this.store.create(params.data);
this.index();
}
else{
Ext.Msg.alert('Incorrect Login');
}
},
failure: function(response, opts) {
alert('server-side failure with status code ' + response.status);
myMask.hide();
}
});
}
else {
params.form.showErrors(errors);
}
},

In Javascript, 'this' keyword changes its meaning with the context it appears in.
When used in a method of an object, 'this' refers to the object the method immediately belong to. In your case, it refers to the argument you passed to Ext.Ajax.request.
To work around this, you need to keep an reference of the upper level 'this' in order to access its 'store' property in an inner context. Specifically, it looks like this:
var me = this,
....;
Ext.Ajax.Request({
...
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
myMask.hide();
//success they exist show the page
if(obj.success == 1){
me.store.create(params.data);
this.index();
}
else{
Ext.Msg.alert('Incorrect Login');
}
},
});

Related

In Processing web service data, Why m.prop is not required?

Note that this getter-setter holds an undefined value until the AJAX
request completes.
var users = m.prop([]); //default value
var doSomething = function() { /*...*/ }
m.request({method: "GET", url: "/user"}).then(users).then(doSomething)
But following code is not used m.prop. Why?
Are you set the default value in a different way?
//model
var User = {}
User.listEven = function() {
return m.request({method: "GET", url: "/user"}).then(function(list) {
return list.filter(function(user) {return user.id % 2 == 0});
});
}
//controller
var controller = function() {
return {users: User.listEven()}
}
If ok in the above code, and useless in the following?
var doSomething = function() { /*...*/ }
m.request({method: "GET", url: "/user"}).then(doSomething)
https://lhorie.github.io/mithril/mithril.request.html
The listEven code works because both m.prop and m.request returns a GetterSetter, but when using m.request the GetterSetter will be populated with the value returned from the promise. It's quite convenient.
And in the last example there is no GetterSetter involved, it's a simple promise usage. So all three examples works fine. To decide which one is best, you have to look at your specific case.

ExtJS: Next method executes even before Ext.Ajax.request completes

Below is one function defined in my Extjs code.
updateJob : function(button,grid, record) {
var activeAccordianName = _myAppGlobal.getController('RFBAccordiansController').getActiveAccordianName();
if(activeAccordianName == 'Lookup') {
var win = button.up('window'),
form = win.down('form'),
record = form.getRecord(),
values = form.getValues();
var oldRecord = new Object();
oldRecord.environment=record.get('environment');
.........
..........
win.close();
this.submitLookupJobUpdateForm(oldRecord,values);
record.set(values);
}
},
Everything works fine until the "this.submitLookupJobUpdateForm(oldRecord,values);" is called. This method has an Ajax request which executes perfectly but takes some time since I am fetching some data from the database. But the next statement "record.set(values);" gets executed even before the Ajax request completes. Below is the submitLookupJobUpdateForm method code
submitLookupJobUpdateForm: function(oldRecord,values){
Ext.Ajax.request({
url : './LookupUpdateController/LookupUpdate/UpdateJob.do',
method : 'POST',
params :
{
record : Ext.JSON.encode(oldRecord),
newValues : values
},
success : function(response)
{
var jobInfoJson=response.responseText;
if (jobInfoJson != "" & jobInfoJson != "[]")
{
alert("Updating row");
} else
{
Ext.MessageBox.alert("Failed","Update Failed");
}
}
});
},
Can anyone please suggest what should I do so that the "record.set(values);" is called after the completion of Ajax request. Thanks in advance.
The Ajax request is being performed asynchronously so it wont pause your code until the request completes, which is why your record.set() is being called immediately after your submitLookupJobUpdateForm() call.
I suggest you move your record.set() call into a separate function that gets called in your success handler.
This kind of thing:
submitLookupJobUpdateForm: function(oldRecord,values){
Ext.Ajax.request({
url : './LookupUpdateController/LookupUpdate/UpdateJob.do',
method : 'POST',
params :
{
record : Ext.JSON.encode(oldRecord),
newValues : values
},
success : function(response)
{
var jobInfoJson=response.responseText;
if (jobInfoJson != "" & jobInfoJson != "[]")
{
//alert("Updating row");
this.processRowUpdate();
} else
{
Ext.MessageBox.alert("Failed","Update Failed");
}
},
scope:this
});
},
processRowUpdate: function() {
record.set(...);
}
This way you can be sure your record.set() waits until the Ajax has succeeded.

How we get and post api in Titanium alloy?

How can we get and post api in Titanium alloy?
I am having the api of userDetails, I just want that how can i code to get the data from api.
function getUserDetails(){
}
Thanks in advance.
As you mentioned, you are using Titanium alloy.
So another approach be to extend the Alloy's Model and Collection ( which are based on backbone.js concept ).
There are already some implementation at RestAPI Sync Adapter also proper description/usage at Titanium RestApi sync.
I also provide the description and methodology used, in-case link gets broken:
Create a Model : Alloy Models are extensions of Backbone.js Models, so when you're defining specific information about your data, you do it by implementing certain methods common to all Backbone Models, therefor overriding the parent methods. Here we will override the url() method of backbone to allow our custom url endpoint.
Path :/app/models/node.js
exports.definition = {
config: {
adapter: {
type: "rest",
collection_name: "node"
}
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
url: function() {
return "http://www.example.com/ws/node";
},
});
return Collection;
}
};
Configure a REST sync adapter : The main purpose of a sync adapter is to override Backbone's default sync method with something that fetches your data. In our example, we'll run through a few integrity checks before calling a function to fetch our data using a Ti.Network.createHTTPClient() call. This will create an object that we can attach headers and handlers to and eventually open and send an xml http request to our server so we can then fetch the data and apply it to our collection.
Path :/app/assets/alloy/sync/rest.js (you may have to create alloy/sync folders first)
// Override the Backbone.sync method with our own sync
functionmodule.exports.sync = function (method, model, opts)
{
var methodMap = {
'create': 'POST',
'read': 'GET',
'update': 'PUT',
'delete': 'DELETE'
};
var type = methodMap[method];
var params = _.extend(
{}, opts);
params.type = type;
//set default headers
params.headers = params.headers || {};
// We need to ensure that we have a base url.
if (!params.url)
{
params.url = model.url();
if (!params.url)
{
Ti.API.error("[REST API] ERROR: NO BASE URL");
return;
}
}
//json data transfers
params.headers['Content-Type'] = 'application/json';
switch (method)
{
case 'delete':
case 'create':
case 'update':
throw "Not Implemented";
break;
case 'read':
fetchData(params, function (_response)
{
if (_response.success)
{
var data = JSON.parse(_response.responseText);
params.success(data, _response.responseText);
}
else
{
params.error(JSON.parse(_response.responseText), _response.responseText);
Ti.API.error('[REST API] ERROR: ' + _response.responseText);
}
});
break;
}
};
function fetchData(_options, _callback)
{
var xhr = Ti.Network.createHTTPClient(
{
timeout: 5000
});
//Prepare the request
xhr.open(_options.type, _options.url);
xhr.onload = function (e)
{
_callback(
{
success: true,
responseText: this.responseText || null,
responseData: this.responseData || null
});
};
//Handle error
xhr.onerror = function (e)
{
_callback(
{
'success': false,
'responseText': e.error
});
Ti.API.error('[REST API] fetchData ERROR: ' + xhr.responseText);
};
for (var header in _options.headers)
{
xhr.setRequestHeader(header, _options.headers[header]);
}
if (_options.beforeSend)
{
_options.beforeSend(xhr);
}
xhr.send(_options.data || null);
}
//we need underscore
var _ = require("alloy/underscore")._;
Setup your View for Model-view binding : Titanium has a feature called Model-View binding, which allows you to create repeatable objects in part of a view for each model in a collection. In our example we'll use a TableView element with the dataCollection property set to node, which is the name of our model, and we'll create a TableViewRow element inside. The row based element will magically repeat for every item in the collection.
Path :/app/views/index.xml
<Alloy>
<Collection src="node">
<Window class="container">
<TableView id="nodeTable" dataCollection="node">
<TableViewRow title="{title}" color="black" />
</TableView>
</Window>
</Alloy>
Finally Controller : Binding the Model to the View requires almost no code at the controller level, the only thing we have to do here is load our collection and initiate a fetch command and the data will be ready to be bound to the view.
Path :/app/controllers/index.js
$.index.open();
var node = Alloy.Collections.node;
node.fetch();
Further reading :
Alloy Models
Sync Adapters
Hope it is helpful.
this is the solution for your problem:-
var request = Titanium.Network.createHTTPClient();
var done=false;
request.onload = function() {
try {
if (this.readyState == 4 && !done) {
done=true;
if(this.status===200){
var content = JSON.parse(this.responseText);
}else{
alert('error code' + this.status);
}
}
} catch (err) {
Titanium.API.error(err);
Titanium.UI.createAlertDialog({
message : err,
title : "Remote Server Error"
});
}
};
request.onerror = function(e) {
Ti.API.info(e.error);
};
request.open("POST", "http://test.com");
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send({ test: 'test'});
if you don't get your answer please let me know.
Thanks

Sencha Touch: setValue on TextField does not work

In Sencha Touch 2 I have a controller which calls a custom 'prepopulate' method on button tap:
Ext.Ajax.request
({
method: 'GET',
url: myurl, //defined outside
withCredentials: true,
headers:{Authorization : auth},
success: function(response){
var data;
if(response.responseText.length > 0)
data = Ext.JSON.decode(response.responseText.trim());
console.log(data);
var fv = me.getFiscal();
console.log(fv);
fv.prepopulate(data);
Ext.Viewport.animateActiveItem('fiscal', me.getSlideLeftTransition());
},
failure: function(response){
Ext.Msg.alert('Server Error', 'Server down :( please try again later');
}
}
);
View code:
prepopulate : function (data) {
var me = this;
var companyTextField = me.down('#fiscalForm').down('#companyTextField');
var vatField = me.down('#fiscalForm').down('#vatField');
var fiscalCodeTextField = me.down('#fiscalForm').down('#fiscalCodeTextField');
var addressTextField = me.down('#fiscalForm').down('#addressTextField');
var cityTextField = me.down('#fiscalForm').down('#cityTextField');
var zipTextField = me.down('#fiscalForm').down('#zipTextField');
var countryTextField = me.down('#fiscalForm').down('#countryTextField');
console.log(vatField);
console.log((data.vat));
if(data){
if(data.company_name)
companyTextField.setValue(data.company_name);
if(data.vat)
vatField.setValue(data.vat);
if(data.fiscal_code)
fiscalCodeTextField.setValue(data.fiscal_code);
if(data.address)
addressTextField.setValue(data.address);
if(data.city)
cityTextField.setValue(data.city);
if(data.zip)
zipTextField.setValue(data.zip);
if(data.country)
countryTextField.setValue(data.country);
}
console.log(vatField);
}
The AJAX call works fine and it calls on success the prepopulate method passing the data retrieved from the server.
I try to initialize the TextFields using setValue() but the form looks 'brand new' when I open it using the browser
console.log() tells me that the _value private field is correctly set though... I'm groping in the dark right now ... any insight?
Thank You in advance.
M.
As you suggest the data i correctly retrieved and display in the console with the console.log, nonetheless the browser don't find any visible fields to modify the value when the setValue() is called.
The solution so far is to modify the ajax request as follows:
Ext.Ajax.request
({
....
....
success: function(response){
....
Ext.Viewport.animateActiveItem('fiscal', me.getSlideLeftTransition());
//view must be in the viewport before modifying data:
var task = Ext.create('Ext.util.DelayedTask', function () {
var fv = me.getFiscal();
fv.prepopulate(data);
});
task.delay(1000);
.....
....
...
..
.

Knockoutjs - function inside viewmodel causing undesirable recursion

In my Knockout view model I have a Save() function which sends a jQuery POST request. Inside this POST request is a call to ko.toJS(this).
Whenever I call this Save function the browser becomes unresponsive and eventually tells me that there's too much recursion. Upon debugging (by using breakpoints), I found that when I call toJS() it appears to do some degree of cloning of the object, and in doing this cloning it calls the Save() function, which in turn calls toJS()... and there's the recursion.
Why exactly does this happen, and is there a way to avoid it without using toJSON()?
[I have another question regarding toJSON, and which explains why I don't want to use it.]
For the sake of completeness, here is my view model.
function vmDictionary(dict) {
if (dict === null || dict === undefined) {
return;
}
var self = this;
// directly-assigned variables
self.Concepts = new vmConcepts(dict.Concepts);
self.Deleted = ko.observable(dict.Deleted);
self.Description = ko.observable(dict.Description);
self.IncludeInSearch = ko.observable(true);
self.ID = ko.observable(dict.ID);
self.Languages = ko.observableArray(dict.Languages);
self.LastUpdate = new vmChangeRecord(dict.LastUpdate);
self.Name = ko.observable(dict.Name);
self.Public = ko.observable(dict.Public);
self.TemplateName = function(observable, bindingContext) {
return "dictionary-template";
};
// computed variables
self.PublicText = ko.computed(function() {
return sp.Utils.Localize(self.Public
? "Public"
: "Private");
});
// exposed functions
self.Save = function () {
$.ajax({
data: ko.toJSON(self),
dataType: "json",
type: "POST",
url: [...],
statusCode: {
200: function (response) {
console.log(response);
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log(xmlHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
};
}
UPDATE: added the entire view model (above).
You must be doing something wrong, works in a little fiddle for me
http://jsfiddle.net/brN9s/
ViewModel = function() {
this.someData = ko.observable("Test");
this.dto = ko.observable();
};
ViewModel.prototype = {
Save: function() {
this.dto(ko.toJS(this));
}
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
viewModel.Save();