populate chosen multiple get plugin with ajax request - php

I am having trouble with populating chosen plugin multiple get with data from an ajax call. I tired following the below posts,
Jquery Chosen plugin - dynamically populate list by Ajax
Multiple Select - Chosen jQuery
Jquery chosen ajax call populate multiselelect not working
But did not help. The data just doesn't get filled :( my ajax request is as follows,
<script type="text/javascript" lang="javascript">
function doGetTag() {
alert('here');
$.ajax({
url: 'index.php/rest/resource/qtag',
//data: data,
success: function(data) {
var jsonObj = JSON.parse(data);
var tags = "";
var curVal = document.getElementById('tags').innerHTML;
for(var i = 0; i < jsonObj.length; i++) {
var tagObj = jsonObj[i];
//document.write("<option>" + tagObj.tagName + "</option>");
var tagHtml = "<option>" + tagObj.tagName + "</option></br>";
tags = tags + tagHtml ;
}
tagTotal = curVal + tags;
document.getElementById('tags').innerHTML = tagTotal;
alert( document.getElementById('tags').innerHTML);
},
type: "get"
});
}
</script>
which returns a json string. the data gets properly displayed over here if I alert it out on a message box. But the issue is how to populate the multiple get plugin? following is my html,
<select data-placeholder="Tag your question here" style="width:350px;height:50px;" multiple class="chosen-select" id="tags">
<option value="" ></option>
</select>
I am very new to this plugin and would very much appreciate your help :)
FYI
I did it using direct php as follows,
<select data-placeholder="Tag your question here" style="width:350px;height:50px;" multiple class="chosen-select" id="tags">
<option value="" ></option>
<?php
$con=mysqli_connect("localhost","user","pass","db");
$result = mysqli_query($con,"SELECT * FROM tags");
while($row = mysqli_fetch_array($result))
{
echo"<option>".$row['tagName']."</option>";
echo"</br>";
}
?>
</select>
and it properly displays the data, but the project requirement states it is a MUST to use AJAX request to populate data. Thank you very much :) your expert advice is very much appreciated :)

Fist of all check your url: 'index.php/rest/resource/qtag',
This may work :
success: function(data) {
$("#tags").html(data).trigger('liszt:updated');
}
where data = (echo from sourse)
<option value=0> </option>
<option value=1> Option 1 </option>
<option value=2> Option 2 </option>

Related

How to post select tag value into PHP using Ajax post?

I have these HTML select code.
<div>
<select id="pickType" class="form-control select2 " name="pickType">
<option value="" selected="selected">Select Type</option>
<option value="TBL_LEMON">Lemon</option>
<option value="TBL_APPLE">Apple</option>
<option value="TBL_GRAPE">Grape</option>
</select>
</div>
And I use Ajax serialize to post the data into php file (populate.php). The jQuery code as below.
<script>
$(document).ready(function(){
$('#pickType').change(function(){
var selected = $(this).val();
var data_type = $("#pickType").serialize()+"&type="+"getTable";
$.post("populate.php",data_type).done(function( data ){
console.log(data);
console.log(selected);
});
});
});
</script>
The problem is the value cannot be sent into populate.php, therefore PHP file cannot pass the json data back.
I tried to console.log and alert the value and it works fine.
My goal is to pass the value from select into my SQL Query. Because my SQL Query will have to query 3 different table. The code for my PHP as below.
if((isset($_POST['type'])) && ($_POST['type']=='getTable'))
{
$sql = DB::getInstance()->FetchArray("select * from '".$_POST['pickType']."' ");
if(count($sql) > 0)
{
$array = array();
foreach($sql as $row)
{
$array2 = array();
$array2[]= $row['ID'];
$array2[]= $row['SUBJECT_ITEMS'];
$array[] = $array2;
}
echo json_encode($array);
}
}
What am I missing here ?
Appreciate if someone can help me. Thanks.
Try to change this code
var data_type = $("#pickType").serialize()+"&type="+"getTable";
to follow code
var data_type = {
pickType: selected,
type: 'getTable'
}
I prefer to use ajax call. First of all get the value of selected option:
var selectedOpt = $('#pickType').val();
and then call your populate.php using ajax:
$.ajax({
url: 'populate.php',
type: 'POST',
data: {
'type': selectedOpt,
'pickType': 'getTable'
},
success: function(result){
}
});
also I think you have wrong post keys in your php file:
if((isset($_POST['type'])) && ($_POST['type']=='getTable'))
maybe should be
if((isset($_POST['pickType'])) && ($_POST['type']=='getTable'))
Try:
var selected = $(this).find(':selected').val();
var data_type = "pickType="+selected+"&type=getTable";
also you can check your post data in the params tab under the network section of the browsers developer console to make sure the data is being posted
I turns out that I add a single quote on name of table in populate.php
It should be ".$_POST['pickType']." , so the query will be "select * from TBL_LEMON".
My problem above because I added single quote '".$_POST['pickType']."' , the query failed because "select * from 'TBL_LEMON' "
My problem solved. Thanks.

