pass combobox value to php extjs 4 - php

I want to pass a combobox value to a PHP file that'll execute a mySQL query. I'm using Extjs 4 with the MVC architecture. This is my combobox :
{
xtype: 'combobox',
id: 'cmbMetric',
name: 'sev',
mode: 'queryMode',
//querymode : 'lcoal',
fieldLabel: 'Metric',
store: 'MetricsData',
editable: false,
valign : 'middle',
margin : 15,
displayField:'name_metric',
valueField : 'id_metric'
}
My store :
Ext.define('Metrics.store.GuiData', {
extend: 'Ext.data.Store',
model: 'Metrics.model.GuiData',
autoLoad: true,
idProperty: 'id_metric',
proxy : {
type : 'ajax',
actionMethods : 'POST',
api : {
read : 'gui_comp_items.php'
},
reader: {
type: 'json',
successProperty: 'success',
messageProperty: 'message',
root: 'data'
}
}
});
When I choose a combobox value, this function is called by the controller :
onSelectedValue : function(combo) {
var selected = combo.getValue();
var guiDataStore = this.getGuiDataStore();
guiDataStore.getProxy().url = 'gui_comp_items.php?id_metric=' + selected ;
guiDataStore.load({
params : {
id_metric : selected //The parameter I want to send to the php file
},
callback:this.onGuiDataLoad,
scope: this
});
}
My php file :
function guiCompItems()
{
$id_metric = $_GET['id_metric'];
$sql = 'select m.id_metric, f.name_filter, gui.type_guicomp from gui_comp gui inner join filter f inner join metric m
on f.id_guicomp = gui.id_guicomp
and f.id_metric = m.id_metric
where m.id_metric ='. mysql_real_escape_string(trim(intval($_GET['id_metric'])));
$result = mysql_query($sql); // result set
while($rec = mysql_fetch_array($result, MYSQL_ASSOC)){
$arr[] = $rec;
};
$data = json_encode($arr); //encode the data in json format
echo '({"success": "true", "message" : "OK","data":' . $data . '})';
}
The data is always "null". I think that the parameter is not sent to the php file.
Any help would be much much appreciated. Thanks.

Store load doesn't actualy encode the params config in the request. The request is made by the proxy configured for the store so any other params you need to send should be set in the proxy's extra params config. Like:
guiDataStore.getProxy().url = 'gui_comp_items.php?id_metric=' + selected ;
guiDataStore.getProxy().extraParams = {
id_metric : selected //The parameter I want to send to the php file
};
guiDataStore.load({
callback:this.onGuiDataLoad,
scope: this
});

Related

How to write values coming from form input to json using php

Since I needed a server side language I used PHP. However I cannot write the data coming from the ajax using the JSON.stringify method.
$('#add-order').on('click',function(){
//create an object for orders
var order = {
name : $('#name').val(),
drink : $('#drink').val()
};
$.ajax({
url : 'add_order.php',
type : 'POST',
data : order,
dataType : 'json',
success : function(newOrder){
console.log(newOrder.name);
$('#orders').append('<li>' + newOrder.name + ' : ' + newOrder.drink + '</li>');
},
error: function(){
console.log('error connecting');
}
});
});
Here's the index.php
<h4>Add a Coffee Order</h4>
<ul id="orders">
</ul>
<p><input type="text" id="name"></p>
<p><input type="text" id="drink"></p>
<button type="submit" id="add-order">Add</button>
add_order.php
if (isset($_POST['submit'])) {
$orders = $_POST['data'];
$orderFile = fopen('api/orders.json', 'w');
fwrite($orderFile, $orders);
fclose($orderFile);
}
When I hard coded any string to fwrite($orderFile, "my orders") it will write on the orders.json however when I used the $orders it's not working. Am i missing something here?
you're posting to api/orders.json which is incorrect, you should be posting to the file that processes the request, like index.php.
Passing an object as the data parameter does not convert it to json, you have to actually do it yourself. So if you want $_POST['data'] to hold the order data as json
$.ajax({
url : 'index.php',
type : 'POST',
data : {data: JSON.strinify(order)},
dataType : 'json',
success : function(newOrder){
console.log(newOrder.name);
$('#orders').append('<li>' + newOrder.name + ' : ' + newOrder.drink + '</li>');
},
error: function(){
console.log('error connecting');
}
});
Anyways I found already the solution. First I did was to serialize the inputs instead of using stringify.
var order = {
name : $('#name').val(),
drink : $('#drink').val()
};
var inputs = $('form').serialize();
$.ajax({
url : 'add_order.php',
type : 'POST',
data : inputs,
dataType : 'json',
//some codes here...
});
Then in my php file which is the add_order.php, I fetch the values passed by the data and make them as an array. I also make used of file_get_contents to read on the json file and file_put_content to write on the file as json.
$ordersFile = 'api/orders.json';
$order = array();
//grab the form input
$formData = array(
'name' => $_POST['name'],
'drink' => $_POST['drink']
);
$jsonOrders = file_get_contents($ordersFile);
$order = json_decode($jsonOrders, true);
echo json_encode($formData);
array_push($order, $formData);
file_put_contents($ordersFile, json_encode($order, JSON_PRETTY_PRINT));
But if you still have shorter solution then let me know.

