Using passed variable from jquery to php dynamically update fields - javascript

I have a bunch locker numbers in a drop down list (populated from MYSQL/PHP). I want to display the locker's combination and location when you select a locker number from the list in two input fields below on the same page.
I have used jquery to tell me which item in the list is selected dynamically. Then I used the $.ajax() function to send that item to my server.
My problem: Can I use $.ajax() to send my variable to the same page I am on? I have tried this and I get an error. I am not sure how to accomplish this. My knowledge of AJAX is very minimal.
My code is as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Locker Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="form.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function show()
{
$('#addlocker').toggle();
}
function lockerSelected(sel)
{
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(){
alert(selected);
}
});
}
</script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<?php
$url = $_SERVER['REQUEST_URI'];
$studID = substr($url, strpos($url, "=") + 1);
$db_handle = mysql_connect("localhost", "root", "pickles") or die("Error connecting to database: ".mysql_error());
mysql_select_db("lockers",$db_handle) or die(mysql_error());
$result = mysql_query("SELECT * FROM students WHERE studID = $studID");
?>
<div class="container">
<header> <img src="images/headmast.png" alt="Insert Logo Here" width="686" height="180" id="Insert_logo" /> </header>
<div id="data1">
<form id ="studData" name="studData" action="update.php" medthod="post">
<fieldset>
<legend>Student Details</legend>
<?php
while($row = mysql_fetch_array($result))
{
echo '<ol>';
echo '<li>';
echo '<label for=studid>Student ID</label>';
echo '<input id=studid name=studid type=text value='.$row['studID'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>First Name</label>';
echo '<input id=fname name=fname type=text value='.$row['firstName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>Last Name</label>';
echo '<input id=lname name=lname type=text value='.$row['lastName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=email>Email</label>';
echo '<input id=email name=email type=text value='.$row['email'].'>';
echo '</il>';
echo '<li>';
echo '<label for=progam>Program</label>';
echo '<input id=progam name=progam type=text value='.$row['program'].'>';
echo '</il>';
echo '</ol>';
$program = $row['program']; //get name of program
}
?>
<input type="submit" value="Update" class="fButton"/>
</fieldset>
</form>
<form id="locker" name="locker" action="" method="post" >
<fieldset>
<input type="button" onclick="show()" value="Add Locker"/>
<div id="addlocker" style="display:none;">
<!--
query lockers where $program = program parsed in & student id is equal to 0 (this makes it available)
get select list to 10
populate select list --> <br/>
<legend>Lockers Available: </legend>
<select size="10" name="lockerSelect" multiple="yes" style="width:200px;" onChange="lockerSelected(this);">
<?php
$result1=mysql_query("SELECT * FROM lockers WHERE progName = '$program' && studID = 0") or die($result1."<br/><br/>".mysql_error());
while($row1 = mysql_fetch_array($result1))
{
echo '<option value=\"'.$row1['lockerScan'].'">'.$row1['lockerNo'].'</option>';
}
echo '</select>';
echo '<br>';
$lockerNo = $_POST['selected']; \\doesn't work - displays error
echo $lockerNo; \\errors out
?>
</div><!--end of add locker section-->
</fieldset>
</form>
</div><!--end of data1 -->
Search
</div><!-- end of container-->
</body>
</html>

Firstly, you can use :
function show()
{
$('#addlocker').toggle();
}
Then, you should learn more about Ajax and PHP. Your call shoud be :
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: {selected: selected},
success: function(data){
alert(data);
}
});
And in your PHP file :
<?php
$select = $_POST['selected'];
//....
// Do what you have to do then return your result
echo '<div>Send to your page !</div>';

First Arrange your files.
js's is in js folder
php's in php folder
best way is to assaign a seperate php page and then in js use on change event
$(document).on("change", "#selectfieldid", function(){
var selected = $('#selectfieldid').val();
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(data){
$('#addlocker').val(data); //echoed result placed here that has id addlocker
}
});
});
send those to a php page echo the result in that php.

Related

Locate the reasoning for NULL values between HTML and PHP

