Changing PHP function to Javascript/AJAX validation - javascript

I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>

Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.

Related

How to fetch questions ony by one on save and next buttons

I have a quiz management system and need to fetch the data from the database and displaying the data one by one on clicking next button.
I want to use ajax to insert data into database after clicking next button by using file read and write function.
$sql=mysqli_query($con,"SELECT * FROM tbl_question WHERE setid='$set' AND status=1 ORDER BY RAND()");
while($sha=mysqli_fetch_array($sql)) {
<h4><? echo $sha['id'];?></h4>
here's simple way to do it
first get question from database then put a button to the next id
<?php
$rows = 0;
$id = isset($_GET['id'] ? (int) $_GET['id'] : 0;
$query = 'SELECT * FROM `tbl_question` WHERE `tbl_question`.`status` = 1 AND `tbl_question`.`id` = ? LIMIT 1';
$mysqli = new mysqli('localhost','user','password','database');
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->bind_result($id,$something,$something_else,$status);
while($stmt->fetch())
$rows++;
$stmt->close();
$mysqli->close();
if($rows === 0) {
echo 'qustion not found';
} else {
// output qustion
// button
echo '<a type="buttton" href="?id=' . $id + 1 . '">next</a>';
}

Load data in template page

I am creating a website in which I need to sell products. I am stuck at the product page of the website.
The big e-commerce website like amazon.com must have a template of the product page and they dynamically load all the data including image of product, price, reviews from the database. I also want to create a similar product page where on clicking a link of product, it automatically loads all the images, price and info stored in the database and show it.
If another product is clicked, everything loads on that very same html/php template page and I don't have to make different page for different products. How can I do that?
I have been searching for a solution to this for many days, but I don't know what exactly to search for to get the answer.
Create a php page, say, load_products.php and pass get parameters like load_products.php?product_id=1.
Change the id (as per the database setup) and get the corresponding product details from database.
Edit : Detailed Answer
Database
Table: table_products
+--------------------------+---
| id | name | details | ...
+--------------------------+---
| 1 | Product1 | Details1 | ...
| 2 | Product2 | Details2 | ...
...
+--------------------------+---
I shall show you how it is done with MySQL database.
PHP Code
load_products.php
// Establish connection to database
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('products_database_name');
// Display All the Products
$res=mysql_query("SELECT * FROM table_products");
echo "<table>";
while($row=mysql_fetch_array($res))
{
$id=$row["id"];
$name=$row["name"];
echo "<a href='load_products?id=$id'>$name</a>";
}
// Display the details of a particular product based on the input click from user
if(isset($_GET["id"]))
{
$id=$_GET["id"];
$res=mysql_query("SELECT * FROM table_products WHERE id=$id");
echo "<table>";
while($row=mysql_fetch_array($res))
{
$details=$row["details"];
$name=$row["name"];
echo "<tr><td>$name</td><td>$details</td></tr>";
}
echo "</table>";
}
A really bare bones implementation, yet fully working and you can see the output on your localhost in 15 minutes. You can build on top of this.
You can search for : Loading images from database, javascript, jquery to enhance the website interface, using ajax on top of this and so on..
Please find the Improved version
products.php page
// Establish connection to database
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('products_database_name');
// Display All the Products
$res=mysql_query("SELECT * FROM table_products");
$productsPerRow = 4;
$columnWidth = (int)(100 / $productsPerRow);
$count = 0; //count product displayed
echo "<table>
<tr>";
while($row=mysql_fetch_array($res))
{
$count++;
$id = $row["id"];
$name = $row["name"];
$image = $row["image"]; //image name with extension, upload it in the images folder
echo "<td width='" . $columnWidth ."' >
<img src='images/" . $image ."' border='0'/><br />
<a href='load_product.php?id=$id'>$name</a>
</td>";
if($count%$productsPerRow==0)
echo"</tr><tr>";
}
//close empty cells
if ($count % $productsPerRow > 0) {
echo "<td colspan='" . ($productsPerRow - ($count % $productsPerRow)) .
"'> </td></tr>";
}
//close table
echo "</table>";
load_product.php page
// Establish connection to database
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('products_database_name');
// Display the details of a particular product based on the input click from user
if(isset($_GET["id"]))
{
$id=$_GET["id"];
$res=mysql_query("SELECT * FROM table_products WHERE id=$id");
echo "<table>";
while($row=mysql_fetch_array($res))
{
$details=$row["details"];
$name=$row["name"];
echo "<tr><td>$name</td><td>$details</td></tr>";
}
echo "</table>";
}

Get the value of the click number in order to update the clicked data

we have a form that we can click on a number at the top of the form in order to load the according data, to be more specific i can have 4 inputs in my table in the database and when I click on number 2 which is the id of the data then it loads the data. We did that but now we want to update the clicked data and until now we cant find a way to GET the correct number(id) and place it in the UPDATE statement.
Below is the code of the clicked functions and of the UPDATE statement.
//Education Scripts
$("#updateEdu").click(function () {
$("#idE").css("display", "none");
var r = parseInt($("#idE").val(), 10) + 1;
$("#idE").val(r);
});
$('[data-row-ide]').click(function (e) {
e.preventDefault();
var fileName = 'addCV.php?idEdu='; //"addCV.php" the name of this file in your project, the "?" starts the GET parameters, idWork= sets the key for the GET parameter
var id = $(this).data('row-ide'); // this gets the id that we stored in the link's data attribute
var url = fileName + id; // then we add that id as the value for the "idWork" key
window.location = url; // esentially refresh this page with the id set as a GET parameter and make use of the logic we already have to load the info
});
<?php
$username = $_SESSION["username"];
if(isset($_POST['updateEdu'])){
$parts = parse_url($url);
parse_str($parts['query'], $query);
$id = $query['idEdu'];
$username = $_SESSION['username'];
$school = mysql_real_escape_string($_POST["school"]);
$degree = mysql_real_escape_string($_POST["degree"]);
$website = mysql_real_escape_string($_POST["website"]);
$start_date = mysql_real_escape_string($_POST["start_date"]);
$end_date = mysql_real_escape_string($_POST["end_date"]);
$start_year = mysql_real_escape_string($_POST["start_year"]);
$end_year = mysql_real_escape_string($_POST["end_year"]);
$degree_description = mysql_real_escape_string($_POST["degree_description"]);
if($start_year > $end_year){
echo 'The Start Year must be smaller than the End Year!';
$id=$id-1;
$good = false;
}
else{
$good = true;
}
if($good == true){
$query="UPDATE education
SET school = '$school', degree = '$degree', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', degree_description='$degree_description'
WHERE id='$id' AND username='$username'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>0){
echo "<p>Record Updated<p>";
echo "<script type='text/javascript'>;
/window.location='addCV.php';
</script>";
}
else{
echo "<p>Error Updating Record<p>";
echo "<script type='text/javascript'>;
</script>";
}
}
}
else if(isset($_GET['idEdu'])){
// user clicked on one of oue id links to get here
// set the id the the value of the GET parameter for key "idWork"
$id = $_GET['idEdu'];
}
else{
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT school,degree,website,start_date,end_date,start_year,end_year,degree_description,id FROM education
WHERE username='%s' ORDER BY id LIMIT 1",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
}
}
To get the value of an elements attribute in jquery you use the attr() function like so:
$(element).attr('attributeName')
So you should change:
var id = $(this).data('row-ide');
into
var id = $(this).attr('row-ide');
in your function $('[data-row-ide]').click(function (e) {};

Pass PHP variable to ajax and run PHP function based on that variable

I have Database records which are loop echoes out, so it lists down in Divs each records info.
I'm trying to make a delete button, to delete the specific record from this page view. The loop number tracker variable $i also corresponds to the record ID, so loop 3 outputs a div containing the info of record ID 3.
So I just need to on click pass $i to a PHP function to then run the sql to drop the record with ID $i.
I'd like to do this all on the same page so I'm assuming I need ajax but thats where I get stumped. Also so I can have an alert "Are you sure" I've done ajax with jquery to ajax to php, but never this way.
PHP:
$webserver = 'localhost';
$administrator = 'root';
$password = '';
$db_name = 'cdb';
$db = mysqli_connect($webserver, $administrator, $password, $db_name)
or die('Error connecting');
if( isset($_REQUEST['page']))
{
$_SESSION['page'] = $_REQUEST['page'];
}
else
{
$_SESSION['page'] = 1;
}
$records_per_page = 8;
$query = " SELECT *
FROM cars, users
WHERE cars.dealerID = users.dealerID
AND users.username = '".$_GET['username']."'";
$result = mysqli_query($db, $query)
or die("Error in query: '$query'");
$row = mysqli_fetch_assoc($result);
$i = 1;
$start = ($_SESSION['page'] - 1) * $records_per_page;
$end = ($_SESSION['page']) * $records_per_page;
while($row = mysqli_fetch_assoc($result) and $i < $end)
{
$i++;
if( $i > $start )
{
<div>
delete
</div>
<div of magic n' fairies>
echo $row['informationandstuff'];
</div>
}
}
Delete function:
function deleteCar()
{
$delete = "DELETE FROM cars
WHERE carindex = '".$i"'";
}
I could post $i to another file and do it bt would prefer to keep to same page and allow for an are you sure js pop up.
If I'm understanding you correctly, one way to do this would be to store the $i variable in either an html data attribute, or an id (as you suggested). Then, use jquery to collect that id and pass it to the data property in the ajax call.
Sample list item (I'm assuming a heredoc here):
<div class="list-item" data-record-id="{$yourId}">your output</div>
Now, collect the id that the user clicked:
$('.list-item').click(function(){
//get item id
var recordId = $(this).data('record-id');
deleteRecord(recordId);
});
function deleteRecord(recordId) {
var recordData = 'recordId=' + recordId;
var request = $.ajax({
type: "post",
url: "the-php-page-you-use-for-async-calls",
data: recordData,
success: function(resp){
//show some validation that the record has been deleted
}
});
}

Two questions about possible mysql and php functionalities (maybe javascript?), and where I should look to learn more

First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>

Categories