Q1. How can convert [object Object] to word?
LIKE: [object Object] =to=> salam
Q2. How can append outputs result search[after click on it] in class .list with(mid) tow input.
LIKE: If resulet search was value salam and after click on it get as:
EXAMPLE:
[object Object] -> input ... & input ...
[object Object] -> input ... & input ...
[object Object] -> input ... & input ...
Js:
$('.auto_complete').keyup(function () {
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
//url: 'http://binboy.gigfa.com/admin/tour_foreign/auto_complete',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
var id_name = $('.list_autobox_hotel').attr('id');
$('.list_autobox_hotel').show().html('');
if (data == 0) {
$('.list_autobox_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p id="' + value.name + '">' + value.name + '</p>').appendTo('.list_autobox_hotel');
});
//////////////////////*HERE Q1//////////////////////
$('.list_autobox_hotel p').bind("click", function (e) {
e.preventDefault();
var ac = $(this).attr('id');
var ok = $.grep(data, function (e) {
return e.name == ac;
})[0].units;
//alert(ok);
/////////////*HERE Q2//// for append////////
$(ok).appendTo('.list');
/////////////HERE Q2*////////////
$(this).remove();
return false;
});
//////////////////////HERE Q1*//////////////////////
$('body').click(function () {
$(".list_autobox_hotel p").hide().remove();
$('.auto_complete').val('');
$('.list_autobox_hotel').show().html('');
$('.list_autobox_hotel').css('display', 'none');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
PHP[insert to database]:
$units = array();
$name_units = $this->input->post('name_units');
$price_units = $this->input->post('price_units');
$checkbox_units = $this->input->post('checkbox_units');
foreach ($name_units as $idx=>$name){
$units[] = array(
'name_units' => $name_units[$idx],
'price_units' => $price_units[$idx],
'checkbox_units' => $checkbox_units[$idx],
);
}
$data = array('name' =>$this -> input -> post('name'),
'units' => json_encode($units)
);
$this -> db -> insert('hotel_submits', $data);
PHP[select code]:
$data = array();
foreach ($query_hotel_search->result() as $row)
{
$units = json_decode($row->units);
$data[] = array('name' => $row->name, 'units' =>$units );
}
echo json_encode($data);
DEMO: There are here the contents of the database and output code PHP and test code for you => CLICK HERE
UPDATE: json response:
Output values salam & salavat of php code: [this values select(selcet * from ...) by json_encode()]
salam:
[{"name":"salam","units":[{"name_units":"salam","price_units":"74,554","checkbox_units":["minibar","mobleman"]},{"name_units":"mokhles","price_units":"4,851,269","checkbox_units":["mobleman","tv"]},{"name_units":"fadat","price_units":"85,642","checkbox_units":["minibar","mobleman","tv"]}]}]
salavat:
[{"name":"salavat","units":[{"name_units":"salam","price_units":"5,452","checkbox_units":null},{"name_units":"khobe","price_units":"5,452,545","checkbox_units":["minibar","mobleman"]}]}]
my answer is totally based on assumption you are getting this json as response when i searched "salam"
[
{
"name": "salam",
"units": [
{
"name_units": "salam",
"price_units": "74,554",
"checkbox_units": [
"minibar",
"mobleman"
]
},
{
"name_units": "mokhles",
"price_units": "4,851,269",
"checkbox_units": [
"mobleman",
"tv"
]
},
{
"name_units": "fadat",
"price_units": "85,642",
"checkbox_units": [
"minibar",
"mobleman",
"tv"
]
}
]
}
]
in the success callback iterate over the json as follow
if (data == 0) {
$('.list_autobox_hotel').show().html('<p><b>there is no</b></p>');
}
else
{
$.each(data[0].units, function (index, value) {
$('<p id="' + data[0].units[index].name_units + '">' + data[0].units[index].name_units + '</p>').appendTo('.list_autobox_hotel');
});
here is a demo hopefully you will get the idea http://jsfiddle.net/BBSyy/
EDIT
see this fiddle http://jsfiddle.net/BBSyy/1/
Another Edit
see this fiddle with grep example http://jsfiddle.net/BBSyy/3/
Related
How to display name one by one using ajax. It seem that my FOR looping is not working to push name one by one. Is there any step that i miss? Can someone point me to where/what i did wrong.
var names = [];
var profiles = {};
var restURL = "fetch.php";
function refresh() {
$.ajax({
method: 'GET',
url:restURL,
success: function (result, status, xhr) {
for (var k in result) {
var name = result[k].name;
if (!profiles.hasOwnProperty(name)) {
names.push(name);
profiles[name] = result[k];
}
}
}
});
}
var namei = -1;
function nextName() {
namei++;
if (namei > names.length - 1) {
namei = Math.max(1, names.length - 10) - 1;
}
console.log(namei + '/' + names.length);
$('.texts li:first', '.jumbotron #atname').text(profiles[names[namei]].name);
$('.texts li:first', '.jumbotron #atdiv').text(profiles[names[namei]].division);
$('.jumbotron .tlt').textillate('start');
setTimeout(function () {
$('.jumbotron .tlt').textillate('out');
}, 5000);
}
fecth.php
$i=1;
while ( $row = mysql_fetch_assoc($rs) ) {
$response['result'][] = array(
'staffno' => $row['g_idm'],
'name' => $row['g_name'],
'division' => $row['g_div']
);
$i++;
}
echo json_encode($response);
Though I have searched a lot, I was not able to get a concrete answer
client side code
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
dataType : "json",
url: myAjax.ajaxurl,
data: { action : "my_action",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " );
//console.log("success " + JSON.parse(response));
jQuery("#d_amount").val(donor_data[0]);
jQuery("#p_button").text("brrr");
},
error: function(response) {
console.log("error" + response);
},
});
});
});
server side code
function ajx_add_donations () {
global $wpdb;
$adv_don=json_decode($_REQUEST['donors']);
//$adv_don = json_decode($_POST['donors']);
//echo json_encode("phani");
//echo json_encode($result);
$dtype = 'OFFLINE';
$d_status = 'PENDING';
$ddate = current_time( 'mysql' );
$donation_e = array (
'UID' => $adv_don->id[0],
'STATUS' => $d_status,
'PMODE' => $dtype,
'AMNT' => $adv_don->amnt,
'DDATE' => $ddate
);
$d_id = update_donation_entry($donation_e);
echo json_encode("<h3> Thank you for Contribution <strong>$amount</strong></h3>");
wp_die();
}
Info needed
I'm not able to see my data base being updated, when I click the button,How to parse the Json data (array) at server side ?
Is there any way to know what I have received at server side, If I use "echo" to print a variable it is sent to ajax client ?
If answer to #2 is "NO" , how to parse the JSON data at client side ?
try this
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
//dataType : "json",
url: myAjax.ajaxurl,
data: { action : "ajx_add_donations",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " ,response);
//console.log("success " + JSON.parse(response));
//jQuery("#d_amount").val(donor_data[0]);
//jQuery("#p_button").text("brrr");
},
error: function(response) {
console.log("error" + response);
},
});
});
});
function ajx_add_donations () {
global $wpdb;
$adv_don=json_decode(stripslashes($_REQUEST['donors']));
//$adv_don = json_decode($_POST['donors']);
//echo json_encode("phani");
//echo json_encode($result);
$dtype = 'OFFLINE';
$d_status = 'PENDING';
$ddate = current_time( 'mysql' );
$donation_e = array (
'UID' => $adv_don->id[0],
'STATUS' => $d_status,
'PMODE' => $dtype,
'AMNT' => $adv_don->amnt,
'DDATE' => $ddate
);
$d_id = update_donation_entry($donation_e);
echo json_encode("<h3> Thank you for Contribution <strong>$amount</strong></h3>");
wp_die();
}
add_action( 'wp_ajax_ajx_add_donations','ajx_add_donations' );
add_action( 'wp_ajax_nopriv_ajx_add_donations', 'ajx_add_donations');
I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.
I try to load database data in my Select2 input. (Im working on CI)
Here's my code from the controller : transforms array in echo json
class Ajax extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('client');
}
public function returnClientsAjax(){
echo json_encode($this->client->getClients());
}
}
Model : returning an array of results
function getClients(){
return $this->db->query("SELECT idclient AS id, CONCAT(societe,' [', nom,']') as text FROM du_client WHERE (societe != '' AND nom != '') AND evo2012 >=2 AND type_client != 'Particulier' AND statut_client = 'Demandeur' AND idclient = 6141;")->result_array();
}
My Select2 :
$("#sel_clients").select2({
placeholder: "Search for an Item",
ajax: {
dataType: "json",
url: "http://commexpert.dev.local/ajax/returnclientsajax",
results: function (data) {
return {results: data};
}
}
});
The input still empty so, don't know what to do.
Thnaks :D
I think something is missing on your data results method. Here is my code from working ajax select2 component:
results: function (data) {
var results = [];
var id1 = data.id;
var name = data.text;
$.each(data.data, function(index, item){
results.push({
id: item[id1],
text: item[name].trim()+' : '+ item[id1]
});
});
return {results: results};
}
also, I'm having somewhat diff data call also:
data: function (term) {
try {
mirko = $(this).closest('[rendered]').find( "input[fparamname$=" + $(this).attr('flookupfiltref') + "]" ).val();
if (mirko.indexOf(' : ') >=0 ) { // pocetna vrijednost
mirko = mirko.split(' : ')[1].trim();
}
} catch(e){
mirko = '';
}
return {
sp_name: $(this).attr('objectname'),
fl_name: $(this).attr('fparamname'),
node_id: $(this).attr('node_id'),
bound: mirko,
q: term,
};
},
I'm having somekind of manipulation before sending or returning q to server,, but I hope that can help you for your service :)
hth, k
I am using the select2 for on of my search boxes. I'm getting the results from my URL but I'm not able to select an option from it. I want to use the 'product.productName' as the text to be shown after selection. Is there anything that I have missed out or any mistake that I have made. I have included select2.css and select2.min.js,jquery.js
function dataFormatResult(product) {
var markup = "<table class='product-result'><tr>";
markup += "<td class='product-info'><div class='product-title'>" + product.productName + "</div>";
if (product.manufacturer !== undefined) {
markup += "<div class='product-synopsis'>" + product.manufacturer + "</div>";
}
else if (product.productOptions !== undefined) {
markup += "<div class='product-synopsis'>" + product.productOptions + "</div>";
}
markup += "</td></tr></table>";
return markup;
}
function dataFormatSelection(product) {
return product.productName;
}
$(document).ready(function() {
$("#e7").select2({
placeholder: "Search for a product",
minimumInputLength: 2,
ajax: {
url: myURL,
dataType: 'json',
data: function(term,page) {
return {
productname: term
};
},
results: function(data,page) {
return {results: data.result_object};
}
},
formatResult: dataFormatResult,
formatSelection: dataFormatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) {
return m;
}
});
});
This is my resut_object
"result_object":[{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"},{"productName":"samsung salaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Graphite;32GB"},{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;16GB"}]
You are missing id attribute for result data. if it has not, it makes option "unselectable".
Example:
$('#e7').select2({
id: function(e) { return e.productName; },
});
Since I was using AJAX, what worked for me was returning something as the ID on processResults:
$(field).select2({
ajax: {
// [..] ajax params here
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
// proccessResults NEEDS the attribute id here
id: item.code,
// [...] other attributes here
foo: item.bar,
}
})
}
},
},
});
The id param can be a string related to the object property name, and must be in the root of the object. Text inside data object.
var fruits = [{code: 222, fruit: 'grape', color:'purple', price: 2.2},
{code: 234,fruit: 'banana', color:'yellow', price: 1.9} ];
$(yourfield).select2(
{
id: 'code',
data: { results: fruits, text: 'fruit' }
}
);
I have faced the same issue,other solution for this issue is:-
In your response object(In above response Product details object) must have an "id" as key and value for that.
Example:- Your above given response object must be like this
{"id":"1","productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"}
SO you don't need this
id: function(object){return object.key;}