JSON response empty when return Ajax Call - javascript

I am following a tutorial using Ext JS 4. I would like for a user to be able to login the application after being authenticated. I have already created the user name and password in the database.
The problem is my JSON response is coming back empty when I click my submit button.
I have an AJAX call in my Login.js controller that calls my login.php which establishes my database connection.
Login.js
Ext.define('Packt.controller.Login', {
extend: 'Ext.app.Controller',
requires: [
'Packt.util.MD5',
'Packt.util.Alert',
'Packt.view.MyViewport',
'Packt.util.Util',
'Packt.util.SessionMonitor'
],
views: [
'Login',
'Header',
'authentication.CapsLockTooltip'
],
refs: [
{
ref: 'capslockTooltip',
selector: 'capslocktooltip'
}
],
init: function(application) {
this.control({
"login form button#submit": {
click: this.onButtonClickSubmit
},
"login form button#cancel": {
click: this.onButtonClickCancel
},
"login form textfield": {
specialkey: this.onTextfielSpecialKey
},
"login form textfield[name=password]": {
keypress: this.onTextfielKeyPress
},
"appheader button#logout": {
click: this.onButtonClickLogout
}
});
Ext.apply(Ext.form.field.VTypes, {
// vtype validation function
customPass: function(val, field) {
return /^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,20})/.test(val);
},
// vtype Text property: The error text to display when the validation function returns false
customPassText: 'Not a valid password. Length must be at least 6 characters and maximum of 20Password must contain one digit, one letter lowercase, one letter uppercase, onse special symbol ##$% and between 6 and 20 characters.'
});
},
onButtonClickSubmit: function(button, e, options) {
var formPanel = button.up('form'),
login = button.up('login'),
user = formPanel.down('textfield[name=user]').getValue(),
pass = formPanel.down('textfield[name=password]').getValue();
if (formPanel.getForm().isValid()) {
pass = Packt.util.MD5.encode(pass);
Ext.get(login.getEl()).mask("Authenticating... Please wait...", 'loading');
Ext.Ajax.request({
url: 'php/login.php',
params: {
user: user,
password: pass
},
success: function(conn, response, options, eOpts) {
Ext.get(login.getEl()).unmask();
var result = Packt.util.Util.decodeJSON(conn.responseText);
if (result.success) {
//Packt.util.Alert.msg('Success!', 'User Authenticated.');
login.close();
Ext.create('Packt.view.MyViewport');
Packt.util.SessionMonitor.start();
} else {
Packt.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
Ext.get(login.getEl()).unmask();
Packt.util.Util.showErrorMsg(conn.responseText);
}
});
}
},
onButtonClickCancel: function(button, e, options) {
button.up('form').getForm().reset();
},
onTextfielSpecialKey: function(field, e, options) {
if (e.getKey() == e.ENTER){
var submitBtn = field.up('form').down('button#submit');
submitBtn.fireEvent('click', submitBtn, e, options);
}
},
onTextfielKeyPress: function(field, e, options) {
var charCode = e.getCharCode();
if((e.shiftKey && charCode >= 97 && charCode <= 122) ||
(!e.shiftKey && charCode >= 65 && charCode <= 90)){
if(this.getCapslockTooltip() === undefined){
Ext.widget('capslocktooltip');
}
this.getCapslockTooltip().show();
} else {
if(this.getCapslockTooltip() !== undefined){
this.getCapslockTooltip().hide();
}
}
},
onButtonClickLogout: function(button, e, options) {
Ext.Ajax.request({
url: 'php/logout.php',
success: function(conn, response, options, eOpts){
var result = Packt.util.Util.decodeJSON(conn.responseText);
if (result.success) {
button.up('mainviewport').destroy();
window.location.reload();
} else {
Packt.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
Packt.util.Util.showErrorMsg(conn.responseText);
}
});
}
});
login.php
<?php
require("db/db.php");
session_start();
// username and password sent from form
$userName = $_POST['user'];
$pass = $_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$userName = stripslashes($userName);
$pass = stripslashes($pass);
$userName = $mysqli->real_escape_string($userName);
$pass = $mysqli->real_escape_string($pass);
$sql = "SELECT * FROM USER WHERE userName='$userName' and password='$pass'";
$result = array();
if ($resultdb = $mysqli->query($sql)) {
// determine number of rows result set
$count = $resultdb->num_rows;
// If result matched $userName and $pass, table row must be 1 row
if($count==1){
$_SESSION['authenticated'] = "yes";
$_SESSION['username'] = $userName;
$result['success'] = true;
$result['msg'] = 'User authenticated!';
} else {
$result['success'] = false;
$result['msg'] = 'Incorrect user or password.';
}
/* close result set */
$resultdb->close();
}
/* close connection */
$mysqli->close();
//JSON encoding
echo json_encode($result);
?>
db.php
<?php
//$server = "192.168.0.11";
$server = "127.0.0.1";
$user ="mark";
$pass = "dog";
$dbName = "sakila";
$mysqli = new mysqli($server, $user, $pass, $dbName);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
I have also created a Login.js view page to display the pop up panel for user to login in.
Login.js view
Ext.define('Packt.view.Login', {
extend: 'Ext.window.Window',
alias: 'widget.login',
requires: [
'Packt.view.Translation'
],
autoShow: true,
height: 170,
width: 360,
layout: {
type: 'fit'
},
iconCls: 'key',
title: translations.login,
closeAction: 'hide',
closable: false,
items: [
{
xtype: 'form',
frame: false,
bodyPadding: 15,
defaults: {
xtype: 'textfield',
anchor: '100%',
labelWidth: 60,
allowBlank: false,
vtype: 'alphanum',
minLength: 3,
msgTarget: 'under'
},
items: [
{
name: 'user',
fieldLabel: translations.user,
maxLength: 25,
value: 'mark'
},
{
inputType: 'password',
name: 'password',
fieldLabel: translations.password,
enableKeyEvents: true,
id: 'password',
maxLength: 15,
value: '123456',
//vtype: 'customPass',
msgTarget: 'side'
}
],
dockedItems: [
{
xtype: 'toolbar',
dock: 'bottom',
items: [
{
xtype: 'translation'
},
{
xtype: 'tbfill'
},
{
xtype: 'button',
itemId: 'cancel',
iconCls: 'cancel',
text: translations.cancel
},
{
xtype: 'button',
itemId: 'submit',
formBind: true,
iconCls: 'key-go',
text: translations.submit
}
]
}
]
}
]
});
I am not sure how to debug this. I seems like it is making the database connection. but i not returning anything back. How can I authenticate this pre existing user and login?