Populating Select box using PHP and Ajax returning empty

I am having an issue with an ajax function populating a list box with null options. I am fairly new to this and must be overlooking something. The DB connection is done through Sugarcrm and works, as I am using it for an auto complete function as well. I just can't seem to get the options to populate anything besides empty.
index.php
<script>
$(document).ready(function(){
$.ajax({
url: 'search.php',
type: 'json',
success:function(response){
var len = response.length;
$("#sel1").empty();
for( var i = 0; i<len; i++){
$("#sel1").append("<option value='"+name+"'></option>");
}
}
});
});
</script>
<select id="sel1" multiple size="6">
<option value="0">- Select -</option>
</select>
search.php
<?php
global $db;
$rolelistQry = "SELECT distinct name from acl_roles";
$rolelistData = $db->query($rolelistQry);
$name_array = array();
while( $row = $rolelistData->fetch_assoc()){
$name = $row['name'];
$name_array[] = array("name" => $name);
}
echo json_encode($name_array);
?>
$("#sel1").append("<option value='"+name+"'></option>");
name variable doesn't exists. Try changing it to response.name
$("#sel1").append("<option value='"+response.name+"'>"+response.name+"</option>");
I'm guessing you're getting a bunch of blank options?
<option value="0">- Select -</option>
Is the right syntax: the option's value (when selected) will be 0, and it'll display Select.
So when you append new items in the ajax callback you'll want to have the options show something:
<option value='name'>NAME</option>
You're trying to access response as an array, right?
You'll need to do something like
$("#sel1").append("<option value='"+response[i].name+"'>"+response[i].name+"</option>");
to get the items out of the response array. (modified from majorlogic's answer)
In fact your are not looping through the array name,
This should work :
<script>
$(document).ready(function(){
$.ajax({
url: 'search.php',
type: 'json',
success:function(response){
var result = $.parseJSON(response);
var len = result.length;
$("#sel1").empty();
for( var i = 0; i<len; i++){
$("#sel1").append("<option value='"+ result[i]['name'] +"'></option>");
}
}
});
});
</script>
<select id="sel1" multiple size="6">
<option value="0">- Select -</option>
</select>

How do I dynamically query the DB based on HTML select option? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a HTML drop-down list populated by querying a database. When the user chooses an option, the application should show information related to that option, with no submit!! That is, if I choose option A, automatically the application should query the DB for that info and display it.
The part of querying and displaying the data is not a problem, as it's similar to what I did for populating the list, but what I don't know is how to do this dynamically. I know how to do it using submit, but I'm not allowed to do this way for a better user experience.
As an example, suppose a hotel booking application. There are two elements, the drop-down list with dates, and a message showing the number of bookings there are for that determined date. So, upon visiting the application it may show:
Date: 2015/11/26 Bookings: 7
But now if the user changes the date, it should display the number of bookings for that new date:
Date: 2015/11/27 Booking: 18
You're looking for AJAX calls.
An example of doing so with jQuery:
$("#id-of-your-select").change(function(){
var val = $(this).val();
$.post("php-page.php", { selectValue : val }, function(response){
console.log(response); //handle the data pinged back by the PHP page in the variable 'response'
});
});
In the PHP file php-page.php, you receive the data in $_POST["selectValue"], and whatever you output (via echo, print, print_r, var_dump, exit() etc) will be received by the JavaScript/jQuery function in the variable "response".
References:
jQuery Ajax
jQuery Post
Here is example of my project where i need to choose option from drop down list of Countries and based on that to query related data from database.
$('#ddl_country').change(function(){
var country = $('#ddl_country :selected').val();
$.ajax({
url: "/admin/findDivisions",
type: 'post',
dataType: 'json',
data: {country:country},
cache: false,
success: function(data){
$('#ddl_division').html('<option value="0"> - Select - </option>');
for (var i = data.length - 1; i >= 0; i--) {
$('#ddl_division').append('<option value="' + data[i]['id'] + '">' + data[i]['name'] + '</option>')
}
}
});
});
I've used ajax because i wanted to fill another drop down list with options generated from database without any reloads.
You looking for this:
HTML + jQuery
<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
$('#values_to_choose').change(function(){
document.getElementById("values_to_choose").value=this.options[this.selectedIndex].text;
});
$("#values_to_choose").change(function(){
var value_val = $(this).val();
$('#values_to_be_filled').empty();
$.post('get_values.php', {value_val:value_val}, function(result){
if (result != 1){
theResult = JSON.parse(result);
var theLength = theResult.length;
var x = document.getElementById("values_to_be_filled");
var option = document.createElement("option");
option.text = "Please select ...";
option.value ="";
x.add(option);
for(i=0;i<theLength;i++){
var new_data = theResult[i].split(',');
var result_val = theResult[i];
var x =document.getElementById("values_to_be_filled");
var option = document.createElement("option");
option.value = result_val;
option.text = result_val;
x.add(option);
}
}else if(result == 1){
alert("No value for selected option");
}
});
})
});
</script>
</head>
<body>
<form method="post" action="" name="user" id="user">
<input id="v1" type="hidden" name="v1"/>
<<select name="values_to_choose" id="values_to_choose">
<option value="" selected="selected">Please select ...</option>
<option value="1" selected="selected">Value 1</option>
<option value="2" selected="selected">Value 2</option>
<<select name="values_to_be_filled" id="values_to_be_filled">
<option value="">Please select ...</option>
</select>
</form>
</body>
</html>
PhP Script for data...
<?php
require_once('DB Connection');
if($_POST['value_val'] != ""){
$get_value = $_POST['value_val'];
}
$get_results = mysql_query("select values_for_chosen_option from table where column_name ='$get_value'") or die(mysql_error());
$get_rows = mysql_num_rows($get_results);
if ($get_rows > 0){
$check=0;
$items=array();
while ($row=mysql_fetch_assoc($get_results)){
$data = $row['values_for_chosen_option'];
array_push($items,$data);
}
}else{
$check=1;
}
if ($check==0){
echo json_encode($items);
}
else{
echo "1";
}
?>

