I use php code to create one shopping cart. When I click in product page, Since the database have more products that use php code to create product page.
Now, I can ten product in one page. But I need a select box to change product quantity in one page. How can I do for it?
This is my code.
Select Box code.
$content .= "<span style=\"margin-left:50px;color:#BE1E2D;font-size:14px;font-weight:bold;\">show
<select name=\"show_num_select\">
<option value=\"10\">10</option>
<option value=\"20\">20</option>
<option value=\"30\">30</option>
<option value=\"50\">50</option>
<option value=\"100\">100</option>
</select>
item each page</span>";
Read select box value.
$show_num_select = isset($_GET['show_num_select'])?$_GET['show_num_select']:"10";
Create product page. n is product type. Product::count_all is a function.
if(empty($_GET['n'])){
$page = !empty($_GET['page'])? (int)$_GET['page']:1;
$per_page = $show_num_select;
$total_count = Product::count_all(true);
if(empty($_GET['page']) || (int)$_GET['page'] > ceil($total_count / $per_page) ){
$page = 1;
}
Keep a count of current items shown and use it to improve the fetch by querying only for items apart from the ones already rendered. Using ajax fetch the next set of items and render that section. Just a suggestion to avoid fetching all items.
Avoiding page refresh will be good from users point of view.
I don't see where you read the data from the database or another data source. If you use an SQL related data source, use something like:
SELECT id, product_title FROM product LIMIT :start,:end
Where ":start" is the current page number (times) $per_page and ":end" is just $per_page.
Related
In my html page, I want to autofill textboxes with informations(common Name, location,..) of the selected object (shop) from the dropdown list without refreshing the page.
this is the dropdown list:
<select id="shops" class="form-control">
<option value="">Choisir</option>
<option th:each="shop : ${shops}" th:value="${shop.uuid}" th:utext="${shop.uuid}" onClick = "autofillValues()"/>
</select>
and this is the script:
function autofillValues()){
document.getElementById('commonName').value = $('#shop').find(":selected").val().siret;
}
I tried several codes for 2 weeks and I can't find the solution yet.
As mentioned by Vincent, the data would need to be held somewhere on the frontend. This could simply be an array within your code or be pulled from a backend endpoint via an API request.
If you, for example, had an array like this:
[
{
uuid:"49c03f73-c0c5-4bc6-bde4-4a01f66f86c1",
commonName:'Shop 1',
location:'New York, NY, US'
},
{
uuid:"1cb2eeb7-6618-4a7a-8334-72cb0c90bf2a",
commonName:'Shop 2',
location:'Toronto, ON, CA'
}
]
Inside your autofillValues function, you can filter the array (lets assume it's called shopList) by id and populate your elements.
<select id="shops" class="form-control" onchange="autofillValues(value)">
<option value="">Choisir</option>
<option th:each="shop : ${shops}" th:value="${shop.uuid}" th:utext="${shop.uuid}" />
</select>
function autofillValues(id){
let shop = shopList.find(f => f.uuid == id);
if(shop !== null) {
document.getElementById('commonName').value = shop.commonName;
}
}
I replaced the onclick attr on the options with an onchange attr on the select for simplicity
This is a very basic implementation, but here's it working on JSFiddle
You need to store he values somewhere in the front end in order to not to a contact the server. Lets assume that you store them in an array : shops
The when you call the autofillValues function when you select a option from the drop down.
in this function, you wind the appropriate value from the array and then populate the items.
If you are only concerned about the refresh, the you can do an ajax call and return the item that way
This is probably very simple, but am learning PHP, Javascript as I go. I find it easier to learn using real examples than the contrived examples given online.
I am creating an attendance register page, based on selecting a class, then all members of that class ordered by Surname and Firstname.
The table row has it's id set, by PHP, as the record's mem_id, and contains just forename+" "+surname, and some checkboxes.
All this is working fine, but now I have been asked to add a link so that clicking on it brings up a modal containing related data for the person selected. The extra data is already in the $a_fetch array.
Have added a glyphicon link for every row and clicking it displays a modal alright, and by having a javascript function I know I can get the row index and row id
<tbody>
<?php
while($g_fetch = $a_query->fetch_array()) {
$checked = array();
$memid = $g_fetch['mem_id'];
$name = $g_fetch['firstname'].' '.$g_fetch['lastname'];
$attendences = explode(",",$g_fetch['attend']);
for ($x = 0; $x <= 12; $x++) {
if ($attendences[$x]!="0") {
$checked[$x] = 'checked = "checked"';
}
else $checked[$x] = '';
}
echo "<tr id='".$memid."'>";
echo "<td>".$name."</td>";
echo "<td align='center'><div id='".$memid."' class='glyphicon glyphicon-info-sign' onclick='getId(this.id)' style='cursor:pointer' data-toggle='modal' data-target='#ModalCentre'></div>";
for ($y = 0; $y <= 12; $y++) {
echo '<td align="center"><input type="checkbox" value = "" '.$checked[$y].'></td>';
}
}
unset($checked);
unset($attendences);
?>
</tbody>
</table>
I am at a loss as how to proceed - is it even possible to pass data to the modal to display related data?
If it is would I need to run a new query (SELECT), or as the row is the same index as the data in the $A_fetch, and the row id has the correct mem_id is it possible to get the data from the existing $a_fetch array using either of those, or would I need to run a new SELECT?
Many thanks
There are multiple ways to provide data to the modal - and (in my opinion) it depends on how much data you need to pass to your modal and how many rows you have.
I want to describe you two ways:
Light+Easier Solution
If you don't want to display a lot of data and you have just a few rows.
The idea is to add the data directly to each div.glyphicon (as data attributes) and then use it in the modal
In your foreach add it to your model like that:
<div id='".$memid."' class='glyphicon glyphicon-info-sign' onclick='getId(this.id)' style='cursor:pointer' data-toggle='modal' data-target='#ModalCentre' data-link='".$g_fetch['additional_link'] ."' data-moreInfo='".$g_fetch['moreInfo']."'></div>
You haven't posted the modal's HTML or your JS code, but you wrote you are using bootstrap, so stick to
https://getbootstrap.com/docs/4.0/components/modal/#varying-modal-content
and fetch/set the relevant data (related clicked glyphicon) as it's described.
More complex solution
For more data / more rows. The additional data is not provided in the inital loaded HTML page - Therefore not all data needs to be loaded in the beginning.
Instead the additional data is loaded via ajax when clicking on one row.
For that you need to provide an additional endpoint (php) which provides the modal content for one row.
Check out second answer in Bootstrap 3 - How to load content in modal body via AJAX?
Basically you have a php file (e.g. getAdditionalData.php)
In this file you access the mem_id via GET
$mem_id = $_GET['mem_id'];
fetch the additional data from database
and print/render out the modal content (full html like in the second answer)
And in JS (inital page) you load the modal content onClick (fetched from php with provided mem_id as parameter)
var clicked = $(e.relatedTarget);
$(this).find(".modal-body").load("%PATH%/getAdditionalData.php?mem_id="+clicked.attr("id"));
I hope it will help you solving your problem and if you need additional infos just let me know. There are more ways to archive your goal but I think this 2 possibilities are enough in the beginning :-)
I am looking for a way to create a drop down list depending on what the user chooses. If the user picks the package of one profile the the output will give the user a drop down list with 1 field if the user chooses two profiles the output will give the user a drop down with 2 fields. The code recently displays just one dropdown even if the user chooses the second option
<ul class="dropdown-menu <?= empty($business) ? 'hidden' : '' ?>" aria-labelledby="business_list">
<?php foreach ($business as $key => $item) : ?>
<li><?= Html::a($item->name, ['social-manager/profiles', 'b' => $key]) ?></li>
<?php endforeach; ?>
</ul>
I will assume you are using jQuery.You will need to define an number variable var length based on user selection. If user selects option 1 then var length=1,if user selects option 2 then var length=2;
Th for loop below should generate the options based on user selection.
for(var x=0;x<length;x++){
.....
}
The best way to do something like this is by creating API endpoint using PHP that will provide the dropdown value and then using ajax to fetch the result and repopulate the dropdown.
The flow would be like;
User select the profile, each time they do trigger a jquery function that will send an ajax to PHP API endpoint with the selected profile(s).
On the API endpoint, check how many profile is selected, return dropdown field value(s) accordingly.
Based on the return value, repopulate the dropdown value using jquery.
i was trying to make a dynamic where the selected option was supposed to be caught in a variable for php as i would use it as a condition to be put in a where clause for mysql. and when a user selects another option the of another tag would change
<form method="GET" action="">
<select name="docSpec" id="docSpec">
<?php
$docSpecQuery = "select DISTINCT specialty from doctors"; // i was going to put a where condition here so i could only project names of the doctor with the selected specialty.
$docquery = "select doctorName from doctors";
$docSpec = mysqli_query($conn,$docSpecQuery);
$docresult = mysqli_query($conn,$docquery);
//this php block is for my options, i used a loop
while ($row = mysqli_fetch_row($docSpec))
{
echo "<option value='$row[0]'>$row[0]</option>";
}
unset($row);
?>
</select>
<script type="text/javascript">
$('#docSpec').on("change",function(){
var option = $("option:selected",this).val();
alert(option);
});
</script>
</form>
i hope i was clear enough i will be waiting if you want to clarify some things in my code.
tell me if you need another parts of my code. please i need help
PHP is executed on the server, which means that by the time you print the <select> you run the jQuery code you can't affect the mysql query directly. You can however move the query to another script, and target it with an ajax call that returns the select and options or, ideally, the dataset so you can create it programmatically.
Your php script will do the same as it does right now but fetch the value from the url for the conditional query. For instance, you could have this php at mysite.com/select.php and pass the variable gynecologist like so mysite.com/select.php?spec=gynecologist then read it with $_GET['spec'] and use it in the query.
In your javascript, you'll get that html by calling something like:
$('#docSpec').on("change",function(){
$.get( "mysite.com/select.php?spec="+$(this).find("option:selected"),
function( data ) {
//data contains the output for the php file, update the dom
//with it or whatever
});
});
I have a MySQL database that contains, amongst other things, 2 tables. One is the events table, containing event names and other details. The other is the instance table. This table links the events table to a venue table and adds a date, so each row is an instance of the linked event.
I am making an event booking form for internal use for these events. I want to allow selection of the event to be booked via a dropdown list. So, I have populated one dropdown with the event names:
$qEvent = "SELECT event_name, event_id FROM events";
$rEvent = mysqli_query($dbc,$qEvent);
echo '<select>';
while ($row = mysqli_fetch_assoc($rEvent)) {
echo '<option value="'.$row['event_id'].'">'.$row['event_name'].'</option>';
}
echo '</select>';
What I now want to do is, for the selected event, grab all the instances associated with that event, and populate another dropdown with the dates.
Can I do this with PHP, or do I need to dip into Javascript? I think I just need some way to grab the event_id value of the dropdown selection and then query based on that, but I don't know how without Javascript.
You should be looking at Javascript or jQuery for achieving your goal. I've used jQuery based on my question to you earlier. It's also simpler and less code.
Your PHP:
Add an ID attribute event_menu to your select menu
echo '<select id="event_menu">';
while ($row = mysqli_fetch_assoc($rEvent)) {
echo '<option value="'.$row['event_id'].'">'.$row['event_name'].'</option>';
}
echo '</select>';
<div id="container_for_new_menu"></div>
Using jQuery:
$('#event_menu').on('change', function() {
// get selected value and build data string for AJAX
var event_selected = "event_selected="+$(this).val();
// send the selected data to a PHP page to build the populated menu
$.ajax({
url : 'populate-menu.php',
type: 'POST',
data : event_selected,
dataType : 'html',
success : function(data) {
$('#container_for_new_menu').html(data);
}, error : function() {
alert("Something went wrong!");
}
});
});
On populate-menu.php, have something like:
$event_selected = isset($_POST['event_selected']) ? $_POST['event_selected'] : null;
// do SQL query here based on user's selection
// making sure you validate the data in the POST request for malicious BS
// or use parameterized queries
// then build a new menu to send back
echo '<select>';
// loop through results and build options
echo '</select>';
This new menu will then be posted back to your original page into the container_for_new_menu element.
By the looks of it, you want to populate the "instances" dropdown based on the selection the user makes on the "event" dropdown. You cannot do this without Javascript.
My suggested way of doing this is to use AJAX to pull the instance data and populate the "instances" dropdown on change of the "event" dropdown. Useful resources below for simple AJAX get with jQuery:
http://api.jquery.com/jQuery.get/
http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/
You need some kind of Javascript to accomplish this. Either:
Basic- submit the form on select and let php populate the instance drop-down.
More elegant- use Javascript to make an Ajax call on select which will dynamically replace the instance drop-down's div.
You will need JavaScript to populate the second drop down box. I suggest you load all the values into JSON on the page and then you can just use a jQuery on change event to populate the second select box.