Post code interfering with inserting data in table - php

In my old code the user can buy as many as he wants to , but in the new code the user must input only numbers less than the stocks.
I am not sure whether this is the problem or not.
Somehow the purchase does not go to the sales total in sales table.
In history.php the total purchase price does not show up , but when you click the view full details button you can see the total purchase.
History.php
View Full Detail
Sales table.
This is my old code add_cart.php code
In here it inserts fine.
<?php
include('session.php');
if(isset($_POST['cart'])){
$id=$_POST['id'];
$qty=$_POST['qty'];
$query=mysqli_query($conn,"select * from cart where productid='$id' and userid='".$_SESSION['id']."'");
if (mysqli_num_rows($query) > ($qty)){
echo "Input must be lower than the quantity!";
}
else{
mysqli_query($conn,"insert into cart (userid, productid, qty) values ('".$_SESSION['id']."', '$id', '$qty')");
}
}
?>
This is my new code add_cart.php code
In here it does not insert properly.
include('session.php');
if(isset($_POST['cart'])){
$id=$_POST['id'];
$qty=$_POST['qty'];
if($qty>0){//This Condition work for you
$query=mysqli_query($conn,"select product_qty from product where productid='$id'");
$result=mysqli_fetch_object($query);
if($result->product_qty < $qty){
echo 'Input must be lower than the stocks';
} else{
$query=mysqli_query($conn,"select * from cart where productid='$id' and userid='".$_SESSION['id']."'");
if (mysqli_num_rows($query)>0){
echo "Product already on your cart!";
}
else{
mysqli_query($conn,"insert into cart (userid, productid, qty) values ('".$_SESSION['id']."', '$id', '$qty')");
}
}
}
}
?>
history.php where the table are listed
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</html>
<?php include('session.php'); ?>
<?php include('header.php'); ?>
<body>
<?php include('navbar.php'); ?>
<div class="container">
<?php include('cart_search_field.php'); ?>
<div style="height: 50px;"></div>
<div class="row">
<div class="col-lg-12">
<center> <h1 class="page-header">Purchase History</h1></center>
</div>
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<center>
<form action="total_sales.php" method="post">
From: <input type="text" class="datepicker" placeholder="E.G.(2018-01-14)" name="dayfrom" required pattern="[0-9]{4}+[0-9]+[0-9]"> To: <input type="text" class="datepicker" placeholder="E.G.(2018-02-11)" name="dayto" required pattern="[0-9]{4}+[0-9]+[0-9]">
<input type="submit" value="Show Purchases" name="salesbtn" ></form></center>
<table width="100%" class="table table-striped table-bordered table-hover" id="historyTable">
<thead>
<tr>
<th class="hidden"></th>
<th>Purchase Date</th>
<th>Total Amount</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$h=mysqli_query($conn,"select * from sales where userid='".$_SESSION['id']."' order by sales_date desc");
while($hrow=mysqli_fetch_array($h)){
?>
<tr>
<td class="hidden"></td>
<td><?php echo date("M d, Y - h:i A", strtotime($hrow['sales_date']));?></td>
<td><?php echo number_format($hrow['sales_total'],2); ?></td>
<td>
<span class="glyphicon glyphicon-fullscreen"></span> View Full Details
<?php include ('modal_hist.php'); ?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
</div>
</div>
<?php include('script.php'); ?>
<?php include('modal.php'); ?>
<script src="custom.js"></script>
<script>
$(document).ready(function(){
$('#history').addClass('active');
$('#historyTable').DataTable({
"bLengthChange": true,
"bInfo": true,
"bPaginate": true,
"bFilter": true,
"bSort": true,
"pageLength": 7
});
});
</script>
</body>
</html>

Related

I can't update my basket at database(using ajax!) when a user changes the count of products that he/she bought?

I have a eshop. in user basket the user added some products. now he/she wants to change(increase or decrease) the number(count) of the products. I have wrriten this part with ajax but it doesn't work. every thing seems right! I don't know whats wrong! please help me...
"at the end I have added "update_order.php" page's code."
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
include('database.php');
$object=new myclass_parent;
?>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link href="css/bootstrap.min.css" rel="stylesheet"/>
<link href="css/bootstrap.rtl.min.css" rel="stylesheet"/>
<script type="text/javascript">
$(document).ready(function () {
$(".navbar-right li .navbar-brand").hide();
});
</script>
<title></title>
</head>
<body>
<?php
include('header.php');
?>
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<div class="container content info">
<h4>سبد خرید</h4>
<div class="row">
<div style="display:none;margin-top:10px;" id="err_alert" class="alert alert-danger ">
<span id="empty_err"> </span>
</div>
<div class="table-responsive">
<table class="table my_table">
<thead>
<tr>
<th>فروشنده</th>
<th>توضیحات کالا</th>
<th>تعداد</th>
<th>قیمت واحد</th>
<th colspan="2">قیمت کل</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_COOKIE['mybasket'])){
$query="select * from tblbasket where cookiename=? and payment=0";
$array=[$_COOKIE['mybasket']];
$result_array=$object->select($query,$array);
foreach($result_array as $result){
$productid=$result['productid'];
$count=$result['count'];
$query2="select * from tblproducts where id=?";
$array2=[$productid];
$result_array2=$object->select($query2,$array2);
$img=$result_array2[0]['img'];
$title=$result_array2[0]['title'];
$price=$result_array2[0]['price'];
$info=$result_array2[0]['info'];
?>
<tr id="<?php echo $productid; ?>" class="pitem">
<td rowspan=''>amazoon.com</td>
<td>
<img src="<?php echo $img; ?>" width="100" height="80"/>
<div>
<strong><?php echo $title; ?></strong>
<p><?php echo $info; ?></p>
</div>
</td>
<td>
<input style="width:50px" type="number" id="pcount" class="pcount"
onKeyDown="return checknumber(event);" min="1" value="<?php echo $count; ?>">
</td>
<td><span id="pprice"><?php echo $price; ?></span> تومان</td>
<td><span id="kol_price"><?php echo $count*$price; ?></span> تومان</td>
<td><a style="cursor:pointer;" class="remove"><img src="images/delete.png" alt="حذف محصول" title="حذف محصول"/></a></td>';
<?php
}//foreach
?>
</tr><!--basket_items-->
</tbody>
</table>
<br/>
</div>
</div>
<?php
}//isset cookie
?>
<div class="row">
<div class="col-12">
<table class="table-responsive tbl jamkharid">
<thead>
<tr><th>پیش فاکتور خرید</th></tr>
<tr><th>مبلغ کل</th><th>مالیات 9%</th><th>هزینه ارسال</th> <th>مبلغ پرداختی نهایی</th></tr>
</thead>
<tbody>
<td><span id="jam_kharid"></span> تومان</td><td><span id="maliat"></span> تومان</td>
<td><span id="delivery">0</span> تومان</td><td><span id="jam_kharid_final"></span> تومان</td>
</tbody>
</table>
</div><!--col12-->
</div><!--row-->
<div class="row">
<?php if(isset($_SESSION['email'])){ ?>
مرحله بعد
<?php }//if
else{
?>
مرحله بعد
<?php }//else ?>
</div>
</div>
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<!--------------------------------->
<?php
include('footer.php');
?>
</body>
</html>
<script>
var timer;
function jam_kharid(){
var amount=0;
var buy_amount=0;
clearTimeout(timer);
timer=setTimeout(function(){
$(".pitem").each(function(index, element) {
var pcount=$(this).find("#pcount").val();
var pprice=$(this).find("#pprice").text();
amount=amount+parseInt(pcount)*parseInt(pprice);
buy_amount=(1.09*amount).toFixed(0);
});//each pitem function
$(".pitem .pcount").change(function(){
var pcount=$(this).val();
var pprice=$(this).parents(".pitem").find("#pprice").text();
var kol_price=parseInt(pcount)*parseInt(pprice);
$(this).parents(".pitem").find("#kol_price").text(kol_price);
jam_kharid();
//****************************************************************************************************************
var productcount=pcount;
var productid=$("#pcount").parents(".pitem").attr('id');
alert(productid);
$.ajax({
url:'update_order.php',
type:'POST',
data:{productid:productid,cookiename:<?php echo $_COOKIE['mybasket']; ?>,productcount:productcount}
})//ajax
.done(function(msg){
alert(msg);
})//done
//****************************************************************************************************************
});//change
$(".jamkharid").find("#jam_kharid").html(amount);
$('.jamkharid').find("#maliat").text(amount*0.09);
$('.jamkharid').find("#jam_kharid_final").text((1.09*amount).toFixed(0));
},600);
}//jam_kharid
jam_kharid();
function khali(){
var l=$('.pitem').length;
if(l==0){
$('#err_alert').show(300); $('#err_alert #empty_err').show(); $('#err_alert #empty_err').html('هیچ محصولی در سبد خرید شما موجود نمی باشد!');
$('.my_table').hide();
$('.jamkharid').hide();
}
}//function p_length
khali();
$(".remove").click(function(){
var id_pitem=$(this).parents(".pitem").attr('id');
var pitem_parent=$(this).parents(".pitem");
$.ajax({
url:'delete.php',
type:'POST',
data:{id:id_pitem}
})//ajax
.done(function(){
pitem_parent.remove();
alert('محصول مورد نظر حذف شد');
jam_kharid();
khali();
})//done
})//remove click function
function checknumber(e){
if( (e.keyCode==65 && e.ctrlKey) || (e.keyCode>=35 && e.keyCode<=40) || ($.inArray(e.keyCode,[8,46])!=-1) ){
return;
}//if
if( e.shiftKey || ((e.keyCode<48 || e.keyCode>57) && (e.keyCode<96 || e.keyCode>105)) ){
e.preventDefault();
}//if
}//checknumber
</script>
////////////////////////////////////////////////////////////////////////////////
update_order.php :
////////////////////////////////////////////////////////////////////////////////
<?php
include('database.php');
$object=new myclass_parent;
$product_id=intval($_POST['productid']);
$cookie_name=$_POST['cookiename'];
$product_count=intval($_POST['productcount']);
$query_update="update tblbasket set count=? where cookiename=? and productid=? and payment=0";
$array=array($product_count,$cookie_name,$product_id);
$object->myquery($query_update,$array); echo $product_id;
?>

