Passing an id to a PHP script using jQuery/Ajax - javascript

This is the code that the user have a participation with.
<html>
<head>
<title></title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery.form.js"></script>
</head>
<body>
<?php
include 'connection.php';
$sql="SELECT * FROM blog";
$result=mysqli_query($link, $sql);
if(!$result)
{
$output='Error fetching students:'.mysqli_error($link);
}
?>
<div id="table">
<table border='1' cellpadding='10' id="table">
<tr>
<td><b>Title<b></td>
<td><b>Edit<b></td>
<td><b>Delete<b></td>
</tr>
<?php
while($row=mysqli_fetch_array($result))
{
echo '<tr class="record">';
echo '<td>'.$row['articletitle'] .'';
echo '<td>Edit';
echo "<input type='hidden' name='id' value='".$row['articleid']."'></td>";
echo '<td><div align="center">Delete</div></td>';
echo "</tr>\n";
}
echo '<form method="post" id="myForm" action="postview.php">';
echo '<input type="hidden" name="myID">';
echo '</form>';
?>
</table>
<button id="addrecord">Add New Post</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#addrecord").click(function(){
$("#table").load("addpost.php");
$("#addrecord").hide();
});//add
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?"))
{
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function(){}
});//ajax
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});//delete
$(".title").click(function(){
$('[name=myID]').val($(this).attr('id'));
$('#myForm').submit();
});//view
$(".edit").click(function(){
var data=$("#tryform").serialize();
$.ajax({
type: "POST",
url: "editpost.php",
data: data
}).done(function( msg ) {
$("#table").html(msg);
});//ajax
});//delete
});
</script>
</body>
</html>
and this the PHP script that the code above redirect to.
<?php
include 'connection.php';
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
?>
I'm having this kind of error:
Undefined index: id in C:\xampp\htdocs\ckeditor\samples\postview.php on line 4

You need to check if argument "id" is passed to the php script first
<?php
include 'connection.php';
if( (isset($_GET['id'])) && ($_GET['id'] != '') ){ //check if the argument "id" is passed to the script
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
}
?>

Not so much an answer to your question, but probably a good suggestion to make your code a lot cleaner- try using PHP Alternative Syntax and moving in and out of PHP to make your HTML clean.
<?php while($row=mysqli_fetch_array($result)):?>
<tr class="record">';
<td><?php echo $row['articletitle'];?>
<td>Edit
<input type='hidden' name='id' value='<?php echo $row['articleid'];?>'></td>
<td>
<div align="center">
Delete
</div>
</td>
</tr>
<?php endwhile;?>
<form method="post" id="myForm" action="postview.php">
<input type="hidden" name="myID">
</form>

$sql="SELECT * FROM blog WHERE articleid='".$id."'";
try this line

That isnt an error, but a notice, which is lowlevel It simple means $_GET['id'] doesnt hav a value
echo $example['something']; // will give undefined index notice
$example['something'] = 'abc';
echo $example['something']; // No notices
Your website should be domain.ext/?id=123, if not, this notice will show.

Related

Create a text form inside table row that stays after submission and updates database