How to write PHP code inside jquery for retrieving values from mysql database?

I am trying to get the values for the next drop-down from a database, which will be dependent on two previous drop-downs. The values for first two drop-downs are listed in the file itself. I want the second drop-down to be enable after selecting values from first, and similarly for third after second. Kindly help.
HTML code below:
<form>
<select id="branch" name="branch" class="form-control" onchange="showUser(this.value)">
<option value="">Select</option>
<option value="1">Civil</option>
<option value="2">Computer</option>
<option value="3">Mechanical</option>
<option value="4">Electronics and Telecommunications</option>
<option value="5">Electrical and Electronics</option>
<option value="6">Information Technology</option>
</select>
<select id="semester" name="semester" class="form-control" disabled>
<option value="1">I</option>
<option value="2">II</option>
<option value="3">III</option>
<option value="4">IV</option>
<option value="5">V</option>
<option value="6">VI</option>
<option value="7">VII</option>
<option value="8">VII</option>
</select>
</form>
jquery is:
<script>
$(document).ready(function(){
document.cookie = "s =hello" ;
console.log('hello');
$("#semester").attr("disabled", true);
$("#branch").change(function(){
$("#semester").attr("disabled", false);
$b = $('#branch').val();
$("#semester").change(function(){
$s = $('#semester').val();
$("#sub_code").attr("disabled", false);
console.log($s);
if($s!=1||$s!=2)
$s = $b+$s;
<?php
$s= $_COOKIE['s'];
$sql = "SELECT * FROM subjects WHERE sem_code=`$s`";
?>
});
});
});
</script>
I did not run the query since it is not assigned properly yet.
You can't include php code in javascript , the first is executed on the server side, the second is executed on the client side which means that you can't re-execute only if you resend a request to the server, obviously this is usually done by submitting forms, BUT sometimes -like in your case- we don't want to reload the whole page for each request ! and for this purpose we use AJAX
ajax sends post/get request to a specified php page which does the desired server-side tasks (updating data in the database, selecting some results from database, dealing with sessions maybe, etc...)
try something like this:
var pathurl='/path/to/your/php/file';
var params={}; //the parameters you want to send
params['semester']=$s;
var requestData= $.ajax({
type: 'POST',
url: pathurl,
cache: 'false',
data: params,
dataType: "json",
beforeSend: function () {
//here you can begin an animation or anything...
},
complete: function () {
//here you can stop animations ...
},
success: function (response) {
console.log(response); //check your console to verify the response
//loop other elements inside response
$.each(response, function (index, resultArray) {
//do something : in your case append to dropdown a new option
});
}
});
requestData.error(function () {
alert("error");
});
you should create a php file with the path specified in the above code, and there you can extract what you need from the database table, store values in an array and finally use:
echo json_encode($resultArray);
hope this was helpful