Related

Extjs Catch pick event (combobox)

Using ExtJS 4.2.3. I have FORM with combobox field and some values inside on choose. I need to catch event when user pick 1 of the value in combobox.
Asking for help with syntax, as example to get ALERT on picking DATA3 value.
Name of combobox field - "document_type".
Example of code on ExtJS:
documentForm_window = Ext.create("Ext.window.Window", {
title: (document_GUID == null) ? "[Create]" : "[Edit]",
width: 500,
modal: true,
layout: "fit",
items: [{
xtype: "form",
frame: true,
waitMsgTarget: true,
listeners: {
afterrender: function (form) {
if (document_GUID != null) {
form.getForm().load({
url: Ext.state.Manager.get("MVC_url") + "/Document/Get",
method: "GET",
params: { document_GUID: document_GUID },
waitMsg: "[loading]",
timeout: 300,
failure: function (form, action) {
if (action.result) Ext.Msg.alert("[Error1]!", action.result.errorMessage);
else Ext.Msg.alert("[Error2]!", "[Error3]!");
}
});
}
}
},
defaults: {
anchor: "100%",
msgTarget: "side",
labelWidth: 145,
allowBlank: false
},
items: [{
xtype: "combo",
name: "document_type",
fieldLabel: "<b>[Type]<font color='Red'>*</font></b>",
displayField: "document_type_name",
valueField: "document_type",
queryMode: "local",
triggerAction: "all",
editable: false,
store: document_store
}, {
xtype: "textfield",
name: "contract_number",
fieldLabel: "<b>[TestData]</b>"
}],
formBind: true,
buttons: [{
text: (document_GUID == null) ? "[Create]" : "[Edit]",
handler: function () {
var action = (document_GUID == null) ? "Create" : "Edit";
var form = this.up("form").getForm();
if (form.isValid()) {
form.submit({
url: Ext.state.Manager.get("MVC_url") + "/Document/" + action,
params: { document_GUID: document_GUID, treasury_GUID: tree_value },
waitMsg: "[Loading...]",
success: function (form, action) {
documentForm_window.destroy();
OrderLines_store.load({
scope: this,
callback: function (records, operation, success) {
documents_List.query('*[itemId="DATA1_grid"]')[0].selModel.select(curr_position);
}
});
},
failure: function (form, action) {
if (action.result) Ext.Msg.alert("[Error1]!", action.result.msg);
else Ext.Msg.alert("[Error2]!", "[Error3]!");
}
});
}
}
}]
}]
}).show();
}
//store//
document_store = new Ext.data.ArrayStore({
fields: ["document_type", "document_type_name"],
data: [[0, "data1"], [1, "data2"], [2, "data3"]]
});
Sorry, part of code I add as screen cause of post error "It looks like your post is mostly code".
You have to add a listener for the select event to the combobox:
editable: false,
store: document_store,
listeners: {
select: function(combo, records) {
console.log(combo);
console.log(records);
if(!Ext.isArray(records)) records = [records];
Ext.each(records, function(record) {
if(record.get(combo.valueField)==3) {
Ext.Msg.alert('Value is 3 for' + record.get(combo.displayField));
}
});
}
}