I am trying to figure out why the resulting values are...
NULL NULL string(4) "PEAR"
..on the page they are displayed on.
Originally I do not want them to be displayed but I want the php code to run, using local storage data, when the page loads, then possibly return a boolean value or something in that direction. With a set goal in mind, I am looking for the mistake I have made that creates the NULL values. I have the following code:
validateSession.php , php functionality that will validate values from localstorage and database
<?php
include("config.php");
include("refc/refcvalidation.php");
$sesuserid = $_POST[$valuserid];
$sessionid = $_POST[$valsesid];
var_dump($sesuserid, $sessionid);
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$stmt = $conn->prepare("SELECT * FROM sessiontable WHERE sesowner=? AND sescode=?");
$stmt->bind_param("is", $sesuserid, $sessionid);
$stmt->execute();
$result = $stmt->get_result();
$conn->close();
if ($result->num_rows > 0) {
var_dump("APPLES");
}else{
var_dump("PEAR");
}
?>
refcvalidation.php , reference coordination, ensuring same value on both pages
<?php
$valuserid = "VALSES1";
$valsesid = "VALSES2";
?>
homepage.php , basic page with contents
<?php
include("services/refc/refcvalidation.php");
include('services/validateSession.php');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="general/styling.css">
<script src="general/launch.js"></script>
</head>
<body>
<div id="topBox">
</div>
<div class="box">
<form id="logForm" action="validateSession.php" method="post">
<input type="hidden" required="required" name="<?php echo $valuserid ?>" id="userfield">
<input type="hidden" required="required" name="<?php echo $valsesid ?>" id="sesidfield">
</form>
</div>
</body>
<style>
</style>
</html>
<script>
document.getElementById("userfield").value = localStorage.getItem("userid");
document.getElementById("sesidfield").value = localStorage.getItem("sessionid");
</script>
The values within HTML are set and have a value in the script section, they are null within the PHP $_POST[$valuserid]; and $_POST[$valsesid]; . Any ideas?
Have'nt tested this, but it might give you some ideas to a solution.
Maybe we could impolement some Ajax into this?
What is Ajax?
AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Ajax can give data as response.
refcvalidation.php
This should be removed
validateSession.php
<?php
include("config.php");
//include("refc/refcvalidation.php"); //REMOVED
$sesuserid = $_POST['valuserid'];
$sessionid = $_POST['valsesid'];
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$stmt = $conn->prepare("SELECT * FROM sessiontable WHERE sesowner=? AND sescode=?");
$stmt->bind_param("is", $sesuserid, $sessionid);
$stmt->execute();
$result = $stmt->get_result();
$conn->close();
if ($result->num_rows > 0) {
$myObj->sesuserid = $sesuserid;
$myObj->sessionid = $sessionid;
$myJSON = json_encode($myObj);
echo $myJSON;
return true; //CONTAINS SOMETHING
}else{
return false; //CONTAINS NOTHING
}
?>
homepage.php
<?php
include("services/refc/refcvalidation.php");
include('services/validateSession.php');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="general/styling.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="general/launch.js"></script>
</head>
<body>
<div id="topBox">
</div>
<div class="box">
<form id="logForm" action="validateSession.php" method="post">
<input type="hidden" required="required" name="<?php echo $valuserid ?>" id="userfield">
<input type="hidden" required="required" name="<?php echo $valsesid ?>" id="sesidfield">
</form>
</div>
</body>
<style>
</style>
</html>
<script>
$.ajax({
url: 'validateSession.php',
method: 'POST',
data: { valuserid: '<?php echo $valsesid ?>', valsesid: '<?php echo $valsesid ?>'},
success: function(data) {
var data_json= JSON.parse(data);
console.log(data_sjon);
localStorage.userid = data_json[0];
localStorage.sesidfield = data_json[1];
document.getElementById("userfield").value = localStorage.getItem("userid");
document.getElementById("sesidfield").value = localStorage.getItem("sessionid");
}
})
</script>

How to update quantity of database from php action