extjs4 store set extraParam dynamically not working

Good day. I have an unsettling error that I've encountered recently and I do not know where it came from or how it came about.
I have a form where I want to save data to the database upon button press which is handled by the controller. This is what I do in my controller:
var personStore = Ext.getStore('personBaseDetails');
var caStore = Ext.getStore('creditApplication');
var form = button.up('form').getForm();
var userId = personStore.first().get('ID');
//use this to update
if(caStore.count() < 1){
var creditApplication = Ext.ModelManager.create({
}, 'appName.model.creditApplicationModel');
caStore.add(creditApplication);
}
var record = caStore.first();
form.updateRecord(record);
console.log("user id to be edited is = " + userId);
console.log("caStore count = " + caStore.getCount());
caStore.getProxy().extraParams = {
selectedUserID: userId
};
// caStore.load();
caStore.sync({
success: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
},
failure: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
}
});
Here, I set the store extra param in order to use it in the php code query. However, the issue I have is that when I get the selectedUserID in the php code I have, I couldn't seem to get the extra parameter. If I commented out the if(isset($_GET['selectedUserID'])){ .... }, the query works (though the values are hardcoded as of now).
Here is what my store looks like:
Ext.define('app.store.creditApplication', {
extend: 'Ext.data.Store',
requires: [
'app.model.creditApplicationModel',
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json',
'Ext.data.writer.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
model: 'app.model.creditApplicationModel',
storeId: 'creditApplication',
clearOnPageLoad: false,
proxy: {
type: 'ajax',
api: {
create: 'data/person/creditApplication/createCreditApplication.php',
read: 'data/person/creditApplication/readCreditApplication.php',
update: 'data/person/creditApplication/updateCreditApplication.php'
},
url: '',
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json',
encode: true,
root: 'data'
}
}
}, cfg)]);
}
});
Now I'm dumbfounded since I have another code which is similar in the sense that I set the extraParam in the controller and the php code was able to receive and read it just fine. Note that both my stores do not have any extraParam property.
I've been stuck with this problem and I don't know how to go about it. Any help would be greatly appreciated.
Store does not have extraParam(s), proxy does. You can set it with:
store.getProxy().setExtraParam(name, value)

jQuery AJAX request returns object

I have the following AJAX request:
$(function(){
$("#MPrzezn").typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'test',
displayKey: 'value',
source: function(query, process){
$.ajax({
url: 'sprawdzKraj.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
console.log(data);
}
});
}
});
});
... and the following php on backend:
<?php
require_once 'core/init.php';
$user = new User(); //current User
if($user->isLoggedIn()){
if(isset($_POST['query'])){
$query = $_POST['query'];
$delegacja = new Delegacja();
$dataListaDelegacji = $delegacja->listujMiasta($query);
header('Content-Type: application/json');
$json_response = json_encode($dataListaDelegacji);
echo $json_response;
}
} else {
$isLoggedIn = false;
$smarty->assign("userid","",true);
$smarty->assign("isLoggedIn",$isLoggedIn,true);
Redirect::to('login.php');
}
The php script returns a proper json:
[{"ID":"66","IDKraju":"117","NazwaMiasta":"Inowroc\u0142aw","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"251","IDKraju":"117","NazwaMiasta":"\u015awinouj\u015bcie","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"2222","IDKraju":"74","NazwaMiasta":"Rhinow","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"3508","IDKraju":"94","NazwaMiasta":"San Bernardino","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null}]
The picture below shows how the json is being picked up by browser:
There are 4 cities that match the query - each object is a city entry
My goal is to pass values of "NazwaMiasta" to a typeahead input, but I get "undefined" entries. I tried different things but it always keeps showing undefined like this:
Red arrows show all 4 json nodes
I hope I described my problem well. I understand that I'm pretty close, but I cannot find the solution myself. I'll appreciate any help.
Thanks
You have to put right displayKey value!
insted of :
displayKey: 'value',
set :
displayKey: 'NazwaMiasta',
EDIT :
Detailed explanation : When you return data via ajax call, typeahead doesn't know what value to display. So you must set where is value for that key. Your return array of object that have structure like this :
['key1':'value1', 'key2':'value2',...]
By setting ie 'key1' , typeahead knows how to access value ie :
currentElement['key1']...
and than put that value to html.

