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)));
Related
I would like to update the data in the frontend when it is changed in the database. The code I'm using is given below:
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<div id="test">
<?php
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = 1;";
if(mysqli_fetch_assoc(mysqli_query($conn, $query))["name"] == "MyName")
echo 'Hi <b>MyName!</b>';
else
echo 'You are not <b>MyName</b>.';
?>
</div>
<script>
setInterval(function(){
$.get("/test.php", function(data){
let $data = $(data);
$("#test").append($data.find("#test > *"));
});
}, 1000);
</script>
However, when the data is updated, it does not get updated in the frontend unless refreshed. When I use jQuery's load() function, it works perfectly. Why does this not work?
As I suggested in the comment, if you create a stand alone PHP Script, it might be like:
getUserName.php
<?php
$id = (int)$_GET['id'];
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = $id;";
$myName = "";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$myName = $row;
}
}
mysqli_free_result($result);
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($myName);
?>
This is a very basic example and I would strongly advise you switch to using prepared statements to avoid the risk of SQL Injection.
In your HTML you can now do:
<script>
setInterval(function(){
$.getJSON("/getUserName.php", { id: 1 }, function(data){
$("#test").append(data.name);
});
}, 1000);
</script>
This will ping the script every second and you will have a list of names appearing.
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);
}
I am using the following code to generate a random string in php, and then am storing this in my database like so:
<?php $allowance_promo = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8); ?>
I am then using my query to store this value into the database:
$query = sprintf("UPDATE internal_users SET allowance_promo = '$allowance_promo' WHERE user_id ='{$_SESSION['id']}'");
$result = mysql_query($query);
I then use another query to retrieve the value:
$query2 = sprintf("SELECT * FROM internal_users WHERE user_id ='{$_SESSION['id']}'");
$result2 = mysql_query($query2);
while ($row = mysql_fetch_array($result2)) {
$check = $row['allowance_promo'];
Then i am trying to use jquery to check if the value entered into my input field matches the one in the database like so:
<script>
$(document).ready(function() {
$('.promo_check').click(function() {
var discountCode = "<?php echo $check; ?>";
var codeEntered = $("input[name='promo']").val();
if (discountCode == codeEntered) {
$('#submit').removeAttr("disabled");
}
});
});
</script>
However i am having some difficulty getting it to work using a php string. If i use normal text like var discountCode = '123'; then it works, but when i try and use var discountCode = "<?php echo $check; ?>"; it wont work. Can someone please show me what i am doing wrong. Thanks,
Replace your script by the script below. Put discountCode outside the click event handler and remove $(document).ready();
<script type="text/javascript">
var discountCode = "<?php echo $allowance_promo; ?>";
$('.promo_check').click(function() {
var codeEntered = $("input[name='promo']").val();
if (discountCode == codeEntered) {
$('#submit').removeAttr("disabled");
}
});
</script>
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
});
});
I have a variable that I am retrieving upon a users button press (artist_id), which I am successfully getting. I would like to use this artist_id to find the artist name, which I have in a database. So far I have been unsuccessful exporting the artist name to the javascript as a varaible.
Here is the javascript/jquery:
<script>
$(function() {
$( "#dialog-modal" ).dialog({autoOpen: false, height: 250, width: 400, modal: true});
$( "#opener" ).click(function() {
$( "#dialog-modal" ).dialog( "open" );
$.get('/like_artist.php', {artist_id : $(this).data('artist_id'), stage_name : $stage_name}, function(data) {
alert("Data Loaded: " + data.artist_id);
var text = '';
var artistId = data.artist_id;
var stage_Name = data.stage_name;
text = 'You have liked ' + artistId + stage_Name;
$('#dialog-modal').text(text);
}, "json");
});
});
</script>
Here is the php (like_artist.php):
<?php
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";
$current_user = current_user();
include_once("config.php");
$artist_id = $_GET['artist_id'];
$query_two = "SELECT stage_name FROM artists WHERE id='.$artist_id.'";
$stage_name = mysql_fetch_row(mysql_query($query_two));
$stage_name = $stage_name[0];
echo json_encode(array('artist_id' => $artist_id));
echo json_encode(array('stage_name' => $stage_name));
$user_id = $current_user['id'];
$query = "INSERT INTO `user_artists`
(`artist_id`, `user_id`)
VALUES
('$artist_id', '$user_id')";
$result = mysql_query($query);
?>
Thank you for the help!
You want to use JSON to bundle up your information in your PHP code and then parse it with JavaScript:
http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP
On a side note, you should also look into using Prepared Statements for your queries.
Edit: Here is a better link showing a simple demo:
http://www.caveofprogramming.com/php/php-json-an-example-javascript-json-client-with-php-server/