Issue with foreach loop updating every record, rather than the ones just selected in a checkbox

I have a page with a dropdown box at the top populated from the database, when I select an item from the dropdown it gives a list of results with a checkbox at the end of each line, I want to be able to select, using each checkbox, any number of results, and submit a value back into a field in the database for each result selected.
I sort of have this working, but it submits the value to every field in the database, rather than just the ones selected
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="favicon.ico">
<title>Stock Items</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- bootstrap theme -->
<link href="css/bootstrap-theme.css" rel="stylesheet">
<!--external css-->
<!-- font icon -->
<link href="css/elegant-icons-style.css" rel="stylesheet" />
<link href="css/font-awesome.min.css" rel="stylesheet" />
<!-- full calendar css-->
<link href="assets/fullcalendar/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet" />
<link href="assets/fullcalendar/fullcalendar/fullcalendar.css" rel="stylesheet" />
<!-- easy pie chart-->
<link href="assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen"/>
<!-- owl carousel -->
<link rel="stylesheet" href="css/owl.carousel.css" type="text/css">
<link href="css/jquery-jvectormap-1.2.2.css" rel="stylesheet">
<!-- Custom styles -->
<link rel="stylesheet" href="css/fullcalendar.css">
<link href="css/widgets.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/style-responsive.css" rel="stylesheet" />
<link href="css/xcharts.min.css" rel=" stylesheet">
<link href="css/jquery-ui-1.10.4.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<script src="js/lte-ie7.js"></script>
<![endif]-->
</head>
<body>
<!-- container section start -->
<section id="container" class="">
<?php include("navigation.php"); ?>
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!--overview start-->
<div class="row">
<div class="col-lg-12">
<h3 class="page-header"><i class="fa fa-lightbulb-o"> </i>Stock</h3>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i>Home</li>
<li><i class="fa fa-lightbulb-o"></i>Stock</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
All Stock
</header>
<div class="panel-body">
<form class="form-horizontal" method="post" action="">
<div class="form-group">
<div class="col-lg-8">
<select name="search" class="form-control" required >
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `description` FROM `stock_templates`";
$stock_templates = mysql_query($query);
echo "<option value=''>Select Stock Template</option>";
while ($description=mysql_fetch_assoc($stock_templates)) {
echo "<option value='" . $description['id'] . "'>" . $description['description'] . "</option>";
}
?>
</select>
</div>
<div class="col-lg-1">
<input type="submit" name="filter" value="Search" class="btn btn-success" />
</div>
</div>
</form><br><br>
<?php
if(isset($_POST['formSubmit']))
{
$aDoor = $_POST['check_list'];
if(empty($aDoor))
{
echo("<p>You didn't select any items to add to lease.</p>\n");
}
else
{
$N = count($aDoor);
echo("<p>You selected $N item(s) to add to lease: ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
echo("</p>");
}
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
?>
<?php
ob_start( );
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$query = mysql_query("UPDATE stock SET lease_id = $lease_id");
$result2 = mysql_query($query);
// check if sent
if ($result2) {
?>
<div class="alert alert-success fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Well done!</strong> Your lease items have been successfully saved.
</div>
<?php
} else {
?>
<div class="alert alert-block alert-danger fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Oh snap!</strong> We could not save your lease items.
</div>
<?php
}
}
}
?>
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
// Extract filter information
$count = 0;
$search = mysql_escape_string(#$_POST['search']);
// select data from the database
$query2 = "SELECT * FROM `stock_templates` ORDER BY `stock_templates`.`id` DESC LIMIT 0";
// Perform Logic
if (array_key_exists("filter", $_POST)) {
// query based on search term
$query2 = "SELECT * FROM `stock` WHERE $search=stocktemplate_id AND lease_id=0";
}
$result2 = mysql_query($query2);
// Result
if (mysql_num_rows($result2) < 1) {
echo "<div align='center'><h2>Please select a stock template above and click search</h2></div>";
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" class="form-horizontal" name="check_list[]">
<div class="form-group">
<label class="control-label col-lg-1" for="lease_id">Lease Number *</label>
<div class="col-lg-10">
<select name="lease_id" class="form-control">
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `leasenumber` FROM `lease`";
$leases = mysql_query($query);
echo "<option value=''>Select Lease..........</option>";
while ($lease=mysql_fetch_assoc($leases)) {
echo "<option value='" . $lease['id'] . "'>" . $lease['leasenumber'] . "</option>";
}
?>
</select>
</div>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Item ID</th>
<th>Description</th>
<th>Barcode</th>
<th>Serial</th>
<th>Add To Lease</th>
</tr>
</thead>
<?php
while ($row = mysql_fetch_array($result2))
{
$id = $row["id"];
$lease_id = $row["lease_id"];
$barcode = $row["barcode"];
$serial = $row["serial"];
$stocktemplate_id = $row["stocktemplate_id"];
$qa = 0;
?>
<tbody>
<tr>
<td><?php print $id ?></td>
<td><?php $q = mysql_query("SELECT description FROM stock_templates WHERE id = '$stocktemplate_id'"); while ($row = mysql_fetch_array($q)){$qa = $row["description"];} print $qa ?></td>
<td><?php print $barcode ?></td>
<td><?php print $serial ?></td>
<td><input type="checkbox" name="check_list[]" value="<?php print $id ?>" /></td>
<td></td>
</td>
</tr>
</tbody>
<?php
}
?>
</table>
<input class="btn btn-danger" type="submit" name="formSubmit" value="Add Selected To Lease" />
</div>
</form>
</section>
</div>
</div>
</section>
</section>
<!--main content end-->
</section>
<!-- container section end -->
<!-- javascripts -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- nice scroll -->
<script src="js/jquery.scrollTo.min.js"></script>
<script src="js/jquery.nicescroll.js" type="text/javascript"></script>
<!-- jquery ui -->
<script src="js/jquery-ui-1.9.2.custom.min.js"></script>
<!--custom checkbox & radio-->
<script type="text/javascript" src="js/ga.js"></script>
<!--custom switch-->
<script src="js/bootstrap-switch.js"></script>
<!--custom tagsinput-->
<script src="js/jquery.tagsinput.js"></script>
<!-- colorpicker -->
<!-- bootstrap-wysiwyg -->
<script src="js/jquery.hotkeys.js"></script>
<script src="js/bootstrap-wysiwyg.js"></script>
<script src="js/bootstrap-wysiwyg-custom.js"></script>
<!-- ck editor -->
<script type="text/javascript" src="assets/ckeditor/ckeditor.js"> </script>
<!-- custom form component script for this page-->
<script src="js/form-component.js"></script>
<!-- custome script for all page -->
<script src="js/scripts.js"></script>
</body>
</html>
No worries. Just put the code of insert query inside foreach() loop. Like this:
foreach($_POST['check_list'] as $item)
{
$sql="INSERT/UPDATE Query";
//for example
$sql = "INSERT INTO table_demo (field_1, TARGET_FIELD, field_2, field_3) VALUES (val_1, $item, val_2, val_3)";
$insert = mysqli_query($connection,$sql);
}
//next code of your choice
That is really Easy to give a go.
See this is same as you want.
In this link the first answer by Sean Valsh is your solution.
Giving the array as name of every checkbox will give you only chacked option's id in array while submitted.
https://stackoverflow.com/a/4997271/6834980
Ask if still have the problem. Happy to help.

Form if then Else/ifElse HTML on submit

I have a form that I need to act in specific ways. Example: User brings equipment back: I don't want that to show up in my form. User takes equipment out: I want it to generate to my form, they enters some information, form sends information to database. User takes equipment out: it too generates said form, he doesn't enter any information, form submits information after 20 sec, information is in database.
I was doing a simple page refresh to get the information into my form but that was pulling all the equipment that had been brought into the warehouse that day. So I commented that out and then I would get stuck on my ajax page.
I then tried creating a new php page that had a 301 page refresh and that worked to get the page back to my index page, however, my form wasn't working properly and so I commented out the auto submit and now my form works great... except I can't fulfill this last requirement where the page will submit the data if the user forgets to put his equipment information in.
I'm looking to do an if/then/else type of page submission. However, I can't figure out how to do one purely in either php or html. This is what I have figured out so far but it doesn't work and I know I'm way off somewhere.
<!DOCTYPE html>
<html>
<body>
<!--This is the one that is currently commented out in my code
<script type="text/javascript">
window.setTimeout(function() {
window.location = 'index.php'},1000*2);
</script>
</body>
</html> -->
//This is my pipe dream
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case ‘DONE’:
document.getElement('formSubmit').submit();
break;
}
} else {
<script type="text/javascript">
window.setTimeout(function(){
document.getElement('formSubmit').submit();
},1000*30);
</script>
}
?>
I don't know that much about jQuery other than going through a codecademy, and I know even less javascript. I'm a database person that got "conned" into building an advanced form/webpage. So I'm learning PHP, CSS, jQuery and HTML as I code.
Index.php:
<!DOCTYPE html>
<html>
<head>
<meta name=“Warehouse 3962” content="width=device-width, initial-scale=1.0">
<link href="style.css" type="text/css" rel="stylesheet">
<script type="text/javascript">
<!—window.setTimeout(function(){
document.getElement(‘formSubmit').submit();
},1000*30); —>
</script>
</head>
<body>
<section class="w">
<div class="row">
<div class="small columns">
<img src="logo.png" />
<h3 class="green">Users</h3>
</div>
<h6>Warehouse 3962</h6>
</div>
<div class="row">
<div class="small columns">
<form action="ajax.php" method="post" id="formSubmit">
<table id="equipment-table">
<thead>
<tr>
<th>Equipment</th>
<th>Amount</th>
<th>Val1</th>
<th>Val2</th>
</tr>
</thead>
<tbody>
<?php foreach
($results['tags'] as $equipment) {
if ($equipment['category'] == "Part") { ?>
<tr>
<td><?= $equipment['Amount']; ?></td>
<td class="text-center"><?= $equipment[‘quantity']; ?></td>
<td><input type="text" name="val1" /></td>
<td><input type="text" name="val2" /></td>
</tr>
<?php } // end if
} // end foreach ?>
<tr>
<td colspan="4" style="text-align: right;"><input type="submit" class="button" name="DONE" value="DONE" /></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</section>
</body>
</html>
Please try this new solution. This will send a post every 30 seconds containing only the input boxes containing text on them.
<!DOCTYPE html>
<html>
<head>
<meta name="Warehouse 3962" content="width=device-width, initial-scale=1.0">
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<section class="w">
<div class="row">
<div class="small columns">
<img src="logo.png" />
<h3 class="green">Users</h3>
</div>
<h6>Warehouse 3962</h6>
</div>
<div class="row">
<div class="small columns">
<form action="ajax.php" method="post" id="formSubmit">
<table id="equipment-table">
<thead>
<tr>
<th>Equipment</th>
<th>Amount</th>
<th>Val1</th>
<th>Val2</th>
</tr>
</thead>
<tbody>
<?php
foreach ($results['tags'] as $equipment) :
if ($equipment['category'] === "Part") :
?>
<tr>
<td>
<?php echo $equipment['Amount']; ?>
</td>
<td class="text-center">
<?php echo $equipment['quantity']; ?>
</td>
<td>
<input id="<?php echo $equipment['number'];?>-val1" type="text" name="<?php echo $equipment['number'];?>-val1"/>
</td>
<td>
<input id="<?php echo $equipment['number'];?>-val2" type="text" name="<?php echo $equipment['number'];?>-val2"/>
</td>
</tr>
<?php
endif;
endforeach;
?>
<tr>
<td colspan="4" style="text-align: right;">
<input type="submit" class="button" name="DONE" value="DONE" />
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</section>
<script type="text/javascript">
function sendData() {
var inputs = document.getElementById('equipment-table').getElementsByTagName('input'),
data = [],
name, val1, val2;
for (var i = 0; i < inputs.length; i++) {
if ( inputs[i].type === 'submit') {
continue;
}
if ( inputs[i].value ) {
name = inputs[i].name.split('-val');
val1 = inputs[i].name.split('val1');
if (val1.length > 1) {
data.push({name: name[0], val1: inputs[i].value});
}
else {
data.push({name: name[0], val2: inputs[i].value});
}
}
}
window.setTimeout(function() {
sendData();
},30000);
}
sendData();
</script>
</body>
</html>
You cannot mix PHP with JavaScript and why you set a timeout to 1000*30, that is equal to set a timeout to 30000 which means 30 seconds.
Then, you can use the 'require' attribute in the input filed to force the user to fill the required information.
<!DOCTYPE html>
<html>
<head>
<meta name="Warehouse 3962” content="width=device-width, initial-scale=1.0">
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<section class="w">
<div class="row">
<div class="small columns">
<img src="logo.png" />
<h3 class="green">Users</h3>
</div>
<h6>Warehouse 3962</h6>
</div>
<div class="row">
<div class="small columns">
<form action="ajax.php" method="post" id="formSubmit">
<table id="equipment-table">
<thead>
<tr>
<th>Equipment</th>
<th>Amount</th>
<th>Val1</th>
<th>Val2</th>
</tr>
</thead>
<tbody>
<?php
foreach ($results['tags'] as $equipment) :
if ($equipment['category'] == "Part") : ?>
<tr>
<td><?= $equipment['Amount']; ?></td>
<td class="text-center">
<?php echo $equipment[‘quantity']; ?>
</td>
<td>
<input id="val1" type="text" name="val1”/>
</td>
<td>
<input id="val2" type="text" name="val2"/>
</td>
</tr>
<?php
endif;
endforeach;
?>
<tr>
<td colspan="4" style="text-align: right;">
<input type="submit" class="button" name="DONE" value="DONE" />
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</section>
<script type="text/javascript">
window.setTimeout(function(){
var val1 = document.getElementById("val1").value,
val2 = document.getElementById("val1").value;
if ( ! val1 && ! val2 ) document.getElement('formSubmit').submit();
},30000);
</script>
</body>
</html>

Ajax call in codeigniter

i actually want to use ajax in CodeIgniter to update value in the database.
below is the code given:
views/list_user.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Admin Panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/screen.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.round_button_circle').click(function() {
//Now just reference this button and change CSS
//$(this).css('background','green');
var id=this.value;//Getting the id of the user to update the status from unpublish to publish
var url='<?php echo base_url(); ?>index.php/ajax_controller/user_status';
alert(id+url);
$.ajax({
type: 'POST',
url: 'url', //We are going to make the request to the method "list_dropdown" in the match controller
data: 'id='+id, //POST parameter to be sent with the tournament id
success: function(data)
{
}
});
});
});
</script>
</head>
<body>
<div id="page-heading">
<div class="button">Create User</div><!--create category-->
<h1>USERS</h1><!--users's list-->
</div>
<!-- end page-heading -->
<table border="0" style="width:97%;margin:0px auto" cellpadding="0" cellspacing="0" id="content-table">
<tr>
<td>
<!-- start content-table-inner START -->
<div id="content-table-inner">
<div class="stdiv"><div class="msg1">
<?php
if(isset($_GET['msg']))
{
$msg=$_GET['msg'];
if($msg=="usertype")
{
echo "User has been Created";
}
if($msg=="create")
{
echo "User has been Created";
}
if($msg=="delete")
{
echo "User has been Deleted";
}
if($msg=="update")
{
echo "User has been Updated";
}
}
?>
</div>
</div>
<!-- start category-table -->
<table border="0" cellpadding="0" style="width:100%;margin:0px auto" cellspacing="0" id="product-table">
<tr>
<tr>
<th class="tbl_hdr">USER ID</th> <!--ID-->
<th class="tbl_hdr">‫NAME</th> <!--Name-->
<th class="tbl_hdr">EMAIL</th> <!--Email-->
<th class="tbl_hdr">PHONE NUMBER‎</th> <!--ph number-->
<th class="tbl_hdr">STATUS</th> <!--publish/unpublish-->
<th class="tbl_hdr" colspan="2">ACTION</th> <!--edit/delte-->
</tr>
<?php foreach($users as $user){?>
<tr>
<td><?php echo $user->id;?></td>
<td><?php echo $user->username;?></td>
<td><?php echo $user->email;?></td>
<td><?php echo $user->contact;?></td>
<td ><button id="status" class="round_button_circle" value="<?php echo $user->id;?>"></button></td>
</tr>
<?php }?>
</table>
<!-- end product-table................................... -->
</div>
<!-- end content-table -->
<!-- start paging..................................................... -->
<!-- end paging................ -->
<div class="clear"></div>
<!-- end content-table-inner ............................................END -->
</td>
</tr>
</table>
<div class="clear"> </div>
</div>
<!-- end content -->
<div class="clear"> </div>
</div>
<!-- end content-outer........................................................END -->
<div class="clear"> </div>
<!-- start footer -->
</body>
</html>
controller/ajax_controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_Controller extends CI_Controller {
// Show view Page
// This function call from AJAX
public function user_status()
{
$id=$this->input->post('id');
$data = array(
'status' => 1
);
$this->db->where('id', $id);
$this->db->update('tbl_users', $data);
echo "1";
}
}
Its giving me the url and the id which i want to update in the database in the alert box...but its not updating the value in the database once the button is clicked..
Can anyone help???
There is one mistakes in your code.
Change
url: 'url', // in ajax call
To
url: url, // do not use quotes with url variable

