Dropdowning with jquery and php - javascript

I am trying to change name of people on a table list. I will change it by a dynamic dropdown on a table cell. On this code, I can not get names from the suggestion box to the searchbox. I pick up the name from dropdown but the name choosen doesn't appear on the search box,
Anyone who knows why?
<td title="Name of workers">
<script>
$(document).ready(function(){
$("#search-box").keyup(function(){
$.ajax({
type: "POST",
url: "getpersonallist.php",
data:'keyword='+$(this).val(),
success: function(data){
$("#dropdown-box").show();
$("#dropdown-box").html(data);
$("#search-box").css("background","#FFF");
}
});
});
});
//I know something is wrong on this JQ part below.
function selectname(val) {
$("#search-box").val(val);
$("#dropdown-box").hide();
}
</script>
<input style="cursor: pointer; hover{background: yellow}" onclick="makeElementEditable(this)"
onblur="updatePersonal(this,'<?php echo $rs['id'] ?>')" type="text"
id="search-box"
value="<?php echo $rs['personal'] ?>"/>
<div id="dropdown-box"></div>
</td>
More code (getpersonallist.php):
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM personal WHERE personal like '%" . $_POST["keyword"] . "%' ORDER BY personal LIMIT 0,6";
$result = $db_handle->runQuery($query);
if(!empty($result)) {
?>
<ul id="selectname">
<?php
foreach($result as $name) {
?>
<li onClick="selectname('<?php echo $name["personal"]; ?>');"><?php echo $name["personal"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>

I'm not sure if you made any errors, but your function selectName() is never called, which could be a problem. I'm not sure where you want to call it either, but make sure it is called in an appropriate place.

Related

variable transfer between php and js with ajax

I encountered a problem.
I have a list of restaurants, ids are named with number at the end strong_restName1 strong_restAddress1 strong_restName2 strong_restAddress2 ... At first I tried doing this href="?count=<?php echo $count] ?>" so I could get value with $_GET['count'] when I press on that <a> tag, I want to use element with that specific id. Basically, my code should work like this: there is list of restaurants, if I press on one of them, it is selected, and should now display that name and address as selected restaurant.
I will put in some code of creating this list:
restaurantlist.php
$count = 0;
while ($row = mysqli_fetch_assoc($result))
{
if ($row['name'] != trim(urldecode($_COOKIE['restaurant_name'])) && $row['address'] != trim(urldecode($_COOKIE['restaurant_address'])))
{
$count++;
$strongRestName = "strong_restName".$count;
$strongRestAddress = "strong_restAddress".$count;
?>
<li class="acc" style="padding: 0;margin: 0;max-width: 100%;word-break: break-all;">
<a class="acc-link" href="" style="position: relative;display: block;width: 100%;padding-bottom: 10px;outline: none;text-decoration: none;padding-right: 0px;padding-left: 10px;padding-top: 10px;" onclick="myAjax()">
<div class="acc-text" style="max-width: 100%;">
<small class="form-text text-muted" style="margin: 0;font-size: 18px;color: rgb(0,0,0);line-height: 18px;">
<strong id="<?php echo $strongRestName ?>" > <?php echo $row['name'] ?></strong></small>
</div>
<div>
<small class="form-text text-muted" style="color: rgb(0,0,0);" id="<?php echo $strongRestAddress ?>">
<?php echo $row['address'] ?>
</small>
</div>
</a>
</li>
<?php
}
}
?>
On every <a> tag there is onclick="myAjax()"
index.php
<?php include('restaurantlist.php'); ?>
<script>
function myAjax() {
var count = "<?php echo $_GET['count'] ?>";
var strongRestName = "#strong_restName" + count;
var strongRestAddress = "#strong_restAddress" + count;
alert($(strongRestName).text());
$.ajax({
type: "POST",
url: '/restaurants/ajax.php',
data:
{
action:'cookies_change',
restName: $(strongRestName).text(),
restAddress: $(strongRestAddress).text()
},
success:function(html) {
alert($('#strong_restName1').text());
}
});
}
</script>
but the problem with $_GET['count'] that it won't read when pressing first time, I tested it out with alert(). It only captures value from $_GET when I press second time on a link. In ajax.php I just use variables sent from ajax and assign them to COOKIES, according to my goal.

Not able to fetch selected value from dropdown into a php variable, and use the value of that variable to fetch other data

I have a form that has some text fields and 2 drop-down lists, from the first drop-down list I need to fetch the selected value and store it in a PHP variable so I can use that variable to fetch another set of data into the 2nd drop-down. I do not want to use the submit button.
I have tried using ajax, I am getting the value as chosen in the console, but not able to fetch the same into a PHP variable.
//1st Drop-down
<dl>
<dt>Project ID</dt>
<dd>
<!-- Function to select the dropdown value -->
<script type="text/javascript" src="<?php echo
url_for('/public/js/jquery.js'); ?>"></script>
<script type="text/javascript">
function fetch_select(val)
{
console.log(val);
$.ajax({
type: "POST",
url: "/flat_booking_again/adminsAccess.php",
data: {
get_option:val
}, success: function(response){
console.log(response);
document.getElementById("new_select").innerHTML=response;
//alert(get_option);
}
});
}
</script>
<select name = "project_id" style ="width:150px" onchange="fetch_select(this.value);">
<option>
<?php
$result = find_projects_without_admins();
foreach($result as $row) { ?>
<option value="<?php echo $row['project_id']; ?>" selected="selected"><?php echo $row['project_id']; ?></option>
<?php }?>
</option>
</select>
</dd>
</dl>
<dl>
//I need to use the fetched data from above to populate this drop-down
<dt>Block ID</dt>
<dd>
<select id="new_select" name="block_id" style ="width:150px">
<option>
<?php
echo $_POST['get_option'] . "hellllllllllllo"; //Not able to fetch value
if(isset($_POST['get_option'])){
$projectId = $_POST['get_option'];
$result = find_blocks_without_admins($projectId);
foreach($result as $row) { ?>
<option value="<?php echo $row['block_id']; ?>" selected="selected"><?php echo $row['block_id']; ?></option>
<?php }
}
?>
</option>
</select>
I am really new to PHP and AJAX sp pardon me for any silly mistakes. I know this may sound like a repeated question, but I am stuck with this bug for long, any help is really appreciated. Thanks !
Change your code with this.
<dl>
<dt>Project ID</dt>
<dd>
<!-- Function to select the dropdown value -->
<script type="text/javascript" src="<?php echo url_for('/public/js/jquery.js'); ?>"></script>
<script type="text/javascript">
function fetch_select(val)
{
console.log(val);
$.ajax({
type: "POST",
url: "/flat_booking_again/adminsAccess.php",
data: {
get_option:val
}, success: function(response){
console.log(response);
document.getElementById("new_select").innerHTML=response;
//alert(get_option);
}
});
}
</script>
<select name = "project_id" style ="width:150px" onchange="fetch_select(this.value);">
<option>
<?php
$result = find_projects_without_admins();
foreach($result as $row) { ?>
<option value="<?php echo $row['project_id']; ?>" selected="selected"><?php echo $row['project_id']; ?></option>
<?php }?>
</option>
</select>
</dd>
</dl>
<dl>
//I need to use the fetched data from above to populate this drop-down
<dt>Block ID</dt>
<dd>
<select id="new_select" name="block_id" style ="width:150px"></select>
<?php
//echo $_POST['get_option'] . "hellllllllllllo"; //Not able to fetch value
if(isset($_POST['get_option'])){
$projectId = $_POST['get_option'];
$result = find_blocks_without_admins($projectId);
$html = '';
foreach($result as $row) { ?>
$html.="<option value='".$row['block_id']."' selected='selected'>".$row['block_id']."</option>";
}
echo $html;
}
?>

Excecuting php when clicking a button

So I've made a database where people can upload pictures to. The pictures are linked to a place which is linked to a category.
I'm trying to create a gallery page that displays all the images, and then the categories available. When you click on a category it's meant to show all the pictures for that category.
I've got my categories in my database as well, which I'm using php to echo out:
<?php
include('includes/connectdb.php');
/* Selects id and name from the table 'category' */
$query = "SELECT id, name FROM category";
$result_category = mysqli_query($dbc,$query);
?>
<h1>Category</h1>
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<button name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?></button>
<?php endwhile; ?>
When a button is clicked I need it to run this php:
<?php
if(isset($_POST['category[]'])){
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
}
?>
I found out that it should be possible with ajax, so I added the following to my ajax.php file:
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'category':
category();
break;
}
}
function category() {
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
exit;
}
?>
And this to my gallery.php file where I'm displaying the pictures and categories.
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
And lastly I changed my button to be
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="submit" class="button" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
I'm linking to the jquery library and I've tested the SQL statement that I need to run, and it works when I specify what the placecategory.category_id is.

how to display data on button click in a loop using php

I have a project in which I am displaying a button tag in a while loop. On every button click I want to display an alert box with the respective UserId. Here is my code:
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo1" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div>
<?php } ?>
Here is my validate function:
function validate1(id2)
{
// var id2;
id2 = document.getElementById('demo2').getAttribute('value');
alert(id2);
}
But it is always showing me last user id .. whereas i want to display userid for every user on everyclick.
Can someone help?
Here man, the function you were calling was undefined validate1, also you don't need to get any arguments on your function declaration, since you are not passing any arguments when you invoke it.
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div>
JS
function validate(){
var id2 = document.getElementById('demo').getAttribute('value');
alert(id2);
}
try this in your code
HTML:
<button onClick="validate('<?php echo $RegisterId; ?>')">Show Interest</button>
Javascript:
function validate(id2)
{
alert(id2);
}
Your code needs some modifications.
Firstly, you have made a provision to send id to javascript function, but, you are not passing id to it.
PHP
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo1" value="<?php echo $dis1['RegisterId'];?>">
<button onClick="validate('<?php echo $dis1['RegisterId'];?>')">Show Interest</button>
</div>
<?php } ?>
Javascript:
function validate1(id2) {
// var id2;
//id2 = document.getElementById('demo2').getAttribute('value');
alert(id2);
}
With this code, your clicks shouldn't even return the last id. Your javascript function is not looking good.
This should work;
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<!-- removed id attribute, as they're unique, you can't set it to every div.
If you really need id attribute, you can set one by using your RegisterId (e.g. id="demo-<?php echo $RegisterId; ?>)
And moved value attribute to button tag, it's much more useful in it. -->
<div>
<button onClick="validate(this)" value="<?php echo "$RegisterId" ?>">Show Interest</button>
</div>
<?php } ?>
Javascript
function validate(element){
alert(element.value)
}
This way, you can use it in other stuff much easier.

