take the result from JS to CI - javascript

i stuck with this one,, i want the the result from js to CI.. i want got string type data from js, and sendback it to CI.
this is my code:
<?php $i=0; foreach ($bahanx as $pin2){ ?> <script type="text/javascript">
document.write("<div class='input-group' style='width:175%'><label class='input-group-addon' style='width:100px'><input type='checkbox' name='bahan' aria-label='Checkbox for following text input' value="+<?php echo $pin2->id_barang ?>+" oninput='changeText(this,"+<?php echo $i ?>+");' > <?php echo $pin2->nama_barang;?></label><input type='text' class='form-control' aria-label='Text input with checkbox' name='banyak_bahan' value='0' disabled/></div><br/>");
</script>
<?php
$i++; } ?>
and this:
var item_box = document.getElementsByName('banyak_bahan');
var item_name = document.getElementsByName('bahan');
var tot;
function changeText(e,i){
item_name[i].value = e.checked ? 1 : 0;
item_box[i].disabled = !e.checked;
var x=x+","+item_box[i];
var y=y+","+item_name[i];
//alert(x);
document.getElementById('fff').innerHTML=x+"<br/>"+y;
}
id=fff
<div id='fff'></div>
the result:
undefined,[object HTMLInputElement]
undefined,[object HTMLInputElement]

Try this you have invalid js string thats because you print +<?php echo $aaa;?>+ inside try to delete +
UPDATE: try this to echo from php directly.
<?php
$i=0;
foreach ($bahanx as $pin2){
echo "<div class='input-group' style='width:175%'><label class='input-group-addon' style='width:100px'><input type='checkbox' name='bahan' aria-label='Checkbox for following text input' value='".$pin2->id_barang."' oninput='changeText(this,".$i.");' > ". $pin2->nama_barang ."</label><input type='text' class='form-control' aria-label='Text input with checkbox' name='banyak_bahan' value='0' disabled/></div><br/>";
$i++;
}
?>
instead of this
<?php $i=0; foreach ($bahanx as $pin2){ ?>
<script type="text/javascript">
document.write("<div class='input-group' style='width:175%'><label class='input-group-addon' style='width:100px'><input type='checkbox' name='bahan' aria-label='Checkbox for following text input' value="<?php echo $pin2->id_barang; ?>" oninput='changeText(this,"<?php echo $i; ?>");' > <?php echo $pin2->nama_barang; ?></label><input type='text' class='form-control' aria-label='Text input with checkbox' name='banyak_bahan' value='0' disabled/></div><br/>");
</script>
<?php $i++; } ?>
UPDATE: you saw x & y is not defined thats number one , to get value of checkbox element you must use item_name[i].value, item_box[i].value
var item_box = document.getElementsByName('banyak_bahan');
var item_name = document.getElementsByName('bahan');
var tot;
function changeText(e,i){
item_name[i].value = e.checked ? 1 : 0;
item_box[i].disabled = !e.checked;
var x= item_box[i].value;
var y= item_name[i].value;
//alert(x);
document.getElementById('fff').innerHTML=x+"<br/>"+y;
}

Related

PHP Looped Array, jquery to print each id value

