Laravel 5 with Select2, Loading data with ajax - php

first of all, here is my code so far.
My route:
Route::get('cities/citybylang/{lang_id}', [
'uses' => 'CitiesController#cityByLanguage',
'as' => 'dashboard.cityByLanguage'
]);
My controller:
public function cityByLanguage($lang_id){
$cities = City::select('name','id')->where('lang_id',$lang_id)->get();
return $cities;
}
My view select
<select class="js-data-example-ajax">
<option value="3620194" selected="selected">select2/select2</option>
</select>
My Select2 code
$(".js-data-example-ajax").select2({
ajax: {
url: "/dashboard/cities/citybylang/1",
dataType: 'json',
delay: 250,
data: function (params) {
console.log(params.term);
return {
q: params.term, // search term
page: params.page,
name: params.name
};
},
beforeSend: function(jqXHR, settings) {
console.log(settings.url);
},
processResults: function (data, page) {
console.log(data);
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
});
function formatRepo (repo) {
if (repo.loading) return repo.text;
var markup = '<div class="clearfix">' +
'<div clas="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-6">' + repo.name + '</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + repo.name + '</div>' +
'<div class="col-sm-2"><i class="fa fa-star"></i> ' + repo.name + '</div>' +
'</div>';
if (repo.name) {
markup += '<div>' + repo.name + '</div>';
}
markup += '</div></div>';
return markup;
}
function formatRepoSelection (repo) {
return repo.name || repo.text;
}
Okey, the basic problem is, i can't pass the right parameter to the controller.
This is how this work now: I start typing to the select field and it give a list with the cities which has the lang_id = 1.
So the ajax call send this to the controller:
somthing.com/dashboard/cities/citybylang/1?q=[value, what i type to the select field]
I have pretty url, so i want something like this:
somthing.com/dashboard/cities/citybylang/[value, what i type to the select field]
So the question is, how can i pass parameter to the controller in the right way?

This question is old but I was looking for same thing that's how I manged it.
url: function(params) {
return '/some/url/' + params.term;
},
Here is reference link
https://select2.github.io/options.html

Related

CodeIgniter, Ajax... How to use insert_id()

Excuse my English, I hope you can understand my question...
In my program, when you submit a new record to the database (MySQL) using a modal+form, it is drawn in a data table without refreshing or recharging the actual page, it's appended dynamically.
What I need to do is, in every new record, draw/append the data AND 2 buttons (1 for deleting that record and 1 for updating it) with the ID of the new data.
I read I can use insert_id() to get the last inserted id, but I don't know how to use it and how to work with the result in my Ajax call.
Any hint, please? I'm pretty new to programming.
Thanks for your time.
EDIT
I need the data I introduced in the modal/form (for that I was using .serialize()) AND the ID generated in the DB...
I don't know how to use the model/controller returned ID info.
I have this in my controller:
public function nuevo_elemento_diccionario()
{
$this->load->helper('form');
$this->load->library('form_validation');
// Validation rules that I deleted for this post
if ($this->form_validation->run() === FALSE)
{
$this->load->view("header");
$this->load->view("section-aside");
$this->load->view("vista_nuevo_elemento_diccionario", $datos);
$this->load->view("footer");
}
else
{
$last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
echo json_encode(array('last_id' => $last_id));
redirect('/diccionarios/lista_diccionarios');
}
}
Model:
public function nuevo_elemento_diccionario()
{
$datos = array(
'ELDI_Key' => $this->input->post('eldi_key'),
'ELDI_Display' => $this->input->post('eldi_display'),
'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
);
$this->db->insert('elementos_diccionario', $datos);
/* $ultima_id = $this->db->insert_id();*/
$last_id = $this->db->insert_id();
return $last_id;
}
Javascript/Ajax (where you see var key = $('input[name="eldi_key"]').val(); and using it, is where I need to use the ID to use the new ID for delete and update clicking the generated buttons):
function nuevo_elemento()
{
var id =$('input[name="eldi_id"]').val();
var display = $('input[name="eldi_display"]').val();
var key = $('input[name="eldi_key"]').val();
key = key.split(" ").join("_").toLowerCase();
swal({
title: 'Añadir elemento',
text: "¿Quieres añadir este elemento?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Sí',
cancelButtonText: 'No'
}).then((result) => {
if (result.value) {
$.ajax({
type: "POST",
url: $("#base_url").attr("valor") +
"diccionarios/nuevo_elemento_diccionario",
data: $("#formNuevoElementoDiccionario").serialize(),
success: function(data) {
console.log(data);
$('#Modal_Add').modal('hide');
$("#formNuevoElementoDiccionario").trigger("reset");
var html =
'<tr>'+
'<td>' + key + '</td>' +
'<td>'+ display +'</td>'+
'<td>'+
'<span class="btn btn-default editar_elemento"
id=' + key + ' value="' + key + '">' +
'<a href="'+$("#base_url").attr("valor") +
"diccionarios/elemento_diccionario/"+key+'" title="Editar">' +
'<i class="material-icons">edit</i>' +
'</a>' +
'</span>' +
'</td>' +
'<td>' +
'<span class="btn btn-default borrar_elemento"
id="'+ key +'" value="'+ key +'">'+
'<i class="material-
icons">delete_outline</i>'+
'</span>'+
'</td>'+
'</tr>'
$('#tabla-diccionarios').append(html);
swal("Añadido", "Elemento añadido correctamente",
"success");
$(".borrar_elemento").off();
evento_borrar_elemento();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error: " + textStatus);
}
});
}
})
}
You can use insert_id() only after inserting data to DB. If you need user last id in controller or js try this:
public function nuevo_elemento_diccionario()
{
$datos = array(
'ELDI_Key' => $this->input->post('eldi_key'),
'ELDI_Display' => $this->input->post('eldi_display'),
'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
);
$this->db->insert('elementos_diccionario', $datos);
$ultima_id = $this->db->insert_id();
return $ultima_id;
}
Then you can use json_encode() for return data to js in Controller:
public function nuevo_elemento_diccionario()
{
$this->load->helper('form');
$this->load->library('form_validation');
// Validation rules that I deleted for this post
if ($this->form_validation->run() === FALSE)
{
$this->load->view("header");
$this->load->view("section-aside");
$this->load->view("vista_nuevo_elemento_diccionario", $datos);
$this->load->view("footer");
}
else
{
$last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
echo json_encode(array('last_id' => $last_id));
// i`m not sure that you need to use redirect
redirect('/diccionarios/lista_diccionarios');
}
}
In you js edit success function:
success: function(data) {
var result = JSON.parse(data);
var insert_id = result.insert_id;

jquery select2: error in getting data from php-mysql

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.

Select2 load data from database - CodeIgniter

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

select2 on success retrieve newly created tag id

In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_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: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term) {
var text = term + (lastResults.some(function(r) {
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#project_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({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.

Unable to select a result from the select2 search results

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;}

Categories