variable transfer between php and js with ajax - javascript

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.

Related

Making a jQuery change permanent on page refresh

Back Ground:
I have made a script that loads a table of product names, when you click a button on that table row it shows a search box. This search box uses the jquery UI autocomplete function. When an option is selected it pulls that products information from a different database from this main project database and puts them in their corresponding tags within the table. It also then submits this content to another table in another database which is the main database for the project. It is storing the information correctly, and when the foreach loop runs with the database content from the main project it is loading correctly. The button that the user presses to reveal the search box says "Link Product", once they selected it the button changes css and html value to Edit Product.
The problem
The issue I'm having is any table row that has content loaded from the main database needs to have the "Edit Button" still be there and any blank rows must show the Link Product Button. But when you refresh the page they all revert to "Link Button".
Now I'm going to show you the code but I will give you a heads up its very messy as I'm new to both ajax and jquery.
The Code
Html Page
<div class="container">
<div class="row">
<div class="col text-center">
<h3 id="edit_sheet_title" class="mt-3 mb-3"><?php echo $title; ?></h3>
</div>
</div>
<div class="row mb-5">
<div class="col-xl-12 col-md-12 col-sm-12 col-12 text-center">
Bulk Import
Container Import
Add Product
Generate Sheet
Go Back
</div>
</div>
</div>
<div class="table-container">
<div class="row">
<div class="col">
<div class="table-responsive">
<table class="table" id="sheet_list">
<thead>
<tr>
<th class="align-middle th-id">ID</th>
<th class="align-middle th-name">Product Name</th>
<th>Ingredients</th>
<th id="button_th"></th>
</tr>
</thead>
<tbody>
<?php if(!empty($sheet_product_list)) { ?>
<?php foreach($sheet_product_list as $product) { ?>
<tr>
<td><p data-id="entry_id" id="entry_id" class="table-p"><?php echo $product['entry_id']; ?></p></td>
<td class="td-name"><?php echo $product['display_name']; ?></td>
<td>
<div id="search_div">
<input type="text" class="wholesale_product_search mb-5 block" data-info="search_box" data-entry-id="<?php echo $product['entry_id']; ?>" name="product_search" id="product_search" placeholder="Search for product...">
</div>
<p data-info="product_id" id="product_id" class="<?php echo $product['entry_id']; ?>">
<?php if(isset($product['wholesale_product_id'])){ echo "Product ID: " . $product['wholesale_product_id'];} ?>
</p>
<p data-info="wholesale_name" id="wholesale_name" class="<?php echo $product['entry_id']; ?>">
<?php if(isset($product['wholesale_name'])){ echo $product['wholesale_name'];} ?>
</p>
<p data-info="is_manual" class="<?php echo $product['entry_id']; ?>">
</p>
<p data-info="ingredients_section" id="ingredients_section" class="<?php echo $product['entry_id']; ?>">
<?php if(isset($product['wholesale_ingredients'])){echo $product['wholesale_ingredients'];} ?>
</p>
</td>
<td class="pull-right align-middle">
<div class="button_td_div">
<button id="edit_product_button" data-id="<?php echo $product['entry_id']; ?>" class="btn btn-info" role="button">Link Product</button><br>
<a id="column_button" href="<?php echo URLROOT; ?>product/delete/<?php echo $sheet['sheet_id']; ?>/<?php echo $product['entry_id']; ?>" class="btn btn-danger" role="button">Delete Product</a>
</div>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<input type="hidden" id="sheet_id" value="<?php echo $sheet_id; ?>">
Jquery Function
$('button[data-id]').click( function () {
var display_name = $('.td-name').html();
var entry_id = $(this).attr("data-id");
var search_box = $("input[data-info='search_box'][data-entry-id="+entry_id+"]");
var ingredients_section = $("p[data-info='ingredients_section']."+entry_id);
var wholesale_name = $("p[data-info='wholesale_name']."+entry_id);
var wholesale_product_id = $("p[data-info='product_id']."+entry_id);
var edit_button = $('button[data-id='+entry_id+']');
const sheet_id = $('#sheet_id').val();
$(search_box).on( "autocompleteselect", function(e, ui) {
var result_string = ui.item.value; // this is the string returned from the search
var product_id = result_string.match( /\d+/ )[0];
$(search_box).hide();
edit_button.html('Edit Product');
edit_button.removeClass("btn btn-warning").addClass("btn btn-success");
$.ajax({
type: "GET",
url: ajax_url,
data: "product_id="+product_id,
success: function(data){
var obj = JSON.parse(data);
const ingredients = obj[0].ingredients;
const product_name = obj[0].name;
const w_product_id = obj[0].product_id;
$(wholesale_product_id).html('Product ID: '+w_product_id);
$('#confirmed').show();
$(wholesale_name).html('Wholesale Name: '+product_name);
$(ingredients_section).html(ingredients);
$.ajax({
type: "POST",
url: ajax_url,
data: {post_sheet_id: sheet_id,post_wholesale_product_id: w_product_id, post_wholesale_ingredients: ingredients, entry_id: entry_id,wholesale_product_name: product_name},
success: function(data){
var obj = JSON.parse(data);
$.ajax({
type: "GET",
url: ajax_url,
data: "sheet_id="+sheet_id+"&content",
success: function(data){
var obj = JSON.parse(data);
const content = obj[0].wholesale_product_id;
console.log(content);
}
});
}
});
}
});
} );
if($(this).html() == 'Link Product'){
$(search_box).show();
$(search_box).focus();
$(this).html('Cancel');
$(this).removeClass("btn btn-info");
$(this).addClass("btn btn-warning");
} else if($(this).html() == 'Cancel'){
$(search_box).hide();
$(this).removeClass("btn btn-warning");
$(this).addClass("btn btn-info");
$(this).html('Link Product');
}
} );
$(function() {
$(".wholesale_product_search").autocomplete({
source: ajax_url,
minLength: 1
});
});
I have not a single clue how to make the Edit Product html value to stay on the page refresh, every time I refresh that page all the buttons go back to saying Link Product, but I only want blank ingredients boxes to have a "Link Product" button, any with ingredients loaded the button needs to say "Edit Product".
I have been driven mad by this for days and I'm at my whits end.
Any help, literally anything at all would spare me my sanity.
** EDIT **
I know its a horrendous mess, but my deadline is fast approaching I'm miles off and at this point will do whatever it takes to make it work. It's used in house and is not accessible to the outside world.
Just use php if else statmant:
<?= isset($product['wholesale_ingredients']) ? 'Edit product' : 'Link Product' ?>
This will echo 'Edit product' if wholesale_ingredients is set, and 'Link product' wholesale_ingredients is empty
This is how your actual button should look like
<div class="button_td_div">
<button id="edit_product_button" data-id="<?php echo $product['entry_id']; ?>" class="btn btn-info" role="button">
<?= isset($product['wholesale_ingredients']) ? 'Edit product' : 'Link Product' ?>
</button><br>
<a id="column_button" href="<?php echo URLROOT; ?>product/delete/<?php echo $sheet['sheet_id']; ?>/<?php echo $product['entry_id']; ?>" class="btn btn-danger" role="button">Delete Product</a>
</div>

How to add different numbers at automatically added divs?

Im working on a confession website, and on the website I have a section "Top of the Week" which displays 3 most liked confessions from current week, it displays them in a horizontal slider by most liked order, so it goes most liked, second most liked, third most liked confession. The thing that Im trying to do is to put #1, #2, #3 number on each one, but I can't achieve that because I only style one div and website automatically create two other and add confession to it.
This is my php + html code that I use to display them:
<div class="sidebox">
<?php
$select = "SELECT confessions.confessId,
(IFNULL(confessions.firstName, '')) AS firstName,
confessions.confessText,
DATE_FORMAT(confessions.postDate,'%b %d %Y %h:%i %p') AS postDate,
hasImage,
UNIX_TIMESTAMP(confessions.postDate) AS orderDate,
confessions.isActive,
(SELECT COUNT(*) FROM views WHERE views.confessId = confessions.confessId ) as totalViews,
(SELECT COUNT(*) FROM likes WHERE likes.confessId = confessions.confessId ) as totalLikes,
(SELECT COUNT(*) FROM dislikes WHERE dislikes.confessId = confessions.confessId ) as totalDislikes
FROM
confessions
WHERE isActive = 1
ORDER BY totalViews DESC , orderDate DESC limit 3";
$resss = mysqli_query($mysqli, $select) or die('-3' . mysqli_error()); ?>
<div id="sticky-nav" style="height:36px;" class="absolute" style="z-index:0">
<div id="width-limit">
<div class="options">
<ul class="menu">
<li><a class="carousel_prev previous" href="#"><b style="font-size: 20px;">‹</b></a></li>
<li><a style="opacity:1;padding-top:1px;position:relative;left:-54px;"><i class="fas fa-crown" id="crownicon"></i> Top of the Week</a> </li>
<li><div class="menu-clear"></div></li>
<li><a class="carousel_next next" href="#"><b style="font-size: 20px;">›</b></a></li>
</ul>
</div>
<div class="options" id="opt2" style="float:right; width:280px;display:none;">
<ul style="display: inline-block;float:right;">
</ul>
</div><div class="options" id="opt2" style="float:right; width:280px;display:none;">
<ul style="display: inline-block;float:right;">
</ul>
</div>
<div id="small-logo"></div>
<div class="clearfix"></div>
</div>
</div><div class="sidecontainer">
<div class="slick">
<?php
while ($row = mysqli_fetch_assoc($resss)) {
// Get Total Comments
$comssql = "SELECT 'X' FROM comments WHERE confessId = ".$row['confessId']." AND isActive = 1";
$commentstotal = mysqli_query($mysqli, $comssql) or die('-4'.mysqli_error());
$totComments = mysqli_num_rows($commentstotal);
if ($totComments == '1') { $comText = 'Comment'; } else { $comText = 'Comments'; }
if ($row['totalViews'] == '1') { $viewText = 'View'; } else { $viewText = 'Views'; }
$shareURL = $set['installUrl'].'page.php?page=view&confession='.$row['confessId'];
?>
<div class="confession" style="margin-left: 0;width: 300px;">
<div class="left"><span class="label2 label-confess1"><?php echo $row['totalViews'].' '.$viewText; ?></span></div>
<div class="right"><span class="bestthisweek">
<?php if ($row['totalLikes'] == '12') { echo "Top of the Day!"; } else { echo "Top!"; } ?>
</span></div>
<div class="confessionstyle" style="margin-top:20px;"><p>
<font color="#fff3b2">
<?php
if ($filterProfanity == '1') {
echo nl2br(htmlspecialchars(filterwords($row['confessText'])));
} else {
echo nl2br(htmlspecialchars($row['confessText']));
}
?>
</font>
</p></div>
<input type="hidden" id="confessId" name="confessId_<?php echo $count; ?>" value="<?php echo $row['confessId']; ?>" />
<?php
$chkLikes = mysqli_query($mysqli,"SELECT 'X' FROM likes WHERE confessId = ".$row['confessId']." AND likeIp = '".$_SERVER['REMOTE_ADDR']."' LIMIT 1");
$hasLike = mysqli_num_rows($chkLikes);
$likeCSS = $hasLike > 0 ? 'text-info' : 'white';
$chkDislikes = mysqli_query($mysqli,"SELECT 'X' FROM dislikes WHERE confessId = ".$row['confessId']." AND dislikeIp = '".$_SERVER['REMOTE_ADDR']."' LIMIT 1");
$hasDislike = mysqli_num_rows($chkDislikes);
$dislikeCSS = $hasDislike > 0 ? 'text-danger' : 'white';
?>
<div class="confession-actions">
<div class="likes" style="width: 75px;">
<span class="label2 label-confess first liked">
<a href="" id="likeIt_<?php echo $row['confessId']; ?>" class="likeIt_<?php echo $count; ?> <?php echo $likeCSS; ?>" style="text-decoration:none;outline:none;">
<i class="fas fa-thumbs-up"></i> <span style="color:white;" id="likesVal_<?php echo $row['confessId']; ?>"><?php echo $row['totalLikes']; ?></span>
</a>
</span>
</div>
<div class="dislikes" style="width: 75px;">
<span class="label2 label-confess disliked">
<a href="" id="dislikeIt_<?php echo $row['confessId']; ?>" class="dislike_<?php echo $count; ?> <?php echo $dislikeCSS; ?>" style="text-decoration:none;outline:none;">
<span style="color:white;" id="dislikesVal_<?php echo $row['confessId']; ?>"><?php echo $row['totalDislikes']; ?></span> <i class="fas fa-thumbs-down"></i>
</a>
</span>
</div>
<?php if ($row['hasImage'] != '0') { ?>
<span class="label label-confess"><i class="fa fa-picture-o img"></i></span>
<?php } ?>
<div class="comments">
<div class="divide" style="width: 75px;"><div id="comments-hvr"><a href="page.php?page=view&confession=<?php echo $row['confessId']; ?>">
<i class="fa fa-comments"></i> <?php echo $totComments.' '; ?>
</a></div></div>
</div>
<div class="divide2" style="width: 75px;"><div class="fb-share-button" style="top:-6.5px;transform: scale(0.93);"
data-href="page.php?page=view&confession=<?php echo $row['confessId']; ?>"
data-layout="button_count"></div></div></div>
<div class="clearfix"></div>
</div>
<?php
}
?>
</div>
I tried everything and this is the best solution that I have, but I can't figure out what should I put inside if, elseif, else, I need something that will place #1 on first, #2 on second, #3 on third confession. So I would need something like this but something that will not require me to manually insert > likes.
<?php if ($row['totalLikes'] > '11') { echo "#1"; } elseif ($row['totalLikes'] > '5') { echo "#2"; } else { echo "#3"; }?>
Please visit my website, its still in development, but check Top of the Week on the right and you'll have a clue of what I actually want: http://confessions.byethost31.com
FINAL:
<?php $i = 1; ?>
<?php
echo '#'.$i;
$i++;
?>
Easiest way to to just create a variable that increments with every while iteration.
$i = 1; // set initial value
while ($row = mysqli_fetch_assoc($resss)) {
echo 'This number will grow by 1 for every row - '.$i;
$i++; // this is equal to $i = $i + 1; so will increment by 1 every time.
}
EDIT:
Instead of attempting to assume what the total likes would be, it would be easier to sort them by total likes (putting the most liked first and assigning this #1).
ORDER BY totalLikes DESC, totalViews DESC, orderDate DESC
You can then just use
echo '#'.$i;
Where you want to display the number, you can do this because you have LIMIT 3 so only the top 3 will display.

modal popup keep populating only first item data on all item buttons

I am implementing cloth shopping website in which i am uploading cloth items with their images and description from admin panel. on home page i am retrieving all cloth items that are in stock and displaying using while loop. in order to view details i have put "view button" which on click opens modal popup and displays whole description of the item. But i am facing problem that every button of item on click only displays first item description in modal popup on all item button. I want that every item button should display item owns description. but it keeps populating first item data on every button.
Code:
<?php
$link = mysql_connect("localhost", "root", "") or die("Cannot Connect to the database!");
mysql_select_db("login", $link) or die("Cannot select the database!");
$sql = "SELECT * FROM add_stock";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {?>
<div class="grid_element">
<div class="show-image">
<form method="post" action="" id="myform" >
<img src="<?php echo $row['image'] ?>" name="image" onclick="openModal()" id="image" name="image1" target="_parent">
<figcaption>
<b>Product Code: <?php echo $row['id']; ?> <br/>
<?php echo $row['dress_description']; ?> <br/>
PKR <?php echo $row['price']; ?></b>
</figcaption>
</form>
<!-- view button -->
<button class="update fa fa-eye" id="popupview" onclick="openModal1()" title="View" type="image" /></button>
<!-- View Item modal popup -->
<div id="mpopupBox" class="mpopup">
<!-- mPopup content -->
<div class="mpopup-content">
<div class="mpopup-head">
<span class="close7">×</span>
<h2 style="font-family:Cooper Black;">Item Description</h2>
</div>
<div class="mpopup-main" ><br/>
<img src="<?php echo $row['image']; ?>" style="width: 300px; height: 300px; border-radius: 25px;">
<p style="margin-top: -250px; margin-left: 380px; "><font size="4"><b>Product Code: <?php echo $row['id']; ?> <br/>
PKR <?php echo $row['price']; ?> <br/>
Brand: <?php echo $row['brand_name']; ?> <br/>
Gender: <?php echo $row['gender_name']; ?><br/>
Category: <?php echo $row['category_name']; ?><br/>
Size: <?php echo $row['size_name']; ?> <br/>
Material: <?php echo $row['material_name']; ?> <br/>
Description: <?php echo $row['dress_description']; ?></font></b> </p>
<button style="margin-left: 380px; margin-top: 20px; width: 135px;" class="button button4 add-to-cart"><i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<div class="mpopup-foot">
<!-- <p>created by CodexWorld</p> -->
</div>
</div>
</div>
<script type="text/javascript">
var mpopup = document.getElementById('mpopupBox');
// get the link that opens the mPopup
var mpLink = document.getElementById("popupview");
// get the close action element
var close7 = document.getElementsByClassName("close7")[0];
// open the mPopup once the link is clicked
mpLink.onclick = function () {
mpopup.style.display = "block";
}
var imagess = document.querySelectorAll('button[title="View"]');
for (var i = 0, len = imagess.length; i < len; i++) {
imagess[i].addEventListener('click', openModal1);
}
function openModal1() {
mpopup.style.display = "block";
}
// close the mPopup once close element is clicked
close7.onclick = function () {
mpopup.style.display = "none";
}
</script>
</div>
</div>
1) The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead. Stop using mysql functions.
2) Why to connect database connection on each and every file. Create one common db file where database connection code is written and include in each file. Otherwise, when database or username or password get changed, then you have to change it in each and every file. So, to avoid it, create one common db file.
db.php
<?php
$link = mysql_connect("localhost", "root", "") or die("Cannot Connect to the database!");
mysql_select_db("login", $link) or die("Cannot select the database!");
?>
3) IDs can't be same through out a page. So, change it accordingly.
YourPage.php
<?php
include("db.php");
$result = mysql_query("SELECT * FROM add_stock");
while ($row = mysql_fetch_assoc($result)) {?>
<div class="grid_element">
<div class="show-image">
<form method="post" action="" id="myform" >
<img src="<?php echo $row['image'] ?>" name="image" onclick="openModal()" id="image" name="image1" target="_parent">
<figcaption>
<b>Product Code: <?php echo $row['id']; ?> <br/>
<?php echo $row['dress_description']; ?> <br/>
PKR <?php echo $row['price']; ?></b>
</figcaption>
</form>
<button class="update fa fa-eye openPopUp" data-url="ajax_pop_up.php?id=<?php echo $row['id'];?>" title="View" type="image" /></button>
</div>
</div>
<?php }?>
<style>
.displayBlock{display:block;}
.displayNone{display:none;}
</style>
<div id="mpopupBox" class="mpopup displayNone">
</div>
<script>
//For Opening Pop Up
$(document.body).on('click', '.openPopUp', function () {
$("#mpopupBox").removeClass("displayNone").addClass("displayBlock");
$.ajax({url:$(this).attr('data-url'),cache:false,success:function(result){
$("#mpopupBox").html(result);
}});
});
//For Closing Pop Up
$(document.body).on('click', '.close7', function () {
$("#mpopupBox").removeClass("displayBlock").addClass("displayNone");
});
</script>
4) Create one common ajax pop up file in same directory, where pop up content will appear.
ajax_pop_up.php
(if you are planning to change file name here, change in data-url of YourPage.php page, both are related to each other)
<?php
include("db.php");
$result = mysql_query("SELECT * FROM add_stock WHERE id=".$_GET['id']);
while ($row = mysql_fetch_assoc($result)){?>
<!-- mPopup content -->
<div class="mpopup-content">
<div class="mpopup-head">
<span class="close7">×</span>
<h2 style="font-family:Cooper Black;">Item Description</h2>
</div>
<div class="mpopup-main" ><br/>
<img src="<?php echo $row['image']; ?>" style="width: 300px; height: 300px; border-radius: 25px;">
<p style="margin-top: -250px; margin-left: 380px; "><font size="4"><b>Product Code: <?php echo $row['id']; ?> <br/>
PKR <?php echo $row['price']; ?> <br/>
Brand: <?php echo $row['brand_name']; ?> <br/>
Gender: <?php echo $row['gender_name']; ?><br/>
Category: <?php echo $row['category_name']; ?><br/>
Size: <?php echo $row['size_name']; ?> <br/>
Material: <?php echo $row['material_name']; ?> <br/>
Description: <?php echo $row['dress_description']; ?></font></b> </p>
<button style="margin-left: 380px; margin-top: 20px; width: 135px;" class="button button4 add-to-cart"><i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<div class="mpopup-foot">
<!-- <p>created by CodexWorld</p> -->
</div>
</div>
<?php }?>
Similar Question
GET PHP variable value from HTML data-id
Passing data via Modal Bootstrap and getting php variable?
Quick Links
Can an html element have multiple ids?
Go through it. And, if any problem comes, feel free to ask.