I want to create a column that has a text box inside each table row. The user can write any text inside the text box and click the 'Save' button to save it in the database. Additionally, the text box can be edited unlimited times. My code is the following:
index.php
<?php
...
while($row = $result->fetch_assoc()){
echo "<form action= 'search.php' method='post'>";
echo "<form action='' method='get'>";
echo "<tr>
<td><input type='checkbox' name='checkbox_id[]' value='" . $row['test_id'] . "'></td>
<td> ".$row['test_id']." </td>
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
<td> ".$row['path']." </td>
<td> ".$row['video1_path']." </td>
<td> ".$row['video2_path']." </td>
<td> ".$row['video3_path']." </td>
<td> ".$row['video4_path']." </td>";
if(empty($row["directory"])){
echo "<td></td>";
}else {
echo "<td><div><button class='href' id='" . $row['test_id'] . "' >View Report</button><div></td>";
}
echo " <td style='display: none;'> ".$row['directory']." </td>
</tr>";
}
?>
</table> <br>
<input id= 'select_btn' type='submit' name='submit' value='Submit' class='w3-button w3-blue'/>
</form>
</form>
</div>
<!-- Opens the pdf file from the pdf_report column that is hidden -->
<script type="text/javascript">
$(document).on('click', '.href', function(){
var result = $(this).attr('id');
if(result) {
var dir = $(this).closest('tr').find("td:nth-child(9)").text();
window.open(dir);
return false;
}
});
</script>
<!-- Updates text input to database -->
<script type="text/javascript">
$(document).on('click', '.name', function(){
var fcookie1= 'mycookie1';
var fcookie2= 'mycookie2';
var name = $(this).attr('id');
if(name) {
var text1 = $(this).closest('tr').find("td:nth-child(2)").text();
var text2 = $(this).closest('tr').find("td:nth-child(3)").text();
document.cookie='fcookie1='+text1;
document.cookie='fcookie='+text2;
$.ajax({
url: "name_edit.php",
type:"GET",
success: function() {
// alert("Edited Database");
}
});
}
});
</script>
name_edit.php
<?php include 'dbh.php' ?>
<?php include 'search.php' ?>
<?php
if (isset($_COOKIE["fcookie1"]))
echo $_COOKIE["fcookie1"];
else
echo "Cookie Not Set";
if (isset($_COOKIE["fcookie2"]))
echo $_COOKIE["fcookie2"];
else
echo "Cookie Not Set";
$var1 = $_COOKIE["fcookie1"];
$var2 = $_COOKIE["fcookie2"];
$conn = mysqli_connect($servername, $username, $password, $database);
$sql = "UPDATE test_data SET name='$var2' WHERE id='$var1'";
$query_run= mysqli_query($conn,$sql);
if($query_run){
echo '<script type="text/javascript"> alert(Data Updated)</script>';
} else {
echo '<script type="text/javascript"> alert(Data Not Updated)</script>';
}
?>
My idea was for the user to write any text. Then i will 'grab' the text and its expected id and save it to a cookie, when the save button is clicked. The cookie will then be echoed in name_edit.php and insert it in the sql code which will then update my database.
Im not sure what to include in 'value' inside the form tag. If there is data inside the database then display it inside the text box which can also be edited, else display blank for a text to be inserted.
I am new to coding and I'm a bit confused if my idea is correct or should i approach it another way.
I did some research and found out i did not have to use form but instead use 'contenteditable'. To edit the specific column i changed
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
to this:
<td class='name' data-id1='" . $row['test_id'] . "' contenteditable='true'>".$row['name']."</td>
and for my jquery i added the following:
<style>
.editMode{
border: 1px solid black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Add Class
$('.name').click(function(){
$(this).addClass('editMode');
});
// Save data
$(".name").focusout(function(){
$(this).removeClass("editMode");
var id = $(this).closest('tr').find("td:nth-child(2)").text();;
var value = $(this).text();
$.ajax({
url: 'name_edit.php',
type: 'post',
data: { value:value, id:id },
success:function(response){
alert('Edits Saved');
return false;
}
});
});
});
</script>
and in the php side, i simply did the following:
<?php include 'dbh.php' ?>
<?php
$conn = mysqli_connect($servername, $username, $password, $database);
$field = $_POST['field'];
$value = $_POST['value'];
$id= $_POST['id'];
$sql = "UPDATE test_data SET name='".$value."' WHERE test_id='".$id."'";
mysqli_query($conn,$sql);
echo 1;
?>

Passing a php variable to a javascript function on button click