So far I have managed that when a button is clicked it will print all values within the array. I need it to be smarter and only print the value of the element clicked.
<?php
$Arr_shoppingList = array(
array("Volvo",22,18,0),
array("BMW",15,13,1),
array("Saab",5,2,2),
array("Land Rover",17,15,3)
);
//Looped through array and printed values
foreach ($Arr_shoppingList as $value) {
echo "<div class='ColumnRow Spacing Color2 Border'>";
echo "<h1> $value[0] </h1> <br>";
echo "<p>'MPG'. $value[1]</p> <br>";
echo "<p>'Stock' . $value[2]</p> <br>";
echo "<form method='GET'>";
echo "<button class='Border' type='submit' id='$value[0]' class='Button'> $value[0]
</button>";
echo "</form>";
echo "</div>";
}
?>
<script>
$('button').on('click', function (event) {
event.preventDefault()
$('button').each(function(index, value){
console.log(value.id)
})
});
</script>
EDIT: The first section has been completed many thanks, but similarly, but I also need the stock and MPG values to also be targeted, how would I go about incorporating that into this code? this is part of a checkout basket I'm attempting to create.
You can use event.target.id to get the id of the clicked element
<?php
$Arr_shoppingList = array(
array("Volvo",22,18,0),
array("BMW",15,13,1),
array("Saab",5,2,2),
array("Land Rover",17,15,3)
);
//Looped through array and printed values
foreach ($Arr_shoppingList as $value) {
echo "<div class='ColumnRow Spacing Color2 Border'>";
echo "<h1> $value[0] </h1> <br>";
echo "<p>'MPG'. $value[1]</p> <br>";
echo "<p>'Stock' . $value[2]</p> <br>";
echo "<form method='GET'>";
echo "<button class='Border' type='submit' id='$value[0]' class='Button'> $value[0]
</button>";
echo "</form>";
echo "</div>";
}
?>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$('button').on('click', function (event) {
event.preventDefault()
console.log(event.target.id);
});
</script>

Trying to use JavaScript to calculate total booking price for selected seats using php pdo?

I am trying to use JavaScript to calculate total price for the tickets which are selected by using the checkbox. The result is should be shown in a alert window by clicking on the check button which invokes the JavaScript function. But when I click the button nothing happens. I don't even get any error message. I am a beginner so please if anyone can help me, I will be extremely thankful.
<?php foreach ($res as $row): ?>
<form action="book.php" method="get">
<tr><td><?php echo $row['RowNumber']; ?></td><td><?php echo $row['Price']; ?></td>
<td><input type="checkbox" type="hidden" name="myForm[<?php echo $row['RowNumber']; ?>][row]" id="row" value="<?php echo $row['RowNumber']; ?>"></input></td></tr>
<input type="hidden" name="myForm[<?php echo $row['RowNumber']; ?>][price]" id="price" value="<?php echo $row['Price']; ?>"></input>
</form>
<?php endforeach; ?>
</table>
<form action='book.php' method='get'>
Enter Email:<input type='text' name='name'></form>
<script>
function summary() {
var total = 0.0;
var seats = document.getElementById("row").value;
for(i = 1; i <= document.getElementById("row").value; i++) {
if(document.getElementId("row").checked) {
total = total + parseFloat(document.getElementById("price").innerHTML);
}
}
return total;
alert("Price of seats =" + total);
}
</script>
<input type="button" onclick="summary()" value="check">
<?php
You're returning before calling the alert, which means you never get to the alert itself. Remove the return total line.
This is a very common problem.All we have face atleast once.you should use Chrome istead of firefox or internet explorer.close your webpage and restart again.
return total should be after alertbox.
thankx.
You can try this sample
<form action="book.php" method="get">
<table>
<?php foreach ($res as $row): ?>
<tr data-rownumber="<?php echo $row['RowNumber']; ?>">
<td><?php echo $row['RowNumber']; ?></td>
<td><?php echo $row['Price']; ?></td>
<td>
<input type="checkbox" name="myForm[<?php echo $row['RowNumber']; ?>][row]" id="row-<?php echo $row['RowNumber']; ?>" value="<?php echo $row['RowNumber']; ?>" onclick="summary()" />
<input type="hidden" name="myForm[<?php echo $row['RowNumber']; ?>][price]" id="price-<?php echo $row['RowNumber']; ?>" value="<?php echo $row['Price']; ?>" />
</td>
</tr>
<?php endforeach; ?>
</table>
</form>
<form action='book.php' method='get'>
Enter Email:<input type='text' name='name'>
</form>
<script>
function summary() {
var total = 0.0;
var table = document.getElementById('items-table');
var rows = table.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var rowNumber = row.getAttribute('data-rownumber');
var isChecked = document.getElementById('row-' + rowNumber).checked;
if (isChecked) {
var price = parseFloat(document.getElementById('price-' + rowNumber).value);
total += price;
}
}
alert("Price of seats = " + total);
return total;
}
</script>
<input type="button" onclick="summary()" value="check">

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));