Fill out select box depending on other two select boxes - jquery

I had three drop down menus. Depending on items selected on two lists, the third list should be filled out (ajax post).
This is the html code:
Source Language:
<select name='source_lang' id='source_lang' $dis size='6'>
<option value='en'>EN</option>
<option value='sq'>SQ</option>
.....
</select>
Target Language:
<select name='targ_lang' id='targ_lang' $dis size='6'>
<option value='en'>EN</option>
<option value='sq'>SQ</option>
.....
</select>
Supplier:
<select name='supplier_id' id='supplier_id'>
<option value='1'>Supplier 1</option>
<option value='2'>Supplier 2</option>
</select>
On target and source language change, the supplier select list should be filled out.
Anybody can help me with the jquery? I need to ajax post the source, target language values and as response fill out the supplier select list with the data.
Is this something you're looking for?
$('#targ_lang, #source_lang').change(function(){
$.ajax({
url : '',
method : 'post',
type : 'json',
data : {
select1 : $('#targ_lang').val(),
select2 : $('#source_lang').val()
},
complete : function(result){
var options = $.parseJSON(result);
$('#supplier_id').html("");
for(i=0; i < options.length; i++) {
$('#supplier_id').append(
'<option value="'+ options[i] + '">' + 'Supplier' + options[i] + '</option>'
);
}
});
});
});
On the PHP side you need to send your result like this:
$array = new Array(1,2,3,4); // supplier IDs
echo json_encode($array);
Example using jQuery's .post() method:
$('#targ_lang, #source_lang').change(function(){
$.post("test.php", { source: $('#source_lang').val(), target: $('#targ_lang').val()},
function(data) {
//Change the data of the 3rd select
});
});

Categories