ExtJS combobox set initial value dynamically from remote store on page load via PHP

My current issue relates to showing an initial value in an ExtJS combobox relating to an employee's department in an employee detail page.
The page retrieves the employee information via PHP, so all the references to the employee are done through PHP echo (the site uses CodeIgniter, which may confuse some; it just simplifies some of the input but works in the same way as normal PHP), i.e.
var formPanel = Ext.create('Ext.form.Panel', {
title: 'User Details',
width: 300,
renderTo: Ext.get('details'),
store: userStore,
defaultType: 'textfield',
items:
[
{
fieldLabel:'User Name',
name: 'UserName',
allowBlank: false,
value: '<?php echo $Employee->UserName; ?>'
},
//More details in similar format etc.
]
});
There is a section for the departments, to be handled through a combobox, to list all departments; there is nothing fancy (I believe), it just lists all the departments:
Ext.define('DeptModel', {
extend: 'Ext.data.Model',
fields: [
{name:'Id', type: 'int'},
{name:'Name', type: 'string'}
]
});
var deptStore = Ext.create('Ext.data.Store', {
model:'DeptModel',
autoload: true,
proxy: {
// load using HTTP
type: 'ajax',
url: '<?= $site_url ?>Settings/JSON/Departments',
reader: {
type: 'json',
model: 'DeptModel'
}
}
});
The formPanel above then references the deptModel/deptStore in a comboBox:
{
fieldLabel:'Department',
xtype:'combo',
name:'Department',
forceSelection: true,
typeAhead: true,
allowBlank: false,
emptyText: 'Choose a Department',
store: deptStore,
displayField: 'Name',
valueField: 'Id'
}
The above combobox renders correctly and provides all the departments. Attempts to initialise the combobox with a value, however, have not worked, ranging from no change in the combobox to creating errors that stop the page rendering. I have looked at the following:
value: 5 // or any integer
value: '5' // or any string
value: <?php echo $Employee->DepartmentId ?> // or any PHP reference like those that work for the textfields e.g. the User Name above - DepartmentId has been checked to be an integer
value: '<?php echo $Employee->DepartmentId ?>' // stringifying the PHP reference
value: 'Accounts'
I have also looked at the numerous posts relating to loading stores after rendering, setting values on store loading, setting values on render, setting values before the formPanel code; quite frankly, none have worked, and most refer to setting the value to the first in the list which doesn't treat my particular issue.
Ideally, I want to simply state
value: <?php echo $Employee->DepartmentId ?>
to have the combobox display the relevant department (i.e. "Accounts") when the employee's details are displayed in the form on page load.
Where am I going wrong? Why does value: {value} not do anything in practice? Can anyone provide a simple explanation as to the correct form of inserting a combobox into a formPanel that allows for the initial value in said combobox to be picked on page load, if the current implementation is somehow incorrect?
JsonStore:
var articleMain = new Ext.data.JsonStore({
model: 'ArticleMainGroup',
autoLoad: true,
proxy: {
type: 'ajax',
url: '<?php echo base_url() ?>dashboard/create',
extraParams: {
type: 'article_group_main'
},
reader: {
type: 'json',
root: 'articleMainGroup',
idProperty: 'ART_GROUP_ID'
}
}
});
Data Model :
Ext.define('ArticleMainGroup', {
extend: 'Ext.data.Model',
fields: [
{name: 'ART_GROUP_ID', type: 'int'},
{name: 'WHG', type: 'int'},
{name: 'WHG_BEZ', type: 'string'}
]
});
Controller:
public function create()
{
$type = $this->input->get('type', TRUE);
// this parameter comes from ExtJS Extraparam
switch ($type)
{
case 'dnr_type':
$data = $this->dnr->get_dnr_type();
exit(json_encode($data));
case 'dnr_definition':
$para = $this->input->get('dnrtype', TRUE);
$data = $this->dnr->get_dnr_definition($para);
exit(json_encode($data));
case 'article_group_main':
$data = $this->dnr->get_article_group_main();
exit(json_encode($data));
Model:
public function get_article_group_main()
{
$sql = $this->db->query('SELECT ART_GROUP_ID, WHG, CONCAT_WS(" - ", WHG, WHG_BEZ) AS WHG_BEZ FROM MD_ARTICLE_GROUP GROUP BY WHG_BEZ ORDER BY WHG');
return array('articleMainGroup' => $sql->result_array());
}
Here is your request :
{
fieldLabel:'Department',
xtype:'combo',
name:'Department',
forceSelection: true,
typeAhead: true,
allowBlank: false,
emptyText: 'Choose a Department',
store: deptStore,
displayField: 'Name',
valueField: 'Id',
id: 'cmb-department'
}
// Add a listener to the combobox before store load
var combo = Ext.getCmp('cmb-department');
var cmbStore = combo.store;
cmbStore.on('load', function() {
// setValue(777) // here, 777 is unique value that available in the store
combo.setValue(<?php echo $Employee->DepartmentId ?>)
})
I will try to help you but you should correct some mistakes. For instance, you had created data model like below :
Ext.define('DeptModel', {
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
reader: 'json'
},
fields: [
{name:'Id', type: 'int'},
{name:'Name', type: 'string'}
]
});
But, data model should be :
Ext.define('DeptModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'Id', type: 'int'},
...
]
});
So, you should define proxy properties in store config, not data model! The reason is that stores interact with server side, data model just modeling the data.
var deptStore = new Ext.data.JsonStore({
model: 'DeptModel',
proxy: {
type: 'ajax',
url: '<?php echo base_url() ?>Settings/JSON/Departments',
reader: {
type: 'json',
root: 'deptList',
idProperty: 'DEP_ID'
}
}
});
Here, I defined a simple store. You must take notice that root and idProperty properties. You should give a name of the Json object like below :
// return value from model
$sql = $this->db->query('SELECT DEP_ID, ......');
return array('deptList' => $sql->result_array());
// return value from controller
$data = $this->db->get_dept_list($arg);
echo json_encode('$data');
Also, idProperty is important which it should be unique value to be able to eliminate value conflict.
Here is the sample screen shot of my app. As you can see, when an user select a value from DNR TİPİ, app automatically populate the ÌNDİRİM TİPİNİ SEÇİNİZ combobox!
On the screen shot, discDetail equal your deptList.