Remove particular row by clicking remove link present in the same row

I have form 1st page(test.php) as follows
<form method="post" action="newtest.php">
<input name="product[]" type="checkbox" value="1" <?php if(in_array("1", $session_products)) echo "checked='checked'"; ?> alt="1607.00" />
<input name="product[]" type="checkbox" value="2" <?php if(in_array("2", $session_products)) echo "checked='checked'"; ?> alt="1848.00" />
<input name="product[]" type="checkbox" value="3" <?php if(in_array("3", $session_products)) echo "checked='checked'"; ?> alt="180.00" />
<input name="product[]" type="checkbox" value="4" <?php if(in_array("4", $session_products)) echo "checked='checked'"; ?> alt="650.00" />
<input name="product[]" type="checkbox" value="5" <?php if(in_array("5", $session_products)) echo "checked='checked'"; ?> alt="495.00" />
<div class="ph-float">
<input type="submit" name="button" value="Checkout >>" class="ph-button ph-btn-green fm-submit" disabled="true" >
</div>
</form>
Based on checkbox selection am displaying Book name,Amount and total in a table as follows(newtest.php)
(Remember am not using data base, these values are not comming from data base instad am taking these values from
product array as specified below)
<?php
$product = array();
$product[1] = array('name' => "Text Book of Human Anatomy by B.D.Chaurasiavol 6th edition Vol -I Vol-II Vol-III.", 'price' => 1607);
$product[2] = array('name' => "Nettars Atlas of Anatomy", 'price' => 1848);
$product[3] = array('name' => "Genera Anatomy by B.D.Chaurasia", 'price' => 180);
$product[4] = array('name' => "Inderbir Singh Embryology 10th edition ", 'price' => 650);
$product[5] = array('name' => "Inderbir Singh Histology ", 'price' => 495);
if(isset($_POST['button']))
{
$first = array();
$second = array();
foreach ($_POST['product'] as $pId)
{
$first[] = $product[$pId]['name'];
$second[] = $product[$pId]['price'];
}
$bookauthor = count($first);
$bookprice = count($second);
$max = ($bookauthor > $bookprice ? $bookauthor : $bookprice);
echo '<br />';
echo '<i style="font-color:#000000;font-weight:bold;text-decoration:underline;font-size:21px; padding-left:110px;margin-top:10px"> List of books you have selected:</i>';
echo '<table>';
echo '<tr>';
echo '<th style="text-align: center">SL No.</th>';
echo "<th>Book Name</th>";
echo "<th>Amount in INR</th>";
echo "<th>Action</th>";
echo '</tr>';
$count = 0;
for ($i = 0; $i < $max; $i++)
{
$count++;
echo '<tr>';
echo "<td style='text-align: center'>{$count}</td>";
echo "<td>{$first[$i]}</td>";
echo "<td>{$second[$i]}</td>";
echo "<td><a href='#'><i style='color:#F5F5F5;background:#D52020'>REMOVE</i> </a></td>";
echo '</tr>';
}
$total = array_sum($second);
echo '<tr>';
echo "<td colspan='2' style='font-weight:bold;font-size:14px'>Total Amount</td>";
echo "<td style='font-weight:bold;font-size:14px;'>{$total}</td>";
echo "</tr>";
echo '</table>';
}
?>
I want to remove particular row from table when i click on REMOVE link displaying in a same row, how to achive this?
link is ok or should i have to use button.If any one write some code may helpfull as am new webie...
Thanks in advance.
$('i').click(function(){
$(this).parent('a').parent('td').parent('tr').remove();
});
The row is deleted but as clicking makes you follow the link, it's immediately restored when the page is refreshed.
Add return false; or event.preventDefault(); at the end of the callback to prevent the default behavior :
$(document).ready(function() {
$("#favoriteFoodTable .deleteLink").on("click",function() {
var tr = $(this).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(400, function(){
tr.remove();
});
return false;
});
});

Passing an id to a PHP script using jQuery/Ajax

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.

Categories

Resources