I wanted to show/hide element based on MySql Value
$(document).bind('DOMNodeInserted', '#composeHeaderTable0', function(event) {
if ($('#data_parent_type0').val() == 'Leads') {
$("#email_template0 option[value='151ddf5a-3fe8-84bd-50db-533545893c67']").hide();
$("#email_template0 option[value='15a6040b-bbad-1a89-d62b-537de2b73832']").show();
}
if ($('#data_parent_type0').val() == 'Contacts') {
$("#email_template0 option[value='1b560788-07b2-0798-6b09-5335520bd9df']").hide();
$("#email_template0 option[value='f15bf4b4-d174-f0d6-6f09-537c8d3e9693']").show();
}
return false;
});
Above script works, but I need to show hide based on Mysql call:
I have partial php corresponding file
<?php
mysql_connect('mysql', 'admin', '123');
mysql_select_db('mydb');
$Leads0emailAddress0 = mysql_real_escape_string($_POST['Leads0emailAddress0']);
$result = mysql_query('select id from email_templates where description = 'Customers' and deleted = 0;');
...............
?>
Use a hidden form element, set its value to the result obtained from mysql. Assign a specific ID to that form element. From jQuery, refer that form element using the ID. That should do the trick.
Your mysql script has error
$result = mysql_query('select id from email_templates where description = 'Customers' and deleted = 0;');
change it to
$result = mysql_query(
"SELECT id FROM
email_templates
WHERE
description = 'Customers'
AND deleted = 0"
);
To list the result
$options = '';
while($row = mysql_fetch_assoc($result)) {
$options .= '<option value="'.$row['id'].'">'.$row['id'].'</option>' . "\n";
}
//display the options list in html where you want
<select id="email_template0">
<?php echo $options; ?>
</select>
now from jQuery handle event on dropdown change
$(function() {
$("#email_template0").change(function() {
alert( $('option:selected', this).val() );
//do your hide and select here
});
});
Related
I have a table with this structure and trying to use a dropdown to select a language from the list and then display the contents of respective language_id .. I am using mysql and php 5.4
My code is as follows, got stuck with looping and not sure how to get it
$sql=mysql_query("SELECT lang_id, lang_desc FROM languages ");
if(mysql_num_rows($sql))
{
$select= '<select lang_desc="select">';
while($rows=mysql_fetch_array($sql))
{
$select.='<option value="'.$rows['lang_id'].'">'.$rows['lang_desc'].'</option>';
}
}
$select.='</select>';
echo $select ;
$result = mysql_query("SELECT * FROM contents LEFT JOIN languages ON contents.lang_id = languages.lang_id WHERE contents.page_name = 'index' AND contents.lang_id = '$select'");
while ($row = mysql_fetch_array($result))
{
}
Please help
I think this want minimum 2 PHP pages 1st for show data and 2nd for creat data in hear I didn't create DB connection please add it
in 1st I use jquery for getting data from 2nd PHP
show.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<select id="lang" onchange="setlang(this.value)">
<?PHP
$sql=mysql_query("SELECT lang_id, lang_desc FROM languages");
while($rows=mysql_fetch_array($sqL,MYSQL_ASSOC)){
echo '<option value="'.$rows['lang_id'].'">'.$rows['lang_desc'].'</option>'
}
?>
</select>
<div id='dis'></div>
<script type="text/javascript">
$( document ).ready(function() {
setlang($('#lang').val());
});
function setlang(val) {
$.ajax({
url: "data.php",
type: "POST",
data:{val:val},
success: function(result){
$("#dis").html(result);
}
});
}
</script>
data.php
<?php
$result = mysql_query("SELECT * FROM contents LEFT JOIN languages ON contents.lang_id = languages.lang_id WHERE contents.page_name = 'index' AND contents.lang_id = '".$_POST['val']."'");
$data="";
while ($row = mysql_fetch_array($result))
$data.="your row data for dis";
//
}
echo $data;
?>
I have been searching everywhere on this website and tried many solutions but none worked for me ! My problem is the following :
I have 2 tables :
TABLE INFO_STATUS (status_id, status_desc)
and
TABLE INFO_MARQUES (comp_id, comp_desc, comp_status(INT))
I am linking comp_status and status_id so that the row in INFO_MARQUES will get the current status.
What I would like to do? (EDITED FROM HERE)
2. get the current status value of info_marques located in comp_status automatically selected in the dropdown list when I open the update form
Example I want to update this company :
comp_id : 15
comp_desc : WEISS
comp_status : 1
Assuming that in table info_status :
status_id = 1
status_desc = FOLLOW-UP
When I open the update form I want to see this :
Check this
My Modal : (WORKING)
<select class="form-control" name="select_status">
<option value=''>Selectionner</option>
<?php
try {
$user = new USER();
$output = array();
$stmt = $user->runQuery("SELECT * FROM info_status");
$stmt->execute();
$result=$stmt->fetchAll();
foreach($result as $row) {
echo '<option value='.$row["status_id"].'>'.$row["status_desc"].'</option>';
}
}
catch(PDOException $e) {
printf('Erreur MySQL %d : %s', $e->getCode(), $e->errorInfo[2]);
exit;
}
?>
</select>
My Ajax
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
$.ajax({
url:"partials/test/fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#comp_name').val(data.comp_name);
$('#comp_parent').val(data.comp_parent);
$.each($('.select_status option'),function(a,b){
if($(this).val()== data.comp_status){
$(this).attr('selected',true)
}
});
$('.modal-title').text("Modifier un fichier client");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
$('#operation').val("Edit");
}
})
});
then my PHP page : (WORKING)
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connection->prepare(
"SELECT *
FROM info_marques AS m
LEFT JOIN info_status AS s
ON s.status_id = m.comp_status
WHERE m.id = '".$_POST["user_id"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["comp_name"] = $row["comp_name"];
$output["comp_parent"] = $row["comp_parent"];
$output["comp_status"] = $row["status_desc"];
}
echo json_encode($output);
}
What am I missing here?
Cheers
I am not sure that if you want to populate drop down or else select data based on your response, But if you want to select the data and you have options already in drop down, you can do this:
$.each($('#select_status option'),function(a,b){
if($(this).val() == data.comp_status){
$(this).attr('selected',true)
}
});
But if you want to populate, you will have to append it using .append(). Do let me know if issue is something different and I may give you a solution.
As you are saying you need all the status and then show the current status. what i would suggest is use .done() method of ajax. It will come handy, like:
$("#select_status").prop('disabled',true)
$('#select_id').append('<option>Please wait... Fetching status</option>');
var status_options;
$.ajax({
url:"your_page_for_all_status.php",
success: function(e){
//add <option> tags to a variable using loop
}
}).done(function(){
$.ajax({
//ajax call to get current data. Compare and select data here. write your $.each here
}).done(function(){
$("#select_status").prop('disabled',false);
});
});
You should be good to go now!!! I am sorry if I made it complex.
I have found a solution that worked but not sure it is very clean though.
For those interested to know:
HTML
<select class="form-control" name="select_status" id="status">
<option value=''>Selectionner</option>
<?php
try {
$user = new USER();
$output = array();
$stmt = $user->runQuery("SELECT * FROM info_status");
$stmt->execute();
$result=$stmt->fetchAll();
foreach($result as $row) {
echo '<option value='.$row["status_id"].'>'.$row["status_desc"].'</option>';
}
}
catch(PDOException $e) {
printf('Erreur MySQL %d : %s', $e->getCode(), $e->errorInfo[2]);
exit;
}
?>
</select>
We list down all options in my table into the dropdown list
AJAX
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"partials/test/fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#comp_name').val(data.comp_name);
$('#comp_parent').val(data.comp_parent);
$('#status').val(data.select_status);
fetching the right value from PHP page and sending to dropdown list so that this value is selected while opening the form (THE PROBLEM WAS HERE)
$('.modal-title').text("Modifier un fichier client");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
$('#operation').val("Edit");
}
})
});
PHP
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connection->prepare(
"SELECT *
FROM info_marques AS m
LEFT JOIN info_status AS s
ON s.status_id = m.comp_status
WHERE m.id = '".$_POST["user_id"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["comp_name"] = $row["comp_name"];
$output["comp_parent"] = $row["comp_parent"];
$output["status"] = $row["status_id"];
we return the match value
}
echo json_encode($output);
}
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function() {
var $article = null;
$('#category').change(function() {
var $categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo('.query');
}
$("#business").load("php.php");
});
});
</script>
This is what I am currently doing, I am loading the php.php script, instead I want to pass the value of $categoryName to the WHERE clause in my query so it's like this:
<?php
$con = mysqli_connect(,,,,);
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
$result = mysqli_query($con,"SELECT Bname, Category FROM Business WHERE Category='$categoryName'");
while($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['Bname']."'>".$row['Bname']."</option>";
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
The way this should work is, the first select box is populated by php on my server showing a list of categories. A user selects a category from that box and onchange, a second select box is created, added to the form, and will query, to populate all of the business name's listed in my database that share a category(i.e the selectedindex from the first box) Can you help me change this to work how I need it to?
UPDATE: This is the updated code, now the second select box never loads.
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script>
$(document).ready(function () {
var $article = null;
$('#category').change(function () {
var categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo ('.query');
$("#business").load( "php.php",
data:{myVar:$categoryName}
);
}
});
});
</script>
Heres the php.php
<?php
$con = mysqli_connect(,,,,);
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
$myVar = $_GET["myVar"];
$result = mysqli_query($con,"SELECT Bname, Category FROM Business WHERE Category='$myVar'");
while($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['Bname']."'>".$row['Bname']."</option>";
}
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
As seen below you can make a data object with one parameter myVar
JS:
$('#category').change(function() {
var $categoryName = $('#category').val();
if ($article == null) {
$article = $('<h4>Select a business you wish to view.</h4><select id="business" name="business" class="business"><option value="0">Select A Business To View Listing</option></select>').appendTo('.query');
}
$("#business").load("php.php",
data:{myVar:$categoryName}
);
});
Then get the variable in PHP like this
PHP:
$con = mysqli_connect(,,,,);
$myVar = $_GET["myVar"];
// Check connection
if (mysqli_connect_errno())
{
echo "<option>Failed to connect to MySQLi</option>" ;
}
So I created an auto complete box using jQuery and PHP to pull the content from the database, and it's working fine, except when I go to type in the input box it pulls back all the results, instead of the results similar to what I'm typing.
So if you type Test it pulls back:
This
is
a
Test
Instead of displaying
Test
Here is my HTML
<input type="text" id="group_name" name="group_name">
Here is the jQuery I'm using
<script>
$(document).ready(function() {
$( "#group_name" ).autocomplete({
source: "/wuzhapnn/php/data_stream/group_names",
select: function(event, ui) {
$("#f").submit(); }
});
});
</script>
Here is my php page
if ($_GET['run'] == 'group_names') {
// pulls live data from database
$db = db_open();
$query = "SELECT group_name FROM groups";
$result = db_query($db, $query);
if (db_num_rows($result) > 1) {
$result = db_fetch_all($result);
foreach ($result as $key=>$value) {
$group_names_array[] .= $value['group_name'];
}
} else {
}
echo json_encode(array_values(array_unique($group_names_array)));
}
Recent Updates
New jQuery
<script>
var availableName;
$.getJson('/wuzhapnn/php/data_stream',function(response){
availableName = response;
});
$(document).ready(function() {
$( "#group_name" ).autocomplete({
source: availableName,
select: function(event, ui) {
$("#f").submit(); }
});
});
</script>
New PHP Page
if ($_GET['run'] == 'group_names') {
// pulls live data from database
$db = db_open();
$query = "SELECT group_name FROM groups WHERE group_name LIKE '%".$_GET['term']."%'";
$result = db_query($db, $query);
if (db_num_rows($result) > 1) {
$result = db_fetch_all($result);
foreach ($result as $key=>$value) {
$group_names_array[] .= $value['group_name'];
}
} else {
}
echo json_encode(array_values(array_unique($group_names_array)));
}
You need to add LIKE clause.
"SELECT group_name FROM groups WHERE group_name LIKE '%".$_GET['term']."%'";
because "SELECT group_name FROM groups" this will give all the result from database but you need only those who match with typed words so use LIKE MySQL clause.
Other Person Comment Response.
if you want to create json object before use it you can do it as below,
var availableName;
$.getJson('/wuzhapnn/php/data_stream/group_names',function(response){
availableName = response;
});
after this just use below code for autoComplete.
$( "#group_name" ).autocomplete({
source: availableName ,
Your PHP snippet doesn't actually use the value sent by the autocomplete plugin.
If you are using JQuery's plugin then the value send is a GET parameter called terms.
This needs to be included in your PHP.
$term = $_GET['term'];
You then need to include that in your query something like the following, but first please escape this value before using it directly in an SQL statement.
SELECT group_name FROM groups WHERE group_name LIKE %<term>%
Got it working right
New jQuery
<script>
$(function() {
$( "#group_name" ).autocomplete({
source: "/wuzhapnn/php/data_stream",
minLength: 2,
});
});
</script>
New PHP (thanks to Dipesh Parmar)
// pulls live data from database
$db = db_open();
$query = "SELECT group_name FROM groups WHERE group_name LIKE '%".$_GET['term']."%'";
$result = db_query($db, $query);
$result = db_fetch_all($result);
foreach ($result as $key=>$value) {
$group_names_array[] .= $value['group_name'];
}
echo json_encode(array_values(array_unique($group_names_array)));
Inside my page I have an input ("Model") with a datalist attribute and a select menu ("Brand"). When a user select one of the options of the datalist from the Model, it will dynamically change the options value from the Brand select menu. Both options value from Model and Brand are called from the database. This is what I code so far;
<input type="text" name="type" id="type" list="datalist1" onchange="fw();"/>
<datalist id="datalist1">
<?php
$query9 = "SELECT DISTINCT model FROM server ORDER BY model ASC";
$result9 = mysql_query($query9);
while($row9 = mysql_fetch_assoc($result9))
{
echo '<option value="'.$row9['model'].'">';
} ?>
</datalist>
<select name="brand" id="test2"><option value="">-- Select Brand--</option></select>
Script;
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function fw()
{
var selname = $("#type").val();
$.ajax({ url: "getBrand.php",
data: {"brand":brand},
type: 'post',
success: function(output) {
document.getElementById('test2').options.length = 0;
document.getElementById('test2').options[0]=new Option(output,output);
// document.getElementById('test2').options[1]=new Option(output,output);
}
});
}
</script>
getBrand.php
<?php
define('DB_HOST1', 'localhost');
define('DB_NAME1', 'standby');
define('DB_USER1', 'root');
define('DB_PASS1', '');
$link = mysql_connect(DB_HOST1, DB_USER1, DB_PASS1);
if(!$link)
{
exit('Cannot connect to server "' . DB_HOST1 . '"');
}
mysql_select_db(DB_NAME1, $link) or die('Cannot use database "' . DB_NAME1 . '"');
if (isset($_POST['brand'])) {
$selname = $_POST['brand'];
$query = "SELECT * FROM server WHERE model='$brand'";
$res = mysql_query($query);
$aBrand= array();
while($rows = mysql_fetch_assoc($res)) {
$brand= $rows['brand'];
$aBrand[] = $brand;
echo $aBrand[0];
echo $aBrand[1];
}
} ?>
From what I have coded, I have succesfully change the select menu dynamically but there is one problem. When there is more one data is called from getBrand.php, the 'output' in the select menu will combine all of the data into one line. For example, if the data is "M3000" and "M4000", it will display as "M3000M4000". Now, how do I split it and make it as a normal select options?
I'm still learning Javascript and I hope anyone here can guide me.
NOTE : The code only works in Firefox because of the datalist attribute
Send your data from getBrand.php as
echo implode(";", $aBrand);
this will generate a string like M3000;M4000;M5000;M6000
and in your java script code break the string into array using this code.
StrArr = Str.split (";");
here 'Str' is your output given by getBrand.php, and 'StrArr' is the array which contains your brands.
add a special character in the string returned form php
PHP
elementcount=0;
while($row9 = mysql_fetch_assoc($result9))
{
if(elementcount>0)
echo '$<option value="'.$row9['model'].'">';//place a $ sign in start or you can for any special character
else
echo '<option value="'.$row9['model'].'">';
}
now in javascript
success: function(output) {
output = output.split("$");
document.getElementById('test2').options.length = 0;
//here now loop through the elements and add
for(var i=0,i<output.length-1)
document.getElementById('test2').options[0]=new Option(output[i],output[i]);
// document.getElementById('test2').options[1]=new Option(output,output);
}