Currently I am using plugin called jQuery TagHandler. How can I link with database to listout data. I have listed code samples below. Below code are not working. Please correct me.
js
$("#array_tag_handler").tagHandler({
getData: { id: '1', type: 'user' },
getURL: '/tag/interest',
updateData: { id: 'user234', type: 'user' },
updateURL: '/ajaxtest/update',
autocomplete: true,
autoUpdate: true
});
PHP
$select_pos = "SELECT title FROM homegrid";
$select_exec = mysql_query($select_pos);
$return_data = array();
while($dataFromDB = mysql_fetch_assoc($select_exec)) {
$return_data[]= array(
"title" => $dataFromDB['title'],
);
}
header('Content-Type: application/json');
echo json_encode($return_data);
I have removed keys from my response {"availableTags":[{"title":"Music"},{"title":"Reading"}]}
Now the response look likes {"availableTags":["Music","Reading"],"assignedTags":["Music","Reading"]}
Related
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.
I use the following select2 Yii widget in my view to populate a drop-down list. Since the data necessary for the preparation of the select list consists of more than 2K records I use select2 with minimumInputLength parameter and an ajax query to generate partial result of the list based on user input. If I create a new record I have no problem at all. It populates everything fine and I can save data to my database. However I don't know how to load saved data back to this drop-down during my update action. I read somewhere that initselection intended for this purpose but I couldn't figure out how to use it.
Can someone help me out on this?
My view:
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
'allowClear'=>true,
'placeholder'=>'Kérem válasszon összetevőt!',
'minimumInputLength' => 3,
'ajax' => array(
'url' => Yii::app()->createUrl('etelOsszerendeles/filterOsszetevo'),
'dataType' => 'json',
'quietMillis'=> 100,
'data' => 'js: function(text,page) {
return {
q: text,
page_limit: 10,
page: page,
};
}',
'results'=>'js:function(data,page) { var more = (page * 10) < data.total; return {results: data, more:more }; }',
),
),
));?>
My controller's action filter:
public function actionFilterOsszetevo()
{
$list = EtelOsszetevo::model()->findAll('nev like :osszetevo_neve',array(':osszetevo_neve'=>"%".$_GET['q']."%"));
$result = array();
foreach ($list as $item){
$result[] = array(
'id'=>$item->id,
'text'=>$item->nev,
);
}
echo CJSON::encode($result);
}
I use initSelection to load existing record for update in this way (I replaced some of your view code with ... to focus in main changes). Tested with Yii 1.1.14. Essentially, I use two different ajax calls:
View:
<?php
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
...
...
'ajax' => array(
'url' => Yii::app()->createUrl('client/searchByQuery'),
...
...
'data' => 'js: function(text,page) {
return {
q: text,
...
};
}',
...
),
'initSelection'=>'js:function(element,callback) {
var id=$(element).val(); // read #selector value
if ( id !== "" ) {
$.ajax("'.Yii::app()->createUrl('client/searchById').'", {
data: { id: id },
dataType: "json"
}).done(function(data,textStatus, jqXHR) { callback(data[0]); });
}
}',
),
));
?>
Now in your controller you should receive parameters for ajax processing: query (q), as string, when inserting; id (id) as int when updating. Parameter names must be same as ajax data parameters (in this sample insert q; in update id) when read in $_GET. Code is not refactored/optimized:
Controller:
public function actionSearchByQuery(){
$data = Client::model()->searchByQuery( (string)$_GET['q'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
public function actionSearchById(){
$data = Client::model()->findByPk( (int) $_GET['id'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
Model - custom query and a little of order / security / clean :)
public function searchByQuery( $query='' ) {
$criteria = new CDbCriteria;
$criteria->select = 'id, ssn, full_name';
$criteria->condition = "ssn LIKE :ssn OR full_name LIKE :full_name";
$criteria->params = array (
':ssn' => '%'. $query .'%',
':full_name' => '%'. $query .'%',
);
$criteria->limit = 10;
return $this->findAll( $criteria );
}
EDIT:
It works out of box when update is preloaded with traditional HTTP Post (synchronous, for example with Yii generated forms). For async/Ajax updates, for example with JQuery:
Event / Trigger:
$('#button').on("click", function(e) {
...
... your update logic, ajax request, read values, etc
...
$('#select2_element').select2('val', id_to_load );
});
With this, initSelection will run again in async way with new id_to_load value, reloading record by id.
In your case and for your needs, initSelection could be complete different to avoid load record from db or you can use formatResult and formatSelection custom functions (are described in Load Remote Data sample source code). Reading documentation, I understand that initSelection's callback need JSON data with id and text elements to load properly or you could try to combine both concepts (this initSelection with your custom JS event/trigger call) (not tested):
'initSelection'=>'js:function(element,callback) {
// here your code to load and build your values,
// this is very basic sample
var id='myId';
var text='myValue';
data = {
"id": id,
"text": text
}
callback(data);
}',
Or directly on Trigger call:
$('#button').on("click", function(e) {
...
... ...
$("#select2_element").select2("data", {id: "myId", text: "MyVal"});
});
Hope that helps.
I tried doing that way, but couldn't do it
the solution I came up to get my record filled and selected was:
In case of the attribute having some data(in update mode or default value), I wrote some javascript that after document ready event, would fill the select with my data (just selected it ind pushed html in it), and made it selected, and then I rest( or update) the select to show my work.
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
});
Building a comment system with Ajax and JQuery and I want the div the comments are in to reload after a comment is added. It posts just fine. This is what I have so far.
The function getComments queries the database and generates the html
$.ajax({
type: "POST",
url: "post_comment.php",
data: dataString,
cache: false,
success: function(html){
????????? What should go here... it is a div with id#commentBody
}
<div id="commentBody">
<ul>
<?php
$q = "SELECT * FROM comment WHERE parent_id = 0 AND idpost = $postID";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)):
getComments($row,$postID,$custID);
endwhile;
?>
</ul>
</div>
Since you're regenerating the entire div I would use replaceWith.
$('#commentBody').replaceWith(html);
When you post it, you should return the data you want from your server side script. Then you can use the .html() jQuery function to update your div.
So, like:
$('#commentBody').html(html);
You could also return just the latest comment (optionally as a JSON object) and then just use the .append() method to add it to your #commentBody.
I would create a JSON object which has a status property and a data property. When the status is -1 (or whatever) there was an error adding the comment and you could put a message in the data property. When the status is 0, it was successful and the latest comment information would be available available in the data property.
Example
PHP
//Check postback variables, add comment and retrieve
// comment information (such as ID) if necessary
if (postedsuccessfully) {
$ary = array("status" => 0,
"data" => array("id" => $commentidvar,
"user" => $commentuser,
"text" => $comment)
);
echo json_encode($ary);
} else {
$ary = array("status" => -1,
"data" => "There was a problem adding your comment.");
echo json_encode($ary);
}
JavaScript
success: function(json){
if (json.status == 0) {
$mydiv = $('<div>');//construct your comment div using json.data.id,
//json.data.user, and json.data.text
$('#commentBody').append($mydiv);
} else {
alert(json.data);
}
}
my problem is that I
can not solve this problem
If I call the php script, all I get is an undefined error
this is the code I use for testing AND
this is the original code from the creator that is giving me a headache
function startJsonSession(){
$.ajax({ url: "jsontest.php?action=startjson",
cache: false,
dataType: "json",
complete: function(data) {
username = data.username;
alert(username);
}
});
}
//phpscript
if ($_GET['action'] == "startjson") { startJson(); }
function startJson() {
header('Content-type: application/json');
$items = '';
echo json_encode(array(
"username" => "bob",
"items" => array( "item1" => "sandwich",
"item2" => "applejuice"
)
));
}
thanks, Richard
edited my question because:
this function returns the json data in a different way
and therefore the solution presented below, does not have the same outcome.
function startChatSession() {
$items = '';
if (!empty($_SESSION['openChatBoxes'])) {
foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
$items .= chatBoxSession($chatbox);
}
}
if ($items != '') {
$items = substr($items, 0, -1);
}
header('Content-type: application/json');
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
exit(0);
}
I recreated with your code and figured it out. The object being returned is of type XMLHttpRequest. Its got a property called responseText holding a json string with the data.
so this works..
var decodedData = eval("(" + data.responseText + ")");
username = decodedData.username;
alert(username);
A bit messy but it does the trick :-)
p.s If it helps, I figured it out using firebug in firefox and sticking a breakpoint in the js code
Edited below:
Without wanting to do the eval, you could use this and it works:
$.getJSON("json.php?action=startjson",
function(data) {
username = data.username;
alert(username);
}
);
Edited to show what I did with the success function:
$.ajax({
url: "json.php?action=startjson",
cache: false,
dataType: "json",
success: function(data) {
username = data.username;
alert(username);
}
});
Is username a global variable?
If not you should prepend the "var" keyword.
username = data.username -> var username = data.username;
At the end I got it working.
I installed firebug and saw that the php script was returning html headers instead off json.
All off the sudden it started working, I really would like to know what the problem was, but I can't tell you.
Anyway, thanks for sticking so long, David
also what I don't understand is that it breaks out off php mode, instead of echoing it back like it's done with xml
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
is this the same as above (object array containing literal array)?
echo json_encode(array(
"username" => "bob",
"items" => $items
)
));
}