I am building a database of different devices which is displayed in a page which sells medical devices. When a user adds a quantity of the device to the cart, I want the database to be updated with (stock - quantity in cart) I am trying to do this on PHP but am having no luck. My attempt and code is below.
Here is a snippet of my attempt. I'm not sure where to place this in the code below.
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
if(isset($_POST['incqty'])){
$value += 1;
$query = "UPDATE products SET stock= (stock-$product_qty) WHERE product_name=$product_name";
mysql_select_db('products');
$retval = mysql_query($query,$mysqli);
}
?>
This is code for index.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 align="center">Products </h1>
<!-- View Cart Box Start -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<div class="cart-view-table-front" id="view-cart">';
echo '<h3>Your Shopping Cart</h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="100%" cellpadding="6" cellspacing="0">';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /> Remove</td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>Checkout';
echo '</td>';
echo '</tbody>';
echo '</table>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<!-- View Cart Box End -->
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price, stock FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content"><h3>{$obj->product_name}</h3>
<div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
Price {$currency}{$obj->price}
<fieldset>
<label>
<span>Color</span>
<select name="product_color">
<option value="Black">Black</option>
<option value="Silver">Silver</option>
</select>
</label>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button type="submit" id="updateb" class="add_to_cart">Add</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
<!-- Products List End -->
</body>
</html>
This is code for cart_update.php
<?php
session_start();
include_once("config.php");
//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
foreach($_POST as $key => $value){ //add all post vars to new_product array
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
}
//remove unecessary vars
unset($new_product['type']);
unset($new_product['return_url']);
//we need to get product name and price from database.
$statement = $mysqli->prepare("SELECT product_name, price, stock FROM products WHERE product_code=? LIMIT 1");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $price, $stock);
while($statement->fetch()){
//fetch product name, price from db and add to new_product array
$new_product["product_name"] = $product_name;
$new_product["product_price"] = $price;
$new_product["product_stock"] = $stock;
if(isset($_SESSION["cart_products"])){ //if session var already exist
if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
}
}
$_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item
}
}
//update or remove items
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
//update item quantity in product session
if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
foreach($_POST["product_qty"] as $key => $value){
if(is_numeric($value)){
$_SESSION["cart_products"][$key]["product_qty"] = $value; //change
}
}
}
//remove an item from product session
if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
foreach($_POST["remove_code"] as $key){
unset($_SESSION["cart_products"][$key]);
}
}
}
//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
header('Location:'.$return_url);
?>
This is code for view_cart.php
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<h1 align="center">View Cart</h1>
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%" cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION["cart_products"])) //check session var
{
$total = 0; //set initial total value
$b = 0; //var for zebra stripe table
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$subtotal = ($product_price * $product_qty); //calculate Price x Qty
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$currency.$product_price.'</td>';
echo '<td>'.$currency.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}
$grand_total = $total + $shipping_cost; //grand total including shipping cost
foreach($taxes as $key => $value){ //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount; //add tax val to grand total
}
$list_tax = '';
foreach($tax_item as $key => $value){ //List all taxes
$list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
}
$shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
}
?>
<tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
<tr><td colspan="5">Add More Items<button type="submit">Update</button></td></tr>
</tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>
</body>
</html>
your variables $product_qty and $product_name are not defined and in the query pass the product name in the quotes as your query is in double quotes so pass name in the single quotes.
Also it will be better if you update using primary id not by name.

Populate multiple form fields from foreach statement

