I have a problem with my website. I have a list of products that i get from database. These products have Image and Name camps.
Now i want that, when i click to someone of this products, into my webpage appears a new box where there is the description of the product, the price etc..
This is the code for the products list
<?php
include 'php/dbmanager.php';
$result = DBManager::getInstance()->getProducts();
if($result->num_rows > 0){
$i = 0;
while($row = $result->fetch_assoc()){
echo "<div class=\"wrap effect8 open\" onclick>";
echo "<h1>".$row['product_name']."</h1>";
echo "<div class=\"left\">";
echo "<img src=".$row['product_image']." width=150 height=150 >";
echo "</div>";
echo "<div class=\"right\">";
echo $row['product_description'];
echo "<div class=\"prodSelection\">";
echo '<a href="catalogo.php?prodID=';
echo $row[product_id];
echo '"';
echo 'class="button">Acquista</a>';
echo '<label>';
echo '<select class="selectBoxCat">';
echo '<option selected> 1 </option>';
echo '<option>2</option>';
echo '<option>3</option>';
echo '</select>';
echo '</label>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
How can i get the ProductID ($row[product_id]) from a single product that i click and use it for a new query for select the database's rows of this single product (and use this query for make another php like that)?
I dont want to refresh the page.
Could i use the pushstate method (HTML5)?
If you want to get additional data when the user clicks, you will need to make an ajax request to update your DOM without refreshing the page.
On the PHP side, you'll want to create a script that returns a json-encoded value.
On the JS side, you'll want to create a click event listener. Inside the listener, you'll want to make an ajax request to your PHP script.
When your data is successfully returned from your ajax call, you'll want to manipulate your DOM to display your product's details.
Example of a click listener:
$("#button").on("click", function(){
// make your ajax request here
});
Example of an ajax call:
$.ajax({
method: "POST",
url: "scriptThatReturnsProductDetails.php",
data:
{
productID: $("#myProduct").attr('id')
}
})
.done(function( msg ) {
// Do some DOM manipulation
});
Related
I have a questions for which I need some help.
I have a page which, after it is finished loading, executes an AJAX, creates a table in PHP containing 2 buttons: 1 change password, the other is delete. Once the table is complete it is injected into a div in the main file. That works great so far. Now after that table is loaded, I want to be able to call another AJAX function linked in the JS file in the main page. So I have 3 components:
1. <div id="DbInfo"></div>
That is where I add the information from the users.
my php which executes the code and gets the information from my database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT LoginName FROM table";
$res = mysqli_query($conn, $sql);
if (mysqli_num_rows($res) > 0) {echo "<center>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>User</td>";
echo "<td colspan=2 align=center>Available Functions</td>";
echo "</tr>";
while($row = mysqli_fetch_assoc($res)) {
echo "<tr>";
echo "<td>" . $row['User'] . "</td>";
echo "<td><button type='button' class='smallbutton' id='removeUser' value='" . $row['LoginName'] . "'>Delete User</button></td>";
echo "<td><button type='button' class='smallbutton' id='CPW' value='" . $row['LoginName'] . "'>Change Password</button></td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
} else {
echo "";
}
mysqli_close($conn);
And lastly the AJAX which does the injection of the created table into the HTML:
$(document).ready(function(){
$.ajax({
method: "POST",
url: "UserData.php",
success: function(data){
//document.getElementById("DbInfo").innerHTML = data;
document.getElementById("DbInfo").html(data);
}
});
});
Again, these functions are working fine. What I want to do after the page is done, be able to click one of these injected buttons and execute another AJAX. Unfortunately the standard declaration that I use for AJAX does not work.
$(document).ready(function(){
$("#removeUser").click(function(){
The question: How can I make sure after the table is injected, that I can call an AJAX function which is linked as an external source (<script src="script.js"></script>) in the main document?
Thanks for your help.
try :
$('#DbInfo').on('click', 'button[id="removeUser"]', function(i,e){
console.log('remove :' + $(this).val());
});
I have a php function which displays all the data in my mysql table and allows the user to delete data not needed. I managed to get the data to show in a table, get the delete button to ask for confirmation using javascript, but when i try to get the value in the 2nd cell of the table with the query result (the name) and display it on the confirmation tab, it says undefined. Why is that happening? From what i understand, document.getElementById("myText").value where myText is the id of the cell, should return the value in the cell, correct? Also, how would i call and send that value to another php file that has the delete query?
<?php
$row = mysqli_fetch_array($result);
echo "<table>";
echo "<tr class='header'><td class='header'>Delete</td>";
echo "<td class='header'>Added</td>";
echo "<td class='header'>Name</td>";
echo "<td class='header'>Genre</td>";
echo "<td class='header'>Developer</td>";
echo "<td class='header'>Rating</td></tr>";
?>
<script type="text/javascript">
function ConfirmDelete(){
var name = document.getElementById("name").value;
if (confirm("Delete" +name+"?")){
//send the value and call the php
}
}
</script>
<?php
for ($x=0; $row; $x++) {
echo "<tr><td><input type='button' onclick='ConfirmDelete()' name='deleteGame' value='DELETE'></td><td>$row[Added]</td><td id='name'>$row[Name]</td><td>$row[Genre]</td><td>$row[Developer]</td><td align='right'>$row[Rating]</td></tr>";
$row = mysqli_fetch_array($result);
}
?>
</table>
Currently my dependent list is working on $_GET request. I'm trying to convert $_GET request to $_POST in Ajax without reloading the form. In the head I put #$cat=$_GET['cat']; I want this to be like $_POST and below ajax script is working on self.location which means its getting the value from $_GET url. I want the below script to work like $_POST and without reloading the form. Any help would very much appreciated.
my global declaration on the top as below
#$cat=$_GET['cat'];
my sql queries as below
<?php
# category and sub-category
$quer2="SELECT DISTINCT name,id FROM tblproductgroups order by name";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT sub_group_name,id FROM tblproductsubgroups where group_id=$cat order by sub_group_name";
}else{$quer="SELECT DISTINCT sub_group_name,id FROM tblproductsubgroups order by sub_group_name"; }
?>
my ajax script as below
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='product-add.php?cat=' + val ;
}
function disableselect()
{
<?Php
if(isset($cat) and strlen($cat) > 0){
echo "document.myForm.subcat.disabled = false;";}
else{echo "document.myForm.subcat.disabled = true;";}
?>
}
</script>
my dependent drop down list as below
<?php
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
$sql = mysqli_query($customCon, $quer2);
while ($row = mysqli_fetch_array($sql)) {
if($row['id']==#$cat){echo "<option selected value='$row[id]'>$row[name]</option>"."<BR>";}
else{echo "<option value='$row[id]'>$row[name]</option>";}
}
echo "</select>";
echo "<select name='subcat'><option value=''>Select one</option>";
$sql2 = mysqli_query($customCon, $quer);
while ($row2 = mysqli_fetch_array($sql2)) {
echo "<option value='$row2[id]'>$row2[sub_group_name]</option>";
}
echo "</select>";
?>
Use jQuery (see their site for installation instructions) and add a change event handler to your select item. Also add an container div to your HTML code that will hold your dynamically loaded content like:
<div id="myCatContainer"></div>
In the event handler do:
$('#myCatContainer').load('product-add.php?cat=' . $('#mySelect').val();
Be sure to read about jQuery and how to define an event handler, before you try the above code!
As the question suggest can you tell me how i can update mysql database using a dropdown menu with the help of ajax. I want to update my database with out reloading my whole webpage.When a user click edit button the selected option from the drop down list is updated. After searching a while i found some tutorials for this method and took ajax codes from there. But when i tried those in my database; it didn't worked out. Below is the sample code for my php script, parent file contains both ajax script and php code in a single php file called samefile.php. Below script only contains the problematic codes, some html and php codes are intentionally removed.
//THIS AJAX SCRIPT FETCHES VALUES FROM THE SELECTED DROPDOWN
<script>
function get_da(str){
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:$("#dropdown").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
}
);
</script>
///////////////////////////////FIRST BLOCK//////////////////
<?php
//THIS PHP SCRIPT GENERATES DROP DOWN VALUES FROM DATABASE
echo "<select name='dropdown' onChange='get_da(this.value)'>";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
/////////////////////////////SECOND BLOCK//////////////////////////////
//THIS PHP SCRIPT VALIDATES THE SELECTED DROPOWN VALUE AND PASS THOSE VALES FOR FURTHER PROCESSING.
if(isset($_REQUEST['dropdown1']))
{
$name=get_the_selected_dropdown_name; //i dont know how to fetch name from dropdown menu
$sql = "UPDATE table SET name = '$name' WHERE id =10";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
//////////////////////////////THIRD BLOCK////////////////////////////////////
?>
I believe this is how my above script works. when a user select a particular option from the drop down menu this function onChange='get_da(this.value)' sends the value (both id and name) to ajax query. in ajax query the drop down values are collected (both id and name) and renames as dropdown1 (data: { dropdown1:$("#dropdown").val()}) and pass it to php script inside the same file. Php script confirms the request from ajax using this if(isset($_REQUEST['dropdown1'])) and the script inside will be executed.
Please forgive me if i made a mess of my code. I suck at java script and ajax so am not sure whether my coding is right for those scripts. if possible can you suggest any other scripts for updating mysql database using ajax drop down list.
EDITED
ID DROPDOWN VALUE
1 ROY
2 TOM
3 CHASE
4 THOMAS
5 GEORGE
6 MICHAEL
have tried by printing the value you are sending in ajax request. You are passing this.value to your function get_da(str). But I think you are using it anywhere , In ajax post you are sending the value like
data: {dropdown1:$('#dropdown').val()}
But this will not post your selected vaule from dropdown, Try like this:
<script>
function get_da(this){
var id = $("#dropdown option:selected").val();
var selectedName = $("#dropdown option:selected").text();
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:id, name:selectedName}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
//drawVisualization();
},
});
}
</script>
Hope this will work.
Your dropdown script should be like this:
<?php
echo "<select name="dropdown" onchange="get_da()" id="dropdown">";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
This will send your selected value from drop down to your samefile.php.And also you are not doing good with your php script it should be like:
if(isset($_REQUEST['dropdown1']))
{
$id=$_REQUEST['dropdown1'];
$name=$_REQUEST['name'];
$sql = "UPDATE table SET name = '$name' WHERE id ='$id'";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
?>
How can I collect the data on the row from the table that I select and use it in the result?
Here is the javascript I am using to show the data entry screen, once the function has been called by selecting the row. Now I just need to design a form in PHP that will include (1) some of the data from the row selected and (2) some new data that will be collected.
Here is the Javascript to select the row and call the data entry form
$(document).ready(function () {
$("tr").live('click',function(){
$.post('data_entry_form.php', function(data) {
$('#section2').html(data);
});
});
});
Here is the PHP Script
<?php
require_once "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$result = $dbh->query("SELECT aif_id, fee_source_id, company_name_per_sedar, document_filing_date FROM a_aif ORDER BY aif_id DESC");
$result->setFetchMode(PDO::FETCH_ASSOC);
echo "<table id=\"all_aifs\">";
echo "<tr>";
echo "<th><b>Document ID</b></th>";
echo "<th><b>Pubco Name</b></th>";
echo "<th><b>Filing Date</b></th>";
echo "<th><b>PDF</b></th>";
echo "</tr>";
foreach($result as $index => $row) {
echo "<tr>";
echo "<td>$row[fee_source_id]</td>";
echo "<td>$row[company_name_per_sedar]</td>";
echo "<td>$row[document_filing_date]</td>";
echo "<td>Placeholder</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
$dbh = NULL;
?>
The "Correct" answer to this problem is NOT to read from the DOM. Never a good idea. I suggest you pass the record id to the ajax call and have the ajax call return an already-populated form.
//PHP
//place the data attribute in the tr
echo "<tr data-recordId='".$row['id']."'>";
//JS
$(document).ready(function () {
$("tr").live('click',function(){
//Get the ID from the row clicked
var id = $(this).data('recordId');
//short-hand
$('#section2').load('data_entry_form.php?id='+id);
});
});
Then your ajax page would just read $_REQUEST['id'] to get the id of the form being edited.
//Ajax side PHP
$id = (int)$_REQUEST['id'];
//Fetch data and use it to pre-populate form item
You would pre-populate your inputs like this
<input type="text" value="<?php echo $row['value']; ?>" />
or
echo '<input type="text" value="'.$row['value'].'" />';
NOTE: If your values contain quotes, you will want to replace them with the code "
echo '<input type="text" value="'.str_replace('"', '"', $row['value']).'" />';
Within the event handler, this and $(this) refer to your selected row:
$("tr").live('click',function(){
// this.cells[1] is the cell that contains Pubco Name
// You can also use $(this).children("td")[1]
...
});