I am displaying a dynamic table.
The problem is when I am passing the php variable to the javascript function it is showing an error Unterminate string literal.
I am new to php so I dont know how we pass the variable.
<?php
include 'dbConf.php';
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST["submit"]))
{
$username=$_SESSION["username"];
$productName=$_POST["productName"];
$quantity=$_POST["quantityRequired"];
$row = mysqli_query($conn,"INSERT into TR_Order_Details_Dummy values('$username','$productName','$quantity')");
if(!$row) {
die('Could not enter data: ' . mysqli_error($conn));
}
else{
$result=mysqli_query($conn,"SELECT * from Order_Details where Username='".$username."' ");
}
}
else
{
echo "dummy";
}
}
?>
<html>
<head>
<title>Order Details Page</title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<table id="table1">
<th>
<tr></tr>
<tr>Username</tr>
<tr>Product Name</tr>
<tr>Quantity</tr>
</th>
<?php
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['Username']."</td>";
echo "<td>".$res['ProductName']."</td>";
echo "<td>".$res['Quantity']."</td>";
$username=$res['Username'];
echo "<td><input type=\"button\" value=\"Edit\" onClick=\"editItem('\".$username.\"')\"> Delete</td>";
}
?>
</table>
</form>
<script>
function addItem()
{
window.location.href="order.php";
}
function editItem(username)
{
$.ajax({
type:"POST",
url:"edit.php",
});
return false;
}
</script>
</body>
</html>
Following line is incorrect.
echo "<td><input type=\"button\" value=\"Edit\" onClick=\"editItem('\".$username.\"')\"> Delete</td>";
You need to concatenate $username in the string so the quotes around it shouldn't be escaped with \ backslash.
Here's the modified code.
echo "<td><input type=\"button\" value=\"Edit\" onClick=\"editItem('".$username."')\"> Delete</td>";
Try your code with this command line
<input type=\"button\" value=\"Edit\" onClick=\"editItem('".$username."')\">

How to post the information using javascript for a preview table

Hey I need to know how to post the information to another php page using javascript to provide a preview table.
Here's my HTML that has a onchange tag that sends the productID to the function.
<form action="Home.php" method="Post">
<div>
<p>
<span class="text">Please Select a product:</span>
<select id="Select_Product" name="Select_Product" onchange="productInfo(this.value)" class="select">
<?php
//setting the select statement and running it
$search = "SELECT * FROM Library.Products order by Name";
$return = mysql_query($search);
//echo "<select id=Select_Product name=Select_Product onchange=productInfo(this.value) class=select>";
while ($row = mysql_fetch_array($return)) {
echo "<option value='" . $row['ProductID'] . "' selected='selected'>".$row['Name'] . "</option>";
}
?>
</select>
</p>
<table>
<tr>
<td>
<input name="action" type="submit"class="button" id="button_Add" value="Add"/>
</td>
<td>
<input name="action" type="submit" class="button" id="button_Remove" value="Remove"/>
</td>
<td>
<input name="action" type="submit" class="button" id="button_empty" value="Empty"/>
</td>
</tr>
</table>
</div>
From there I want it to send it to catalogue.php.
<script>
function productInfo(key) {
//Send key to catalogue.php
}
</script>
If I can get the other page to get that variable I can run a MYSQL command to get the information. Here is what catalogue.php looks like at the moment.
<?php
$sql = "SELECT Name, Price FROM Library.Products WHERE ProductID = " . $product_id;
echo "<table border=\"1\" padding=\"3\" width=\"650px\"><tr><th>Name</th><th>Description</th><th>Price</th><th width=\"80px\">Image</th></tr>";
echo "<tr>";
echo "<td>" .$product_id . "</td>";
echo "<td> Hi</td>";
echo "<td></td>";
echo "<td align=\"center\"><img alt=\"\" src=\"productImages/".$product_id.".jpg\ width=\"120\" height=\"120\"/></td>";
echo "</tr>";
echo "</table><br>";
document.
?>
So in a sense I want to turn the key in productInfo(key) to be assigned to the variable $product_id in catalogue.php. Thanks for helping.
You can add an invisible form :
<script>
function productInfo(key) {
//Send key to catalogue.php
document.getElementById( "key" ).value = key;
document.getElementById( "frm" ).submit(); // SUBMIT FORM.
}
</script>
<form action="catalogue.php" method="post" id="frm"
style="display:none" target="_blank">
<input type="text" id="key" name="key"/>
</form>
catalogue.php needs one little change :
<?php
$product_id = $_POST[ "key" ]; //<================== VALUE FROM THE INVISIBLE FORM.
$sql = "SELECT Name, Price FROM Library.Products WHERE ProductID = " . $product_id;
echo "<table border=\"1\" padding=\"3\" width=\"650px\"><tr><th>Name</th><th>Description</th><th>Price</th><th width=\"80px\">Image</th></tr>";
echo "<tr>";
echo "<td>" .$product_id . "</td>";
echo "<td> Hi</td>";
echo "<td></td>";
echo "<td align=\"center\"><img alt=\"\" src=\"productImages/".$product_id.".jpg\ width=\"120\" height=\"120\"/></td>";
echo "</tr>";
echo "</table><br>";
document.
?>
Or you can use Ajax :
html file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax ( key ) {
$.ajax( { type : 'POST',
data : { 'param' : key },
url : 'catalogue.php',
success: function ( data ) {
document.getElementById( "my_div" ).innerHTML = data;
},
error: function ( data ) {
alert( "error" );
}
});
}
function productInfo( key ) {
//Send key to catalogue.php
myAjax( key );
}
</script>
</head>
<body>
<button onclick="productInfo('123')">Click here to get the data</button>
<div id="my_div">
- data will show here -
</div>
</body>
</html>
catalogue.php
<?php
$key = $_POST[ "param" ];
echo "<table border='1'>" .
" <tr>" .
" <td>$key</td>" .
" <td>ABC</td>" .
" </tr>" .
"</table>";
?>