Dropdowning with jquery and php

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.

Using jQuery to navigate between divs

I currently have a div which when clicked posts data to another page and reloads the div. I would like to add a back button (#backref) to the new div to take me back to the previous div. I have found several posts on this whereby you add display:none; to the div you want to browse to, but obviously this is my initial div so I cannot use that css. Any suggestions on how to get round this would be appreciated!
Code I am using to achieve this:
$(document).ready(function () {
$('.clickthrough2').click(function () {
// get car id
carId = $(this).attr('id'); // get the car id to access each class element under the car div container
$.post('referrer-ajax2.php', {
clickthrough: $('#car-'+carId+' .clickthrough').val(),
ref_date_from2: $('#car-'+carId+' .ref_date_from2').val(),
ref_date_to2: $('#car-'+carId+' .ref_date_to2').val()
},
function (data) {
$('#car1').html(data);
});
});
});
index.php:
<div id="car1" class="declined3 statdivhalf2">
<h4>Select Car</h4>
<div class="statgrid">
<?php
$result=$ mysqli->query($sql);
if($result->num_rows === 0) { echo 'No Cars in selected time period.'; }
else { while ($row = $result->fetch_array()) {
?>
<div id="car-<?php echo $row['car_id'];?>">
<input type="hidden" class="ref_date_from2" value="<?php echo $date_from; ?>" />
<input type="hidden" class="ref_date_to2" value="<?php echo $date_to; ?>" />
<input type="hidden" class="clickthrough" value="<?php echo $row['car_name'] ?>" />
<a><div id="<?php echo $row['car_id'];?>" class="clickthrough2 col-5-6"><?php echo $row['car_name'] ?></div></a>
</div>
<div class="col-1-6">
<?php echo $row[ 'quantity']; ?>
</div>
<?php } } ?>
</div>
</div>
referrer-ajax2.php:
<div id="car1" class="declined4 statdivhalf2">
<h4>Car Details</h4>
<div class="statgrid">
<?php
$result=$ mysqli->query($sql);
if($result->num_rows === 0) { echo 'No Cars in selected time period.'; }
else { while ($row = $result->fetch_array()) {
?>
<div id="clickthrough2" class="col-5-6"><?php echo $row['car_details'] ?></div>
<div class="col-1-6"><?php echo $row[ 'quantity']; ?></div>
<?php } } ?>
<a><div id="backref">< Back</div></a>
</div>
</div>
EDIT: I have tried the below be it did not work:
$('#backref').click(function () {
$('.declined4').hide();
$('.declined3').show();
});
Instead of reloading the div with the new content you could create a new div each time hiding the old one. You would then cycle through them by indexing each div with either an id or (probably better) a "data-" attribute.

Categories

Resources