I'm using Select2 for a project. The second select box gets filled depending on the selected item in the first box, as shown in the link below. However, I can't click the first item in the second select box for some reason. The only way for me to select the first item if I want to, is to first select a different user, and then back to the first. How can I solve this?
Video:
My code:
This is the first select box, getting filled by regular PHP (Laravel). Everything works fine here.
<div class="form-group">
<label for="select"> Partner: </label>
<select id="select" name="select" class="searchselect searchselectstyle">
#foreach($partners as $i => $partner)
<option {{$i == 0 ? 'selected' : ''}} value="{{$partner->id}}">{{$partner->name}}</option>
#endforeach
</select>
</div>
Here Is the second select box, with the error.
<div class="form-group" >
<label for="select2"> Hoofdgebruiker: </label>
<select id="select2" style="min-width: 200px;" name="select2" class="searchselect searchselectstyle">
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url = '/json/getusers';
var $post = {};
$post.id = $("select").val();
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: $post,
cache: false
}).done(function(data){
$('#select2')
.find('option')
.remove()
.end();
$.each(data, function(i, value) {
console.log(data);
$('#select2').append($('<option>').text(value.text).attr('value', value.id));
});
}
);
});
-
public function getusers(){
if(!isset($_POST['term'])){
$users = User::where('partner_id', $_POST['id'])->get();
}else{
$wildcard = '%'.$_POST['term'].'%';
$users = User::where('partner_id', $_POST['id'])->where('email', 'LIKE', $wildcard)->get();
}
$array = array();
foreach($users as $i => $user){
$array[$i] = array("id" => $user->id, "text" => $user->email);
}
return response()->json($array);
}
Check the case sensitivity of the key "id" in json data. Probably you return "ID" insteat of "id".
{"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]}
not like that
{"results":[{"ID":"3","text":"Exampe 3"},{"ID":"4","text":"Example 4"},{"ID":"16","text":"Example 16"}]}
I found a solution, which is the following:
<script type="text/javascript">
$(document).ready(function() {
$(".searchselect").select2();
search();
$("#select").change(function(){
search();
});
});
function search(){
var $post = {};
$post.id = $("#select").val();
$("#select2").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
var query = {
term: params.term,
id: $post.id
};
return query;
},
url: '/json/getusers',
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
}
</script>
Now I'm using the regular AJAX functionality built in Select2, it is all working as expected now!
Related
Hello i am displaying state name and state id after ajax success function but i am not display because i don,t know how can i show ? After that i am also show that list of state below the state name. need help to solve this query
public function edit_address(Request $request)
{
$state = DB::table('states')->pluck('state_name','state_id');
$each_edit_address=DB::table('address')
->join('states','states.state_id','=','address.state_id')
->select('address.*','states.state_name')
->where('address_id',$request->address_id)
->get();
foreach ($each_edit_address as $edit_address)
{
return response()->json(['address_id' => $edit_address->address_id,'address' =>$edit_address->address,'pincode'=>$edit_address->pincode,'locality'=>$edit_address->locality,'city'=>$edit_address->city,'landmark'=>$edit_address->landmark,'option_mobile_number'=>$edit_address->option_mobile_number,'user_name'=>$edit_address->user_name,'user_mobile'=>$edit_address->user_mobile]);
}
}
//javascript
$(document).on('click', '.show_address', function(e){
e.preventDefault();
$('.edit_address_label').show();
$('#edit_address').show();
$("#address_show:checked").closest('.col-sm-8').find('.current_user_address').hide();
$("#address_show:not(:checked)").closest('.col-sm-8').find('.edit_address_label').hide();
$("#address_show:checked").closest('.display_address').find('.deliver_show_address').removeClass('deliver_address');
$("#address_show:checked").closest('.display_address').find('.deliver_show_address').addClass('delivery_hide_address');
$('#save_address').hide();
var address_id=$(this).attr('data-val');
$.ajax({
type : 'get',
url : '/edit-address',
data:{ 'address_id':address_id
},
success:function(result)
{
$('#edit_address').attr("data-val",result.address_id);
$('.show_address').parents().find('#name').val(result.user_name);
$('.show_address').parents().find('#mobile_number').val(result.user_mobile);
$('.show_address').parents().find('#address').val(result.address);
$('.show_address').parents().find('#pincode').val(result.pincode);
$('.show_address').parents().find('#locality').val(result.locality);
$('.show_address').parents().find('#city').val(result.city);
$('.show_address').parents().find('#landmark').val(result.landmark);
$('.show_address').parents().find('#option_number').val(result.option_mobile_number);
}
});
});
<div class="col-sm-6">
<div class="form-group">
<label>State<span>*</span>
</label>
<select name="new_state" class="form-control" id="state">
<option value="">Select State</option>
#foreach($state as $id => $state_name )
<option value="{{ $id }}">{{ $state_name }}</option>
#endforeach
</select>
</div>
</div>
It's because you are doing it wrong, I don't really know what you have in mind with the data, but you are starting a foreach loop inside your controller function, but you only return the first row of the $edit_address and the rest are skipped. So you have to first, return the data as a whole to JavaScript and then loop through it in your Ajax complete() function like below:
controller:
public function edit_address(Request $request)
{
$state = DB::table('states')->pluck('state_name','state_id');
$each_edit_address=DB::table('address')
->join('states','states.state_id','=','address.state_id')
->select('address.*','states.state_name')
->where('address_id',$request->address_id)
->get();
return response()->json(['addresses' => $each_edit_address, 'states' => $state]);
}
and then, in your JS code, based on the data that you returned from your controller, you can loop through the addresses like below:
var address_id=$(this).attr('data-val');
$.ajax({
type : 'get',
url : '/edit-address',
data:{ 'address_id':address_id
},
success:function(result)
{
$(result.addresses).each(function(address){
console.log(address.user_name);
// Write your own code here to deal with each address.
});
}
});
Note: You can also get access to the states data in your ajax complete() function like below:
var address_id=$(this).attr('data-val');
$.ajax({
type : 'get',
url : '/edit-address',
data:{ 'address_id':address_id},
success:function(result)
{
console.log(result.states);
}
});
Please, I'm a beginner with php..
I would like to use an array encoded in json like this :
http://stegonia.fr/autocomplete/index2.php (you can see result of a var_dump).
I want to be able to see in an autocomplete form the value and label name and store the id number in my database.
I want to use this autocomplete solution :
http://stegonia.fr/autocomplete/index3.php
The javascript of this solution (index3) is :
<script>
$(document).ready(function () {
$('#speciesname').typeahead({
source: function (query, result) {
$.ajax({
url: "server3.php",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
});
php code of server2 is this one :
$term = trim(strip_tags($_GET['term']));
$a_json = array();
$a_json_row = array();
if ($data = $mysqli->query("SELECT * FROM `taxrefv11_mini` WHERE `GROUP2_INPN` = 'oiseaux' and `NOM_VERN` LIKE '%$term%' ORDER BY `NOM_VERN`")) {
while($row = mysqli_fetch_array($data)) {
$nomlat = htmlentities(stripslashes($row['NOM_VALIDE']));
$nomvern = htmlentities(stripslashes($row['NOM_VERN']));
$code = htmlentities(stripslashes($row['CD_REF']));
$a_json_row["id"] = $code;
$a_json_row["value"] = $nomvern.' '.$nomlat;
$a_json_row["label"] = $nomlat.' '.$nomvern;
array_push($a_json, $a_json_row);
}
}
// jQuery wants JSON data
echo json_encode($a_json);
flush();
$mysqli->close();
Please, I don't know well javascript my question is :
If I use json file sended by server2.php, what is the right syntax of the javascript of index3 to fetch values of "id", "value" and "label" ?
Thanks
Olivier
Someone helped me to solve.
Below the solution. But there is a problem : menu items disappear when hovering over a menu in the autocomplete form. It's discussed here :
Why menu items disappear when hovering over a menu in autocomplete form
This is the entire php file. This file call a server2.php file who send json
(http://stegonia.fr/autocomplete/server2.php)
here the entire index.12.php (http://stegonia.fr/autocomplete/index12.php)
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Autocomplete with Dynamic Data Load using PHP Ajax</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- Bootstrap core CSS -->
<link href="./css/bootstrap.min.css" rel="stylesheet">
<script src="jquery-2.1.4.min.js"></script>
<script src="//twitter.github.io/typeahead.js/releases/latest/typeahead.jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.js"></script>
</head>
<body>
<div class="container-fluid">
Search a species name and press enter (linotte for example) :
<form method="post" action="index12.php" id="form">
<input type="text" name="speciesname" id="speciesname" autocomplete="off" class="typeahead"/>
<input type="hidden" name="speciesid" id="speciesid">
</form>
<script>
function html_decode(value) {
return $('<textarea />').html(value).text()
}
$(document).ready(function () {
var input = document.getElementById('speciesname');
input.focus();
$('#speciesname').typeahead({
source: function (query, store) {
if (!input.value || input.value.length < 3) {
return [];
}
$.ajax({
url: 'server2.php',
data: 'term=' + query,
dataType: 'json',
type: 'post',
success: function (data) {
var species = [];
$.each(data, function (i, item) {
species.push({ id: item.id, name: html_decode(item.value) });
});
return store(species);
}
}
)
},
matcher: function (item) {
return item.name ? item.name.toLowerCase()
.indexOf(this.query.toLowerCase()) !== -1 : false;
},
afterSelect: function (item) {
if (item.id) {
$(input).val(item.name);
$('#speciesid').val(item.id);
$('#form').submit();
}
}
})
});
</script>
<br>
<?php if (isset($_POST['speciesid'])): ?>
<p>The code number (id number) of the previous selected species is : <?php echo $_POST['speciesid'] ?></p>
<?php endif; ?>
</body>
</html>
Controller:
public function index()
{
.
.
.
$search_result = $this->m_results->search_people(array('country'=>$country,'state'=>$state,'city'=>$city,'sort'=>$this->sort,'id'=>$data['id']),$keyword,$s_id);
$this->load->view('include/header',$data);
if($search_result != FALSE)
{
$data['results']['freelancers'] = $search_result;
// print_r($data['results']['freelancers']); exit();
$data['sort_value'] = $this->sort;
$this->load->view('search',$data);
}else{
$data['string'] = $this->input->post('keyword');
$this->load->view('search_empty',$data);
}
$this->load->view('include/footer',$data);
}
Ajax function:
$("body").on("change", "#sort", function () {
$.ajax({
method: "get"
, url: base_url + "search"
// , cache: false
, data: {
skills: $("#inputtags").val()
, sort: $("#sort").val()
, city: $("#locationTextField").val()
}
, success: function (data) {
// console.log(data);
alert(data);
$("body").html(data);
}
})
});
View:
<div class="form-group sidemargin">
<select name="sort" id="sort" class="form-control select color2 bold">
<option value="rating" <?php echo set_select('sort','rating',( $sort_value == "rating" ? TRUE : FALSE )); ?>>Ratings</option>
<option value="review_count" <?php echo set_select('sort','review_count',( $sort_value == "review_count" ? TRUE : FALSE )); ?>>Reviews</option>
</select>
</div>
Above are the code I'm using for display the results after sorting by Ajax. But now the problem is after sorting the result, when I alert the success data its coming the entire html code but not the result from database.
I can't understand why its showing the html code instead of the sorted data from db. When I try to print_r() those result in controller, its showing correct value. When it come to Ajax success the values are different.
So folks help me to solve this. Answers will are appreciated. Thanks in advance.
I have dropdown list and i want to retrieve data from database when select value of downlist. This is working without having error. But this is working when i click on dropdown list, not in dropdown value. That mean work only for default value. please help me how to rectify this error. code as below.
HTML code for Dropdown list
<select name="lab_no" id="lab-no" class="form-control">
<option value="Lab 01" >Lab 01</option>
<option value="Lab 02">Lab 02</option>
</select>
Jquery Code is Here
<script type="text/javascript">
$(document).ready(function () {
$("option").click(function () {
var txt = $("#lab-no:selected").val();
if (txt = '') {
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {search: txt},
dataType: "text",
success: function (data) {
$('#table-row').html(data);
}
});
}
});
});
</script>
First you need to target your select $('#lab-no') and use change event instead of click. Then you can target the selected option.
$(document).ready(function () {
$("#lab-no").change(function () {
var txt = $("select option:selected").val()
console.log(txt)
if (txt = '') {
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {search: txt},
dataType: "text",
success: function (data) {
$('#table-row').html(data);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="lab_no" id="lab-no" class="form-control">
<option value="Lab 01" >Lab 01</option>
<option value="Lab 02">Lab 02</option>
</select>
Try with $("#lab-no").change. This Way your event will trigger after you have made a change in the dropdown.
You should not use :selected in $("#lab-no:selected").val() since its not needed. $("#lab-no").val() will return the selected value.
Working Demo
$(document).ready(function() {
$("#lab-no").change(function() {
var txt = $("#lab-no").val();
console.log(txt)
if (txt = '') {
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {
'search': txt
},
dataType: "text",
success: function(data) {
$('#table-row').html(data);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="lab_no" id="lab-no" class="form-control">
<option value="Lab 01">Lab 01</option>
<option value="Lab 02">Lab 02</option>
</select>
You can use in simple way like:
var drpSelectedValue=$("#lab-no").val();
May this help for you.
You should try like this
1.You need to change jquery event
<script type="text/javascript">
$(document).ready(function () {
$("#lab-no").change(function () {
var txt = $("#lab-no").val();
alert(txt) //place alert and check value. You will get values which you have selected
if (txt == '') { //make changes here
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {search: txt},
dataType: "text",
success: function (data) {
$('#table-row').html(data);
}
});
}
});
});
</script>
I have some results in div's ,each result has one checkbox associated with it, when a user click on single checkbox user, Current checked box's value is passed to another page using an ajax call and data is fetched and displayed in a hidden div box.
Now problem is, when user uncheck the checkbox it should remove the data associated with the checkbox.
My code is :
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
Ajax call
<script type="text/javascript">
$(document).ready(function()
{
$(".compare").change(function() {
if(this.checked) {
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').append(data);
}
});
}
});
});
Use something like this to empty the contents of the DIV
$('#compare_box').empty()
better way is to keep the reference map, something like this
$(document).ready(function() {
var boxes = {};
$(".compare").change(function() {
var check = $(this).val();
var data = $(this).closest('.box').clone();
if (this.checked) {
boxes[check] = data;
$('#comparebox').append(boxes[check]);
} else if (!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
});
});
EDIT - should be working (not tested)
var check = $(this).val();
if (this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType: 'JSON',
data: {
value: check
},
success: function(data) {
boxes[check] = $(data);
$('#compare_box').append(boxes[check]);
}
});
} else if(!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
DEMO