Retrieve data with extjs 3.4 panel + dataview + jsonstore

i'm trying to show some data via dataview, but for some reason i am getting an emptytext message (No data).
Here is my dataview:
xtype : 'dataview',
emptyText : 'No data',
id : 'cartdata',
multiSelect : true,
plugins : new Ext.DataView.DragSelector( { dragSafe : true } ),
store : new Ext.data.JsonStore({
url : '/aecms/user-photos-view/',
autoLoad : true,
root : 'data',
fields : [
'images'
],
listeners : {
scope : this,
load : function(store) {
var data = store.reader.jsonData;
if (data.systemMessage) {
infoReport(data.systemMessage.title, data.systemMessage.message, data.systemMessage.icon);
}
}
}
}),
tpl : new Ext.XTemplate(
'<tpl for=".">',
'<tpl for="images">',
'<a title="{id}">test</a>',
'</tpl>',
'</tpl>'
)
and this is a data from php:
{"data":{"images":{"id":"2"}},"status":"success"}
I am new to extjs and appreciate any help.
By the looks of it you are not returning a successProperty value correctly. Change the response from you php code to be, as listed below.
The default successProperty of the JsonReader on your store is 'success'. ExtJs will look for this property in your server response.
http://docs.sencha.com/ext-js/3-4/#!/api/Ext.data.JsonReader-cfg-successProperty
Also, you will probably want to return your data as a json array, not an object. You dont need the image object inside the data array.
Server response:
{ "data":[{"id":"2"}], "success":true }
Javascript:
...
store : new Ext.data.JsonStore({
url : '/aecms/user-photos-view/',
autoLoad : true,
root : 'data',
fields : [
'id'
],
listeners : {
scope : this,
load : function(store) {
var data = store.reader.jsonData;
if (data.systemMessage) {
infoReport(data.systemMessage.title, data.systemMessage.message, data.systemMessage.icon);
}
}
}
})
tpl: new Ext.XTemplate(
'<tpl for=".">',
'<a title="{id}">test</a>',
'</tpl>'
)

Categories