I'm trying to populate multiple form fields from a generated button in a foreach statement. I don't have a vast knowledge of JS so I don't know if I'm just not thinking of a certain function or not.
I have the following code and I'm able to get title to populate in the form but I have no clue where to start for populating content as well based of the same button. ex: one button will load a specific title and content value while another edit button will load another specific title and content value.
//Announcement table select
$sql = "SELECT * FROM `announcements` ORDER BY `startDate` DESC"; //I want to see all existing announcements from database
$announcement = $dbConnect->query($sql);//execute query
$a = 0;
?>
<script type="text/javascript">
function changeText(title, content){
document.getElementById('title').value = title.id;
document.getElementById('content').value = document.getElementById(content).getAttribute('data-content');
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$x[$a].'" type=button class=test onclick="changeText(this, '.$y[$a].');" value="Edit">';
echo '<p id="'.$y[$a].'" data-content="'.$row["content"].'">test</p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
?>
</div>
</div>
</div> <!--m4 ends here-->
<div class="col m8 s8"> <!--m8 starts here-->
<div class="titleboxmargin grey" style="width:100%;">
<div class="bar yellow"></div>
<img class="boxicon" src="../images/announcementsicon.svg">
<h3 class="title">Announcements</h3>
</div>
<div class="col yellow-light"> <!--Announcement Form Starts-->
<form action="includes/postAnnouncement.php" method="post">
<ul class="yellow-form">
<li class="textfield-container">
<label for="text" class="textlabelblack">Title:</label>
<input id="title" name= "title" type="text" placeholder="Title of My Announcement">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">Start Date:</label>
<input type="date" id="startDate" name="startDate">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">End Date:</label>
<input type="date" id="endDate" name="endDate">
</li>
<li class="textfield-container">
<label for="textarea" class="textlabelblack">Announcement:</label>
<textarea id="content" name="content" rows="7"></textarea>
</li>
<li class="textfield-container">
<div class="leftsidebutton">
<input type="submit" class="button" style="width:auto; padding:5px; border:0;" name="register" value="Submit the form"/><!--Action: Attempts to Redirect to postAnnouncement.php-->
</div>
</li>
</ul>
</form>
The following code works
Edit:
<script type="text/javascript">
function changeText(title, content){
document.getElementById('content').value = document.getElementById(content).getAttribute('data-content');
document.getElementById('title').value = document.getElementById(title).getAttribute('data-content');
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$tile = $row["announcementID"] * 2;
$cont = $row["announcementID"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$tile.'" data-content="'.$row["title"].'" type=button class=test onclick="changeText(id, '.$cont.');" value="Edit">';
echo '<p id="'.$cont.'" data-content="'.$row["content"].'">test</p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
?>
You could add a second parameter to your onclick handler:
$a = 0;
?>
<script type="text/javascript">
function changeText(elem, content){
document.getElementById('title').value = elem.id;
/*
* Here we get the value of the hidden content by the passed
* in id and assign it to the value of the #content form element
*/
document.getElementById('content').value = document.getElementById(content).value;
}
</script>
<?php
foreach ($announcement as $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
echo '<input id="'.$x[$a].'" type=button class=test onclick="changeText(this, '.$y[$a].'); startDate('.$y[$a].'); " value="Edit">';
echo '<p style="display:hidden;" id="'.$y[$a].'" ></p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
EDIT:
$a = 0;
?>
<script type="text/javascript">
function changeText(elem, contentID){
var contentElem = document.getElementById(contentID);
document.getElementById('title').value = elem.getAttribute('data-title');
/*
* Get the value of the hidden content's data attribute by the passed
* in id and assign it to the value of the #content form element
*/
document.getElementById('content').value = contentElem.getAttribute('data-content');
}
</script>
<?php
// Let's get $index as well
foreach ($announcement as $index => $row){ //Displays title, startDate, endDate from announcement table from database
$x[$a] = $row["title"];
$y[$a] = $row["content"];
echo "<h2 style=width:auto;padding:8px;margin-top:-30px;font-size:18px;><a style=text-decoration:none;color:#c4572f; >".$row["title"]."</a></h2><br>";
echo "<p style=padding-top:10px;>".$row["content"]."</p><br>";
echo "<p style=font-size:10px;>Posted: ".$row["startDate"]."</p><br>";
// Not sure if I'm escaping quotes correctly on this line:
echo '<input id="title'.$index.'" data-title="'.$x[$a].'" type=button class=test onclick="changeText(this, \"content'.$index.'\"); startDate('.$y[$a].'); " value="Edit">';
// Generate a unique id that we can reference
// and add `data-content` attribute
echo '<p style="display:hidden;" id="content'.$index.'" data-content="'.$y[$a].'"></p>';
echo "<h5 style=line-height:2px;margin-top:-15px;><p>_____________________________________</p></h5><br>";
}
I am not sure what your title and content values are, but I suspect they are not valid HTML element IDs. I think it would be better to avoid using the DOM as a data store and instead create a JSON representation of your announcement table in your script. My PHP is a little rusty, but it should be something similar to:
<script>
var rows = <?php echo json_encode($announcement); ?>;
</script>
Hopefully this will produce something like the following:
var rows = [
{
"title": "Title One",
"content": "Content One"
},
{
"title": "Title Two",
"content": "Content Two"
}
];
This way, our changeText function need only accept a row index as parameter:
function changeText (index) {
document.getElementById('title').value = rows[index].title;
document.getElementById('content').value = rows[index].content;
}
All that is left is to pass the row index where we call changeText:
<?php foreach ($announcement as $index => $row) { ?>
<!-- echo your HTML markup here. -->
<button onclick="changeText(<?php echo $index; ?>);">Edit</button>
<?php } ?>

AJAX comment system Validation problems

So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique

Populate second <select> drop down based on the first <select> drop down option

I'm trying to populate my second drop down based on the first selected drop down option.
Here's my work so far:
form.php - I used javascript to call getgeneral.php. Second drop down will show up when user has chosen from the (first) drop down:
<html>
<head>
<script type="text/javascript">
function get_states() { // Call to ajax function
var classitem = $('#classitem').val();
var dataString = "classitem="+classitem;
$.ajax({
type: "POST",
url: "getgeneral.php",
data: dataString,
success: function(html)
{
$("#get_general").html(html);
}
});
}
</script>
</head>
<body>
<form action="" method="POST">
<?php
include('conn.php');
$result=mysqli_query($con,"SELECT * FROM classtable");
?>
<select id="classitem" name="classitem" onchange="get_states();">
<option value=''>Select</option>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['genclasscode'] . "'>" . $row['description'] . "</option>";}
?>
</select>
<div id="get_general"></div>
</form>
</body>
</html>
This is the getgeneral.php where it will fetch data based from the first drop down list:
<?php
include('conn.php');
if ($_POST) {
$classitem = $_POST['classitem'];
if ($classitem != '') {
$result1=mysqli_query($con,"SELECT * FROM generalclass WHERE genclasscode='$classitem'");
echo "<select name='classitem'>";
echo "<option value=''>Select</option>";
while ($row = mysqli_fetch_array($result1)) {
echo "<option value='" . $row['specclassid'] . "'>" . $row['description'] . "</option>";}
echo "</select>";
}
else
{
echo '';
}
}
?>
PROBLEM: Second drop down won't show up. There's no error showing up when I run form.php
Sorry for getting back on this question too late.
The problem is that I forgot to include the jQuery in my code.
I include jQuery like this, between the <head> </head> section:
<link rel="stylesheet" type="text/css" href="jquery-ui-1.10.4.custom/css/custom-theme/jquery-ui-1.10.4.custom.min.css">
<script src="jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
Thank you to Bryan and Chitowns24 on their comments above.

Categories