While loop gets killed when refreshing div

I have this JavaScript code refreshing my watcher.php file every 5 seconds and that works great. The first page load is fine but after the 5 seconds and so on the while loop gets killed. Any reason?
index.php file
<script type="text/javascript">
var auto_refresh = setInterval(function(){
$('.view').load('watcher.php');
}, 5000); // refresh div time
</script>
<body>
<div class="view">
<?php include 'watcher.php'; ?>
</div>
</body>
...
watcher.php file
include 'config.php';
$sql = "SELECT id, name, available, will_return, status FROM check_in_out";
$result = $conn->query($sql);
echo '<div style="margin-top:35px;"><center>';
echo '<table class="pure-table">
<thead>
<tr>
<th>Name</th>
<th>Available</th>
<th>Status/Comments</th>
<th>I\'ll Return At:</th>
<th>Returned</th>
</thead>
</tr>
';
if ($result->num_rows > 0) {
$i = 1;
// output data of each row
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td><img style="vertical-align:middle" src="imgs/card.jpg"> <a class="various" href="#'.$i.'"/>'.$row["name"];'</a></td>';
echo "<td>";
if ($row['available'] == 1) {
echo "<img src='imgs/available.gif'/>";
echo "Online";
} else {
echo "<img src='imgs/not-available.gif'/>";
echo "<span style='vertical-align:middle'>Away</span>";
};
echo "</td>";
echo '<td>'.$row["status"];'</td>';
echo '<td>'.$row["will_return"];'</td>';
echo '<td></td>';
echo '</tr>';
echo '<div align="center" id="'.$i++.'" style="display:none;width:520px;">
<h2>'.$row["name"].'</h2>
<!-- <h4>Current Status: '.$row["status"].'</h4> -->
<form method="post" action="statusChange.php" />
<input type="hidden" value="'.$row["id"].'" name="id"/>
<textarea rows="4" cols="50" placeholder="Enter Comment/Status Here..." name="comment"></textarea>
<br/><br/>
When will you return? - <input type="time" name="e_time">
<br/><br/>
<input class="pure-button pure-button-primary" type="submit" value="Leave/Return">
</form>
</div>';
}
} else {
echo "0 employees";
}
echo '</tr></table>';
echo '</div></center>';
$conn->close();
UPDATE:
What is by this is that look at image below. You will notice that after the first load (5 seconds) the clickable (href) gets killed...
<script type="text/javascript">
var updateWatcher = function() {
$.ajax({
url: 'watcher.php',
success: function(response) {
$('.view').html(response);
window.setTimeout(function(){
updateWatcher();
}, 3500);
}
});
}
updateWatcher();
</script>
Granted, this could be solved more elegantly with something like promises, but as far as a simple fix you could try something like this where the timer is only setup once the response has been successfully received. This should be more reliable.
Here is a simple fiddle: http://jsfiddle.net/agentfitz/26mahomm/3/ (look in the console).