Disable Checbox in Ext Js checkbox model

I have grid with checkboxmodel , As per my requirement I have to disable some checkbox in checkbox model and restrict user to select that row. I am able to achieve below code.
viewConfig: {
getRowClass: function (record, rowIndex, rowParams, store) {
return record.data.name == 'Lisa' ? 'bg' : "";
}
},
listeners: {
beforeselect: function ( test , record , index , eOpts ) {
return record.data.name == "Lisa" ? false : true;
}
}
above configs are used in grid and below is my css
.bg .x-grid-cell-row-checker{
background-color: grey;
pointer-events: none;
opacity: 0.4;
}
Everythings work fine only one issue is header checkbox is not working i.e not able deselectAll from header and able to select but not getting checked
Here is my working fiddle
Ext js version 5
Expanding on And-y's answer, I would construct my own class and do something like in this Fiddle. I did add a few things, like the isDisabled flag in the model, but I don't see that as a bad thing, and it greatly helps out with deciding how to show the checkbox/fixing the Check All checkbox logic.
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.define('MySelectionModel', {
extend: 'Ext.selection.CheckboxModel',
alias: 'selection.mySelectionModel',
// default
disableFieldName: 'isDisabled',
listeners: {
beforeselect: function (test, record, index, eOpts) {
return !record.get(this.disableFieldName);
}
},
renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
if (record.get(this.disableFieldName)) {
metaData.tdCls = 'bg';
}
else {
return this.callParent(arguments);
}
},
updateHeaderState: function () {
// check to see if all records are selected
var me = this,
store = me.store,
storeCount = store.getCount(),
views = me.views,
hdSelectStatus = false,
selectedCount = 0,
selected, len;
var disableFieldName = me.disableFieldName;
if (!store.isBufferedStore && storeCount > 0) {
selected = me.selected;
hdSelectStatus = true;
// loop over all records
for (var i = 0, j = 0; i < storeCount; i++) {
var rec = store.getAt(i);
var selectedRec = selected.getAt(j);
// Check selection collection for current record
if (selectedRec && selected.indexOf(rec) > -1) {
++selectedCount;
// Increment selection counter
j++;
}
// Otherwise, automatically consider disabled as part of selection
else if (rec.get(disableFieldName)) {
++selectedCount;
}
}
hdSelectStatus = storeCount === selectedCount;
}
if (views && views.length) {
me.toggleUiHeader(hdSelectStatus);
}
}
});
Ext.create('Ext.data.Store', {
storeId: 'simpsonsStore',
fields: ['name', 'email', 'phone', 'isDisabled'],
data: {
'items': [{
'name': 'Lisa',
isDisabled: true,
"email": "lisa#simpsons.com",
"phone": "555-111-1224"
}, {
'name': 'Bart',
"email": "bart#simpsons.com",
"phone": "555-222-1234"
}, {
'name': 'Homer',
"email": "homer#simpsons.com",
"phone": "555-222-1244"
}, {
'name': 'Marge',
"email": "marge#simpsons.com",
"phone": "555-222-1254"
}]
},
proxy: {
type: 'memory',
reader: {
type: 'json',
rootProperty: 'items'
}
}
});
Ext.create('Ext.grid.Panel', {
title: 'Simpsons',
store: Ext.data.StoreManager.lookup('simpsonsStore'),
selModel: {
selType: "mySelectionModel",
showHeaderCheckbox: true,
mode: 'MULTI',
allowDeselect: true,
toggleOnClick: false,
checkOnly: false
},
columns: [{
text: 'Name',
dataIndex: 'name'
}, {
text: 'Email',
dataIndex: 'email',
flex: 1
}, {
text: 'Phone',
dataIndex: 'phone'
}],
height: 200,
width: 400,
renderTo: Ext.getBody()
});
}
});
The problem occurs in the function updateHeaderState of the Ext.selection.CheckboxModel.
The function checks if all checkboxes are selected by hdSelectStatus = storeCount === selectedCount;. In your case selectedCount is not matching the storeCount and the state of the header checkbox is not updated.
You could extend the Ext.selection.CheckboxModel and override the updateHeaderState function to fit your needs.