Javascript Only the first button submits to Ajax form despite different Ids

Other users have had similar problems about when they're looping rows of buttons but it's always because they accidentally reused the same Id or value. I'm experiencing the same problem, but all of my buttons are unique.
AJAX request
<script>
$(document).ready(function(){
$("#friendadd").submit(function(){
alert("checkpoint");
$.ajax({
type:"POST",
url:"getuser.php"
});
})
});
</script>
PHP and form
<form id="friendadd">
<?php
for($i=0; $i<$ctk->rowCount(); $i++){
echo "<img src='".$ctk_values[$i][6]."' alt='Blank' style='width:64px;height:64px'>";//PP, Later add clickable profile
echo "<th rowspan='3'>Attributes</th>";
echo "<tr> ".$ctk_values[$i][0]."</tr>";//UN
echo "<tr> ".$ctk_values[$i][1]."</tr>";//UL
echo "<tr> ".$ctk_values[$i][5]."</tr>";//UA
?>
<input type="submit" id="friend<?php echo $i;?>"><!--pass in this.value-->
</form>
<?php
}//Ends for loop
}
}
?>
Explanation: When I type in a username into the search box, it returns me three different users named rikesh1, rikesh2, and rikesh3. Each of them have a button next to them, with values friend0, friend1, friend2, respectively. When I click on the friend0 button, it successfully calls and updates the database. When I click the friend1 button, nothing happens. This is different from other users in that my buttons have unique Ids. Thanks for any and all help, I think this is a very fixable problem but after searching Stack, I'm still not sure what's happening.
<form id="friendadd">
<?php
for($i=0; $i<$ctk->rowCount(); $i++){
echo "<img src='".$ctk_values[$i][6]."' alt='Blank' style='width:64px;height:64px'>";//PP, Later add clickable profile
echo "<th rowspan='3'>Attributes</th>";
echo "<tr> ".$ctk_values[$i][0]."</tr>";//UN
echo "<tr> ".$ctk_values[$i][1]."</tr>";//UL
echo "<tr> ".$ctk_values[$i][5]."</tr>";//UA
?>
<input type="submit" id="friend<?php echo $i;?>"><!--pass in this.value-->
<?php
}//Ends for loop
?>
</form>
<?php
}
}
?>
Use this code instead.
The other one ends the form tag at the first loop.

Categories

Resources