Can't Display data from mysql on table jquery mobile

to the point, I'm having trouble with jquery mobile. If i innactive the source from jquery my script run. but if I Activate the source of jquery, my php script didnt work.
This my script
<html>
<head>
<title>Security</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--script for jquery source-->
<link rel="stylesheet" href="jqm2/jquery.mobile-1.3.1.min.css" />
<script src="jqm2/jquery.js"></script>
<script src="jqm2/jquery.mobile-1.3.1.min.js"></script>
<!--script for jquery source-->
</head>
<body>
<div data-role="page" id="BahanBaku" class="type-interior" data-theme="c">
<div data-role="header">
<h1>Bahan Baku</h1>
</div><!-- /header -->
<div data-role="content">
<form method="post" action="BahanBaku.php">
<!--this select button-->
<select name="BARANG" data-native-menu="false" onchange="this.form.submit()">
<option value="">Pilih Nama Barang</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<!--this select button-->
</form>
<?php
//this script for get data from mysql based the select button
if(isset($_POST[BARANG])){
$barang = $_POST[BARANG];
//print_r($_POST);
$sql2 = "SELECT * FROM tb_spekbaku WHERE namaBarang = '$barang' ";
$hasil2 = mysql_query($sql2) or die ('Error = '. mysql_error());
$data2 = mysql_fetch_array($hasil2);
}
?>
<table data-role="table" id="table-column-toggle" data-mode="columntoggle" class="ui-responsive table-stroke">
<thead>
<tr>
<th>Jenis Spec</th>
<th>Spec</th>
</tr>
</thead>
<tbody>
<tr>
<th>Lain lain</th>
<td><?php echo $data2[lain];?></td><!--this is the line when jquery inactive the result showed, but if jquery active the result not show again-->
</tr>
</tbody>
</table>
</div><!--end off content-->
<div data-role="footer">
<h4>Bla bla </h4>
</div><!-- /footer -->
</div><!--end of page-->
</body>
</html>
Can Anyone help me to Fix this?
Im very appreciated your answer
Thanks
By default form submissions are being automatically handled with Ajax in jQM.
To prevent this behavior, add the data-ajax="false" attribute to the form element.
<form method="post" action="BahanBaku.php" data-ajax="false">

Categories