EXTJS Passing Form Fields and Assigning Values to Variables in Controller

I'm trying to create a login form that mimics the call to a server and "authenticates" a users information.
Here's my Login.js code. this is the form I created:
Ext.define("ies.view.login.Login",{
extend: 'Ext.window.Window',
xtype: 'login',
requires: [
'ies.view.login.LoginController',
'Ext.form.Panel'
],
controller: 'login',
bodyPadding: 60,
draggable: false,
title: 'Login Window',
closable: false,
autoShow: true,
items: {
xtype: 'form',
reference: 'form',
itemId: 'LogInForm',
method: 'post',
items: [{
xtype: 'textfield',
name: 'username',
fieldLabel: 'Username',
itemId: 'username',
allowBlank: false
}, {
xtype: 'textfield',
name: 'password',
itemId: 'passwords',
inputType: 'password',
fieldLabel: 'Password',
allowBlank: false
}, {
xtype: 'displayfield',
hideEmptyLabel: false,
value: 'Enter any non-blank password'
}],
buttons: [{
text: 'Login',
formBind: true,
itemId: 'submit',
listeners: {
click: 'onLoginClick'
}
}],
}
});
This is my controller code:
Ext.define('ies.view.login.LoginController', {
extend: 'Ext.app.ViewController',
alias: 'controller.login',
onLoginClick: function(){
//var username = form.down('textfield[name=username]').getValue();
//var password = form.down('textfield[name=password]').getValue();
//get form field values
var username = this.lookupReference('username');
var password = this.lookupReference('password');
console.log(username + ' ' + password);
// This would be the ideal location to verify the user's credentials via
// a server-side lookup. We'll just move forward for the sake of this example.
/********************************************/
if ((username === 'carol' || username === 'denise' || username === 'coley' || username === 'yegappan' || username === 'julie' || username === 'dawn' || username === 'yvonne' || username === 'chuck' || username === 'belinda' || username === 'atlante' || username === 'blake' || username === 'ernie' || username === 'Patrick.Dwyer') && password === 'password1'){
/********************************************/
// Set the localStorage value to true
localStorage.setItem("TutorialLoggedIn", true);
console.log("Atuthenticated");
// Remove Login Window
this.getView().destroy();
// Add the main view to the viewport
Ext.widget('app-main');
} else {
document.getElementById("displayfield-1014-inputEl").innerHTML = "Authentication Failed";
console.log("Not authenticated");
}
}
});
I'm not sure how to pass the form fields and assign them to the username and password variables in the controller code. All help is really apreciated. Thanks!
I'm using EXTJS v 5.1
The name and itemId aren't relevant here. Instead, use the reference property in conjunction with lookupReference.

