How to make a remote connection with database using sencha touch - sencha-touch

How to make a remote connection with database using sencha touch
I mean, how do you connect submitting the form to a remote database ?
How do you get the response from database that your form has been submitted successfully ?

You can do it by making an Ext.Ajax request.
Let's assume that your form has 3 fields:-
Name (textfield)
Password (passwordfield)
Age (numberfield)
You will get those fields values like shown below,
.....
.....
// form code ...
{
xtype:'button',
id:'submitBtn',
text:'Submit',
ui:'confirm',
listeners : {
tap : function() {
var form = Ext.getCmp('form-id');
var values = form.getValues();
Ext.Ajax.request({
url: 'http://www.servername.com/insert.php',
params: values,
success: function(response){
var text = response.responseText;
Ext.Msg.alert('Success', text);
}
failure : function(response) {
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
}
});
}
}
....
....
Now, at the server side, your insert.php code will make a connection with your database and insert the values & get the response back to the user.
<?php
$con = mysql_connect("server","username","password");
mysql_select_db('database_name',$con);
$insertQry = "INSERT INTO tableName(name,password,age) VALUES ('".$_POST['name']."','".$_POST['password']."','".$_POST['age']."')";
if(mysql_query($insertQry))
{
echo('success');
}
else
{
echo('failure' . mysql_error());
}
?>

Related

Angularjs - what are the possible reasons for duplicate records being inserted by the following code?

The following code is called on the click of a button
$scope.someFunction = function () {
$scope.submitting = true; // the button is disabled if submitting is true
var query = { query: { id: $scope.employeeID } };
// this api call inserts a record in a table
httpFactory.patch("/someURL", query).then(function (data) {
$scope.submitting = false;
if (data.error) {
// display error message
}
else {
// display success message
}
$scope.submitting = false;
}, function () {
$scope.submitting = false;
});
};
can duplicate records be inserted from the call above if a user has poor connectivity or if the server is slow and the request is not completed and soon another same request is received?
If so.. could any one please suggest a suitable way to handle this?

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.

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);
.....
....
...
..
.

File upload field in EXTJS MVC

Am having a form which consists of various text fields and combo boxes, along with a fileupload field. the file is being uploaded successfully, but when am trying to access the other form fields, they are not seen in the post parameters in the firebug. The code for the controller is given below:
uploadFile : function(button) {
**var form = button.up('form');
var Title = form.down('Title');
console.log(Title);** // This returns null
if (form.getForm().isValid()) {
form.getForm().submit({
url : 'data/Downloads.aspx',
waitMsg : 'Saving the file...',
params : {
mode : 'UPLOADFILE',
client : SYSTEM.CLIENT
},
success : function(f, a) {
Ext.Ajax.request({
url : 'data/Downloads.aspx',
params : {
mode : 'SAVE',
fileName : a.result.fileName
},
success : function() {
this.mWin = Ext.create('Campus.view.GenMessage');
this.mWin.addMessage(true, LANG.SUCT, LANG.SUCTxt2);
},
failure : function() {
}
});
},
failure : function() {
}
})
}
},
How do i access the other form fields and send it to the server.
I don't quite follow what you are doing. You seem to submit the form and then you are doing an ajax call to the server ???
Regardless, all form fields are sent to the server together with the file input. The framework does not use ajax to submit the form as usual because of the file upload, see the docs on this: http://docs.sencha.com/ext-js/4-1/#!/api/Ext.form.Basic-method-hasUpload
Thanks you for your guidance dbrin.
Actually, i was trying to uplaod a document, and at the same time save the information regarding the file in the database. And, thats why i was trying to make an AJAX request. But, here is what i did:
uploadFile : function(button) {
var form = button.up('form');
if (form.getForm().isValid()) {
form.getForm().submit({
url : 'data/Downloads.aspx',
waitMsg : 'Saving the file...',
params : {
mode : 'UPLOADFILE',
client : SYSTEM.CLIENT
},
success : function(form, a) {
this.mWin = Ext.create('App.view.GenMessage');
this.mWin.addMessage(true, LANG.SUCT, LANG.SUCTxt1);
},
failure : function() {
}
})
}
},

Sencha Touch Sync and Get New Data from Server

My app is a list of ToDo's of forms that need to be completed.
When the app is opened, it goes to the server and collects (from a database) a list of forms to be completed.
When you click on a form you can then fill in the data (using LocalStorage proxy) and then save/update the data. The data is stored locally on the device.
As of now : When I open the app again, it collects the same list of ToDo's and overwrites the data in the LocalStorage (ie my filled up forms) with new empty forms and therefore I need to fill them again.
What I want : Instead of overwriting filled up forms I need to only collect those forms that are not already in my localstorage.
My Code :
Store :-
Code:
FMS.stores.onlineTodo = new Ext.data.Store({
model: 'ToDoMod',
proxy: {
id : 'fmsonlinetodo',
type: 'ajax',
url: 'app/data/dummydata.json',
reader: new Ext.data.JsonReader({
root: 'items'
}),
timeout: 2000,
listeners: {
exception:function () {
console.log("I think we are offline");
flagoffline = 1;
//
}
}
}
});
FMS.stores.offlineTodo = new Ext.data.Store({
model : 'ToDoMod',
proxy : {
type : 'localstorage',
id : 'fmsofflinetodo'
}
});
Controller function that loads data into store :
Code:
loadDataInitial : function(){
FMS.stores.onlineTodo.addListener('load', function () {
console.log("I think we are online");
FMS.stores.offlineTodo.proxy.clear();
FMS.stores.onlineTodo.each(function (record) {
FMS.stores.offlineTodo.add(record.data)[0];
});
FMS.stores.offlineTodo.sync();
FMS.stores.offlineTodo.load();
flagoffline = 0;
});
if(flagoffline == 0){
FMS.stores.onlineTodo.load();
}
else{
FMS.stores.offlineTodo.load();
}
},
HELP !!!!!
If I'm not mistaken, you are clearing all of your localStorage records when you use this:
FMS.stores.offlineTodo.proxy.clear();
What you would want to do is use the online store to collect all of the database records and then for each record, query local storage for the same record and if it exists, don't update it.
Basically a version control approach but definitely don't clear the store, you will delete everything in it!
UPDATED:
Here is some sample code:
//load remotestore
remoteStore.load({
scope: this,
callback: function (records, operation, success) {
//get record count
var localCount = localStore.getCount();
if (localCount == 0) {
//iterate each record in remotestore
remoteStore.each(function (record) {
//add record to localStorage
localStore.add(record.copy());
});
//save localstore
localStore.sync();
} else {
//set count var
var count = 0;
//iterate each record in remotestore
remoteStore.each(function (record) {
//reset var
var localRecord = null;
//find matching record in localstore
localRecord = localStore.findRecord('xid', record.data.xid, null, false, false, true);
//if the record exists
if (localRecord) {
//version check
if (record.data.version > localRecord.data.version) {
//remove record from localstore and add new one
localStore.remove(localRecord);
localStore.add(record.copy());
//increment counter
++count;
}
} else {
//add record to localstore
localStore.add(record);
}
});
//save localstore
if (localStore.sync()) {
alert("store saved");
}
//if records were added we need to reload
if (count > 0) {
this.onUpdate();// or whatever your function is.
}
}
}
}); //ends
in your store's load method, just pass addRecords:true, like so:
FMS.stores.onlineTodo.load({addRecords: true});