Get input before submitting to insert into action url

Im trying to get a value of an input into my buttons action url before the button is pushed.
I need to get the value of:
id="qty<?php echo $i;?>"
Into where it says:
<?php echo VALUE OF $qtyforaction; ?>
My Code is:
<?php $i = $_product->getId();?>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<?php echo $qtyforaction; ?>
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/<?php echo VALUE OF $qtyforaction; ?>')" ><span><span>Order Again</span></span></button>
</form>
Would I have to use javascript to get it into the url string? My javascript is a bit ropey, would something like this work?
<script type="text/javascript">
var something= document.getElementById('<?php echo $qtyforaction;?>');
</script>
UPDATE WITH FULL CODE:
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
}
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
$_product = Mage::getModel('catalog/product')->load($item->getProductId());
$product_small_image_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(200);
$product_thumbnail_path = Mage::helper('catalog/image')->init($_product, 'small_image')->resize(150);
$summaryData = Mage::getModel('review/review_summary')->load($item->getProductId());
echo "<li>";
echo "<div class='previous-name'><p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "'>";
echo $item->getName() . "</a></p></div>";
echo "<div class='previous-image'><a href='" . $_product->getProductUrl() . "'>";
echo "<img src='" . $product_small_image_path . "' />";
echo "</a></div>";
echo "<div class='previous-rating'>";
echo "<p><a style='color:black; font-weight:bold; font-size:14px;' href='" . $_product->getProductUrl() . "#product_tabs_review_tabbed'>Review this beer now</a></p>";
echo $summaryData->getRatingSummary() . '% Would buy again <br/>';
echo "<div class='rating-box' style='float:left;'>";
echo "<div class='rating' style='width:" . $summaryData->getRatingSummary() . "%'></div></div>";
echo "</div>";
/**echo "<div class='previous-button'>";
echo '<button type="button" title="Add to Cart" class="button btn-cart" onclick="setLocation(\'';
echo $this->helper('checkout/cart')->getAddUrl($_product);
echo '\')"><span><span>Order Again</span></span></button>';
echo "</div>";**/
?>
<?php $i = $_product->getId();?>
<div class='previous-button'>
<form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId()?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<input type="text" name="qty" id="qty<?php echo $i;?>" maxlength="12" value="1" title="Qty" class="cartnum" />
<?php $qtyforaction = 'qty'.$i; ?>
<script type="text/javascript">
var xy = document.getElementsByTagName("input")[0].getAttribute("qty");
var x = "<button type='button' class='addtocartbutton button btn-cart' onclick='setLocation()'><span><span>Order Again</span></span></button>";
document.getElementById("buttonaddcart").innerHTML = x;
</script>
<div id="buttonaddcart">
<button type="button" class="addtocartbutton button btn-cart" onclick="setLocation('<?php echo $this->helper('checkout/cart')->getAddUrl($_product); ?>qty/')" ><span><span>Order Again</span></span></button>
</div>
</form>
</div>
<?php
echo "<div class='previous-clear'></div>";
echo "</li>";
}
}
}
?>
You need to get the value of the id attribute:
var x = document.getElementsByTagName("input")[0].getAttribute("id");
But how do you plan on using PHP to echo out this variable if PHP is loaded and done with before Javascript even comes into play? You could use Javascript though to display this variable on the page if that's all you needed.
If you had something in your HTML to target, you could do it like this:
document.getElementById("result").innerHTML = x;
But anyways, get the action attribute value...
var y = document.getElementsByTagName("form")[0].getAttribute("action");
Then set the action attribute to this + the qty...
document.getElementsByTagName("form")[0].setAttribute("action", x + y);
That should work for you, if not, try wrapping x + y in additional parentheses...("action", (x + y));

Categories

Resources