Extjs form submit

I searched hours and hours for a solution but can't find one. I want to submit something to a php api function. it looks like this:
/*global Ext:false */
Ext.onReady(function ()
{
var i = 0;
var form = Ext.create('Ext.form.Panel', {
title: 'base_entity_id',
bodyPadding: 5,
width: 350,
defaultType: 'textfield',
items: [{
fieldLabel: 'base_entity_id',
name: 'first',
allowBlank: false
}],
buttons: [{
text: 'Reset',
handler: function() {
this.up('form').getForm().reset();
}
}, {
text: 'Submit',
formBind: true,
//only enabled once the form is valid
disabled: true,
handler: function() {
var form = this.up('form').getForm();
}
}],
})
var tabs = Ext.create('Ext.tab.Panel',
{
renderTo: 'tabs',
id: 'tabs',
itemId: 'tabs',
fullscreen: true,
renderTo: document.body,
items:
[
{
title: 'Home',
margin: 40,
items: [form],
},
{
title: 'Results',
itemId: 'Results',
listeners:
{
activate: function (tab)
{
if(i == 0)
{
var panel = Ext.create('Ext.tab.Panel',
{
id: 'tabs2',
width: window,
height: window,
renderTo: document.body,
items:
[
{
title: '1',
itemId: '1',
closable: true,
html: '10329u9iwsfoiahfahfosaofhasohflhsalkfhoihoi3riwoifhoiashfkhasofhosahfsahfahsfosafoisaiohfaoishfoihsaoifasoifsaifhsaoifasoihfoiahsfoihasfoihasoifoisfoihsafoihasfoiasoihasfoihaoifhaoihfoiahfoiaoaffoafoiafsaoafohaoh'
},
{
title: '2',
itemId: '2',
closable: true,
}
]
})
tab.add(panel);
tab.doLayout();
i = 1;
}
}
}
}]
})
});
But when i'm submitting i get no response, can someone help me with this? I dont know what the next steps are...
I have a simple application done with Ext JS/PHP and the following code worked for me:
myFormPanel.getForm().submit({
clientValidation: true,
url: 'updateConsignment.php',
params: {
id: myFormPanel.getForm().getValues().first
},
success: function(form, action) {
Ext.Msg.alert('Success', action.result.msg);
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
break;
case Ext.form.Action.CONNECT_FAILURE:
Ext.Msg.alert('Failure', 'Ajax communication failed');
break;
case Ext.form.Action.SERVER_INVALID:
Ext.Msg.alert('Failure', action.result.msg);
}
}
});
Source:
http://docs.sencha.com/extjs/3.4.0/#!/api/Ext.form.BasicForm-method-submit
Well, you have set no URL for your form, and the submit button doesn't have the submit method so I'm not really sure how this was supposed to work.
You will need to add the url config to your form:
Ext.create('Ext.form.Panel', {
title: 'base_entity_id',
method: 'POST',
url: 'myBackEnd.php' // Or whatever destination you are using for your backend.
...
});
Also, I saw that you are using formbind: true and later checking if the form was valid, one action renders the other unnecessary, so choose one, there is no need for both!
Add this your button handler:
form.submit({
params: {
id: form.getForm().getValues().first
},
success: function(form, action) {
Ext.Msg.alert('Success', 'Your form was submitted successfully');
},
failure: function(form, action) {
Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
}
});
Then you should check for $_POST['id']
For more information on form methods and configurations check this doc: http://docs.sencha.com/extjs/5.0/apidocs/#!/api/Ext.form.Basic

EXT JS JsOnStore can't show in Grid Panel

vehicle.js
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', 'ux/');
Ext.require([
'Ext.tip.QuickTipManager',
'Ext.tree.*',
'Ext.data.*',
'Ext.window.MessageBox',
'Ext.window.*',
]);
Ext.onReady(function() {
Ext.QuickTips.init(); //tips box
Ext.define('MyApp.view.MyGridPanel', {
extend: 'Ext.grid.Panel',
renderTo: Ext.getBody(),
width: window.innerWidth,
header: false,
height: window.innerHeight,
store: UserStore,
initComponent: function() {
var me = this;
Ext.applyIf(me, {
columns: [
{
xtype: 'gridcolumn',
dataIndex: '_id',
text: 'Vehicle ID'
},
{
xtype: 'numbercolumn',
width: 126,
dataIndex: 'Plat_No',
text: 'Plat Number'
}
],
dockedItems: [
{
xtype: 'toolbar',
dock: 'top',
items: [
{
xtype: 'button',
cls: '',
width: 59,
icon: '',
iconCls: 'save',
text: 'Save'
},
{
xtype: 'button',
cls: '',
width: 59,
icon: '',
iconCls: 'edit',
text: 'Edit'
}
]
}
]
});
me.callParent(arguments);
}
});
var win = Ext.create('MyApp.view.MyGridPanel');
win.show();
Ext.define('VehicleModel', {
extend: 'Ext.data.Model',
fields: ['_id', 'Plat_No']
});
Ext.override(Ext.data.Connection, {
timeout : 840000
});
var UserStore = Ext.create('Ext.data.JsonStore', {
model: 'VehicleModel',
autoLoad: false,
proxy: {
type: 'ajax',
url: 'get-vehicle.php',
baseParams: { //here you can define params you want to be sent on each request from this store
//groupid: 'value1',
},
reader: {
type: 'json'
}
}
});
UserStore.load({
params: { //here you can define params on 'per request' basis
//groupid: 1,
}
})
}); // on ready
get-vehicle.php
<?php
mysql_connect("localhost", "root", "123456") or die("Could not connect");
mysql_select_db("db_shuttlebus") or die("Could not select database");
$parent_id = $_GET['groupid'];
$query = "SELECT * FROM tbl_vehicle";
$rs = mysql_query($query);
$arr = array();
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo json_encode($arr);
?>
but the grid panel still is blank, but the firebug return the get-vehicle.php like below
/localhost/BusTicket/vehicle/get-vehicle.php?_dc=1386449682081&page=1&start=0&limit=25
ParamsHeadersResponseHTML
[{"_id":"1","Plat_No":"PKN7711"},{"_id":"2","Plat_No":"AKC1234"},{"_id":"3","Plat_No":"ADB4333"}]
what is the problem?
In your proxy reader definition you have defined root to "images"
Because of this configuration reader expect JSON in this format:
{
'images': [
{"_id":"1","Plat_No":"PKN7711"},
{"_id":"2","Plat_No":"AKC1234"},
{"_id":"3","Plat_No":"ADB4333"}
]
}
If you remove root definition from your reader configuration, reader should process your current JSON format.
Problem Solved,
because UserStore need to be loaded before the grid panel load.
so, just modify the UserStore in front of grid panel. done

Categories

Resources