Objective Inserting name(input-text) and info(textarea-contains multiple lines) into the database, and after submission of the form, at the same page, 2 columns are for displaying the same data in columns, name & info, but under info column. I have made buttons for each row in front of the names, which is used as slideToggle for showing/hiding which contains the data retrieved from the 'info' column
Problem - when I am clicking the button of 1st row, instead of displaying the info related to 1st entry only, it is sliding and showing all info(s) related to all entries at only click.
*others - one more input has been added to the form but as hidden used for id(auto increment)
----index.php-----
<?php include('php_code.php'); ?>
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM records WHERE id=$id");
if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$name = $n['name'];
$acc = $n['acc_no'];
$info = $n['info'];
}
}
?>
<html>
<head>
<title>JSK</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('form').hide();
$('p').hide();
$('#sp').hide();
$("#inf").click(function(){
$("p").slideToggle();
$('#sp').slideToggle();
});
$("#fo").click(function(){
$("form").slideToggle();
});
});
</script>
</head>
<body>
<div class="container">
<div class="left">
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
<?php $results = mysqli_query($db, "SELECT * FROM records"); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Account No</th>
<th>Info</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['acc_no']; ?></td>
<td><button id="inf" onclick="myFunction()">show</button></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>" class="edit_btn" >Edit</a>
</td>
<td>
Delete
</td>
</tr>
<tr id="sp"> <td colspan="4"><p> <?php echo $row['info']; ?> </p></td>
</tr>
<?php } ?>
</table>
<div id="fotable" align="center">
<button id="fo">Add New/Edit</button>
</div>
<form method="post" action="php_code.php" >
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>Name</label>
<input type="text" autocomplete="off" name="name" value="<?php echo $name; ?>">
</div>
<div class="input-group">
<label>Account No</label>
<input type="text" name="acc" value="<?php echo $acc; ?>">
</div>
<div class="input-group">
<label for="info">Info</label>
<textarea class="form-control" rows="8" name="info" id="info"><?php echo $row['info']; ?></textarea>
</div>
<div class="input-group">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Add Account</button>
<?php endif ?>
</div>
</form>
</div><!-- left closed -->
<div class="right">
hello
</div> <!-- right closed -->
</div> <!-- container closed -->
</body>
</html>
---php_code.php-----
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'jskrecords');
// initialize variables
$name = "";
$acc = "";
$info = "";
$id = 0;
$update = false;
if (isset($_POST['save'])) {
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "INSERT INTO records (name, acc_no, info) VALUES ('$name', '$acc', '$info')");
$_SESSION['message'] = "Account saved";
header('location: index.php');
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "UPDATE records SET name='$name',acc_no='$acc',info='$info' WHERE id=$id");
$_SESSION['message'] = "Account updated!";
header('location: index.php');
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM records WHERE id=$id");
$_SESSION['message'] = "ACC deleted!";
header('location: index.php');
}
?>
Concept:
If you are creating multiple form from same mysql table using php script, You need to give each form a unique id.
e.g.
<form method="post" action="php_code.php" id="form<?= $id ?>">
Then add data-target="#form" to button with class 'inf'. It will store id of form.
<button class="inf" data-target="#form<?= $id ?>">show</button>
When button is clicked we know which form to open from data-target.
<script>
$('.container').on('click','button.inf',function(e){
e.preventDefault();
var formid=$(this).attr('data-target'); //get value of data-target attribute
//...proceed to play toggle with this form 'formid'
Related
I am new in JavaScript i don't know how to do ajax in pagination. is there anyone who can help me out on ajax in pagination. I write normal code of PHP and Ajax .
Thank you for your good support(:
i know that in ajax pagination is work on ClassName is active or not and replace the Inner HTML at the end but I don't know how can i do in my Code
this is my pagination.php file
<script type="text/javascript" src='../project/assets/js/ajax_pegination.js'></script>
<?php
include('../project/header.php');
include('../project/sidebar.php');
?>
<div class="body-contant">
<div class="main">
<table align="center">
<h2>Persnol information</h2>
<tr>
<div class="column">
<th>Id</th>
<th>firstName</th>
<th>lastName</th>
<th>email</th>
<th>mobileNo</th>
<th>gender</th>
<th>hobbies</th>
<th>Prewview</th>
<th>function</th>
</div>
</tr>
<?php
if (check_is_admin($_SESSION['id'])) {
$select = "SELECT * FROM form";
}
else{
$select = "SELECT * FROM form WHERE ID=".$_SESSION['id'];
}
$result= mysqli_query($conn, $select);
$total_rows= mysqli_num_rows($result);
$limit= 3;
$totalPages= ceil ($total_rows/$limit);
if (!isset ($_GET['page']) ) {
$pageNumber= 1;
} else {
$pageNumber= $_GET['page'];
}
$offset= ($pageNumber-1) * $limit;
if (check_is_admin($_SESSION['id'])) {
$select= "SELECT *FROM form LIMIT " . $offset . ',' . $limit;
}
$result= mysqli_query($conn, $select);
while($data = mysqli_fetch_assoc($result)) {
$extract=explode(',',$data['hobbies']);
$hobbies=[];
?>
<tr>
<td><?php echo $data['ID']; ?> </td>
<td><?php echo $data['first_name']; ?> </td>
<td><?php echo $data['last_name']; ?> </td>
<td><?php echo $data['email']; ?> </td>
<td><?php echo $data['mobile_no']; ?> </td>
<td><?php echo $data['gender']; ?> </td>
<?php
foreach($extract as $hobbiesId){
$select1 = "SELECT * from hobbies WHERE `ID` IN ($hobbiesId)";
$result1=mysqli_query($conn,$select1);
while($data1=mysqli_fetch_assoc($result1)){
$hobbies[] = $data1['name'];
}
}
?>
<td><?php echo implode(",", $hobbies); ?> </td>
<td><img src="..\project\assets\uploads\<?php echo $data['file_path'] ?>" id="preview" alt="img"></td>
<div class="btn">
<td>
<a class="button1" type="button" name="edit" href="..\project\edit_user.php?id=<?php echo $data['ID']; ?>">Edit</a>
<a class="button2" type="button" name="delete" href="../project/delete_user.php?id=<?php echo $data['ID']; ?>" onclick="return confirm('are you sure you want to delete??');">Delete</a>
</td>
</div>
</tr>
<?php
}
?>
</table>
<!-- --------------------------------------------------------- -->
<div class="pagination">
<?php
if (check_is_admin($_SESSION['id'])) {
$pageURL = "";
if($pageNumber>=2){
echo "<a class='prev' href='pagination.php?page=".($pageNumber-1)."' onchange='load()'> Prev </a>";
}
for ($i=1; $i<=$totalPages; $i++) {
if ($i == $pageNumber) {
$pageURL .= "<a class = 'active' href='pagination.php?page=" .$i."'>".$i." </a>";
}
else {
$pageURL .= "<a href='pagination.php?page=".$i."'>".$i." </a>";
}
};
echo $pageURL;
if($pageNumber<$totalPages){
echo "<a class='next' href='pagination.php?page=".($pageNumber+1)."'> Next </a>";
}
}
?>
</div>
<!-- ------------------------------------------------------- -->
</div>
</div>
<?php
include('../project/footer.php');
?>
and this my AJAX_pagination.js file
// document.getElementsByClassName("prev").addEventListener("change", (event) => {
// event.preventDefault();
// load();
// });
function load(){
var httpx = new XMLHttpRequest();
httpx.onreadystatechange = function(){
if(this.readyState==4 && this.status==200){
console.log(this);
document.getElementsByClassName("prev").innerHTML=this.responseText;
}
}
httpx.open("POST", "http://localhost/project/pagination.php", true);
httpx.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpx.send();
}
JQuery connected, AJAX probably works correctly, because when I change select in the console the values are correct. But the query to the database doesn't change. Checking var_dump($_POST['filter']) shows that there value from previous request.
If I wrap select in a form and send it via POST using submit button, the requests are sent.
Where can there be an error here?
And how to add a condition, so that when selecting "All" the query will just be to all items "SELECT * FROM orders, without the condition "WHERE?
<script>
$('#filter').change(function() {
$.ajax({
method: "POST",
url: "thispage.php",
data: {
filter: $("#filter").val()
},
success: function(response) {
console.log($("#filter").val())
}
});
});
</script>
<?php
require_once __DIR__ . "/database/database.php";
$item1 = $_POST['item1'];
$worker_name = $_POST['worker_name'];
$worker_company = $_POST['worker_company'];
$errors = [];
if (empty($item1)) {
$errors['item1'] = true;
}
if (empty($errors)) {
$sql = "INSERT INTO `orders`(`order_dish1`, `order_name_worker`, `order_company`) VALUES (:order1, :order_name_worker, :worker_company)";
$params = [
"order1" => $item1,
"order_name_worker" => $worker_name,
"worker_company" => $worker_company
];
$dbh->prepare($sql)->execute($params);
}
$order_dishes1 = [];
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
// In this form it works
<form action="thispage.php" method="POST">
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
<button type="submit">submit</button>
</form>
<div class="orders__wrapper" id="result">
<?php
$company = $_POST['filter'];
var_dump($_POST['filter']);
$sql = "SELECT * FROM `orders` WHERE `order_company` = '$company'";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<div class="order-items">
<div class="order-items__header">
<div class="order-items__wrapper">
<div class="order-items__number">
Order №: <?php echo $row['order_id'] ?> </div>
</div>
<div class="order-items__wrapper">
<div class="order-items__name">
<?php echo $row['order_name_worker'] ?> </div>
<div class="order-items__company">
Company:
<span>
<?php echo $row['order_company'] ?>
</span>
</div>
</div>
</div>
<div class="order-items__orders">
<div class="orders-item orders-item-1">
Order №1:
<span class="order1">
<?php echo $row['order_dish1'] ?>
</span>
</div>
</div>
</div>
<?php
$order_dishes1[] = $row['order_dish1'];
}
$content = ob_get_contents();
ob_end_clean();
?>
<div class="result__all" id="result__all">
<div class="result__all-company">
<?php echo $row['order_company'] ?>
</div><br>
<div class="result__all__wrapper">
<div class="result__all-view">
<div class="result__all-title">
Soups:
</div>
<?php
$count_dishes1 = array_count_values($order_dishes1);
foreach ($count_dishes1 as $key => $val) echo '<div class="result__all-item">' . $key . ' - ' . $val . ' шт.,</div>';
?>
</div><br>
</div>
</div>
<?= $content ?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>
Hello I have some data in mysql table, like this:
name----cake----image_design
explosion----cheesecake----images/cake/sofia.png
I have all images of the designs in a folder (/cake)
In my php document I get the data:
<?php
session_start();
include "../config/config.php";//Contiene funcion que conecta a la base de datos
if (!isset($_SESSION['user_id'])&& $_SESSION['user_id']==null) {
// header("location: index.php");
}
$id_conect=$_SESSION['user_id'];
$query3=mysqli_query($con, "SELECT * from user where id='$id_conect'");
while ($rs=mysqli_fetch_array($query3))
{
$tipo=$rs['tipo'];
}
$action = (isset($_REQUEST['action']) && $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if (isset($_GET['id'])){
$id_del=intval($_GET['id']);
$query=mysqli_query($con, "SELECT * from pedido where id_pedido='".$id_del."'");
$count=mysqli_num_rows($query);
if ($delete1=mysqli_query($con,"DELETE FROM pedido WHERE id_pedido='".$id_del."'")){
?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Aviso!</strong> Datos eliminados exitosamente.
</div>
<?php
}else {
?>
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Error!</strong> Lo siento algo ha salido mal intenta nuevamente.
</div>
<?php
} //end else
} //end if
?>
<?php
if($action == 'ajax'){
// escaping, additionally removing everything that could be (html/javascript-) code
$q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
$aColumns = array('cliente');//Columnas de busqueda
$sTable = "pedido";
$sWhere = "";
if ( $_GET['q'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".$q."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
$sWhere.=" order by created_at desc";
include 'pagination.php'; //include pagination file
//pagination variables
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
$per_page = 10; //how much records you want to show
$adjacents = 4; //gap between pages after number of adjacents
$offset = ($page - 1) * $per_page;
//Count the total number of row in your table*/
$count_query = mysqli_query($con, "SELECT count(*) AS numrows FROM $sTable $sWhere");
$row= mysqli_fetch_array($count_query);
$numrows = $row['numrows'];
$total_pages = ceil($numrows/$per_page);
$reload = './expences.php';
//main query to fetch the data
$sql="SELECT * FROM $sTable $sWhere LIMIT $offset,$per_page";
if($tipo==1|| $tipo==3)
{
$query = mysqli_query($con, $sql);
}else
{
$query=mysqli_query($con, "select * from pedido where id_usuario= $id_conect");
}
//loop through fetched data
if ($numrows>0){
?>
<table class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th class="column-title">Cliente </th>
<th>Fecha</th>
<th class="column-title">Tienda </th>
<th class="column-title no-link last"><span class="nobr"></span></th>
</tr>
</thead>
<tbody>
<?php
while ($r=mysqli_fetch_array($query)) {
$id=$r['id_pedido'];
$created_at=date('Y-m-d H:i:s', strtotime($r['created_at']));
// $description=$r['description'];
// $nombre=$r['nombre_ticket'];
// $solucion=$r['solucion'];
// $soporte=$r['soporte'];
// $title=$r['title'];
// $priority_id=$r['priority_id'];
$status_id=$r['id_status'];
// $kind_id=$r['kind_id'];
// $category_id=$r['category_id'];
$Cliente=$r['cliente'];
$project_id=$r["project_id"];
$encargada=$r["nombre_pedido"];
$producto_id=$r["id_producto"];
$cantidad=$r["cantidad"];
$biscocho=$r["biscocho"];
$relleno=$r["id_relleno"];
$design=$r["id_design"];
$opcion=$r["opcion"];
$observacion=$r["observacion"];
$dedicatoria=$r["dedicatoria"];
$c_fondo=$r["color_fondo"];
$c_chongo=$r["color_chongo"];
$c_rosas=$r["color_rosas"];
$figura=$r["figura"];
$c_figura=$r["color_figura"];
$hora=$r["hora"];
$cliente=$r["cliente"];
$telefono=$r["telefono"];
$entrega =$r['fecha_entrega'];
$imagen =$r["id_design"];
$sql = mysqli_query($con, "select * from project where id=$project_id");
if($c=mysqli_fetch_array($sql)) {
$name_project=$c['name'];
}
// $sql = mysqli_query($con, "select * from priority where id=$priority_id");
// if($c=mysqli_fetch_array($sql)) {
// $name_priority=$c['name'];
// }
$sql = mysqli_query($con, "select * from status where id=$status_id");
if($c=mysqli_fetch_array($sql)) {
$name_status=$c['name'];
}
?>
<input type="hidden" value="<?php echo $id;?>" id="id<?php echo $id;?>">
<input type="hidden" value="<?php echo $created_at;?>" id="fecha<?php echo $id;?>">
<input type="hidden" value="<?php echo $project_id;?>" id="project_id<?php echo $id;?>">
<input type="hidden" value="<?php echo $Cliente;?>" id="cliente<?php echo $id;?>">
<input type="hidden" value="<?php echo $encargada;?>" id="encargada<?php echo $id;?>">
<!-- me obtiene los datos -->
<input type="hidden" value="<?php echo $producto_id;?>" id="producto_id<?php echo $id;?>">
<input type="hidden" value="<?php echo $cantidad;?>" id="cantidad<?php echo $id;?>">
<input type="hidden" value="<?php echo $biscocho;?>" id="biscocho<?php echo $id;?>">
<input type="hidden" value="<?php echo $relleno;?>" id="relleno<?php echo $id;?>">
<input type="hidden" value="<?php echo $design;?>" id="design<?php echo $id;?>">
<input type="hidden" value="<?php echo $status_id;?>" id="status_id<?php echo $id;?>">
<input type="hidden" value="<?php echo $opcion;?>" id="opcion<?php echo $id;?>">
<input type="hidden" value="<?php echo $observacion;?>" id="observacion<?php echo $id?>">
<input type="hidden" value="<?php echo $dedicatoria;?>" id="dedicatoria<?php echo $id?>">
<input type="hidden" value="<?php echo $c_fondo;?>" id="c_fondo<?php echo $id?>">
<input type="hidden" value="<?php echo $c_chongo;?>" id="c_chongo<?php echo $id?>">
<input type="hidden" value="<?php echo $c_rosas;?>" id="c_rosas<?php echo $id?>">
<input type="hidden" value="<?php echo $figura;?>" id="figura<?php echo $id ?>">
<input type="hidden" value="<?php echo $entrega;?>" id="entrega<?php echo $id ?>">
<input type="hidden" value="<?php echo $hora;?>" id="hora<?php echo $id ?>">
<input type="hidden" value="<?php echo $cliente;?>" id="cliente<?php echo $id ?>">
<input type="hidden" value="<?php echo $telefono;?>" id="telefono<?php echo $id ?>">
<input type="hidden" value="<?php echo $imagen;?>" id="imagen<?php echo $id ?>">
<tr class="even pointer">
<td><?php echo $cliente;?></td>
<td><?php echo $created_at;?></td>
<td><?php echo $project_id;?></td>
<td ><span class="pull-right">
<i class="glyphicon glyphicon-edit"></i>
</span></td>
</tr>
<?php
} //en while
?>
<tr>
<td colspan=6><span class="pull-right">
<?php echo paginate($reload, $page, $total_pages, $adjacents);?>
</span></td>
</tr>
</table>
</div>
<?php
}else{
?>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Aviso!</strong> No hay datos para mostrar!
</div>
<?php
}
}
?>
Then in another archive.php, I receive the variables like this:
<script>
function obtener_datos(id){
var soporte = $("#soporte"+id).val();
var encargada = $("#encargada"+id).val();
var producto_id = $("#producto_id"+id).val();
var cantidad = $("#cantidad"+id).val();
var biscocho = $("#biscocho"+id).val();
var relleno = $("#relleno"+id).val();
var design = $("#design"+id).val();
var opcion = $("#opcion"+id).val();
var observacion =$("#observacion"+id).val();
var dedicatoria =$("#dedicatoria"+id).val();
var c_fondo = $("#c_fondo"+id).val();
var c_chongo =$("#c_chongo"+id).val();
var c_rosas =$("#c_rosas"+id).val();
var figura =$("#figura"+id).val();
var entrega =$("#entrega"+id).val();
var hora =$("#hora"+id).val();
var cliente =$("#cliente"+id).val();
var telefono =$("#telefono"+id).val();
var kind_id = $("#kind_id"+id).val();
var project_id = $("#project_id"+id).val();
var category_id = $("#category_id"+id).val();
var priority_id = $("#priority_id"+id).val();
var status_id = $("#status_id"+id).val();
var imagen =$("#imagen"+id).val();
$("#mod_id").val(id);
$("#mod_encargada").val(encargada);
$("#mod_producto_id").val(producto_id);
$("#mod_cantidad").val(cantidad);
$("#mod_biscocho").val(biscocho);
$("#mod_relleno").val(relleno);
$("#mod_design").val(design);
$("#mod_opcion").val(opcion);
$("#mod_observacion").val(observacion);
$("#mod_dedicatoria").val(dedicatoria);
$("#mod_c_fondo").val(c_fondo);
$("#mod_c_chongo").val(c_chongo);
$("#mod_c_rosas").val(c_rosas);
$("#mod_figura").val(figura);
$("#mod_entrega").val(entrega);
$("#mod_hora").val(hora);
$("#mod_cliente").val(cliente);
$("#mod_telefono").val(telefono);
$("#mod_soporte").val(soporte);
$("#mod_kind_id").val(kind_id);
$("#mod_project_id").val(project_id);
$("#mod_category_id").val(category_id);
$("#mod_priority_id").val(priority_id);
$("#mod_status_id").val(status_id);
$("#mod_imagen").val(imagen);
}
</script>
Below #mod_name and #mod_cake is the id of text box.
<div class="col-md-9 col-sm-9 col-xs-12">
<input type="text" style="width:150px; float:left;"name="encargada" id="**mod_cake**"class="form-control">
</div>
</div>
</div>
Now my problem is with the image, because return me images/cake/sofia.png and I don't know how I show that image
I try with this:
<img id ="mod_imagen"src="">
but does not work.
i solve that wiht this:
javascript:
var imagen =$("#imagen"+id).val();
document.getElementById("imagenid").src=imagen;
other php:
<img id="imagenid"src="" />
Having the image itself in you database may slow down your queries. Instead, consider storing the image name in the database and the image itself as you usually would: a file in a directory. Then, with Javascript:
document.getElementById("**mod_cake**").src = "<?php echo $filename; ?>";
I just started to learn how to program and I have been having issues with ajax when it comes to adding items to my cart. Everything is fine when it comes to adding items, its the ajax that is not working and my page constantly keeps refreshing. For the code since there is a lot of it I will put the things I think are the most important.
Index.php
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title></title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.add_to_cart', function(){
var product_id = $(this).attr("id");
var product_name = $('#name'+product_id+'').val();
var product_price = $('#price'+product_id+'').val();
var product_quantity = $('#quantity'+product_id).val();
if(product_quantity > 0)
{
$.ajax({
url:"index.php",
method:"POST",
data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity},
success:function(data)
{
alert("Item has been Added into Cart");
}
});
}
else
{
alert("lease Enter Number of Quantity");
}
});
});
</script>
</head>
<body>
<header>
<?php
include_once'widget/header.php';
if (isset($_SESSION['u_id'])) {
include_once"include/addcart.php";
include_once "widget/shoppingcart.php";
}
?>
</header>
<main>
<div class="item-container">
<?php
$item = mysqli_query($db,"SELECT * FROM itemlist ORDER BY title");
include_once 'widget/container.php';
?>
</div>
</main>
Addcart.php
<?php
$row_ids = array();
//session_destroy();
//check if Add to Cart button has been submitted
if(filter_input(INPUT_POST, 'add_to_cart')){
if(isset($_SESSION['shopping_cart'])){
//keep track of how mnay products are in the shopping cart
$count = count($_SESSION['shopping_cart']);
//create sequantial array for matching array keys to products id's
$row_ids = array_column($_SESSION['shopping_cart'], 'id');
if (!in_array(filter_input(INPUT_POST, 'id'), $row_ids)){
$_SESSION['shopping_cart'][$count] = array
(
'id' => filter_input(INPUT_POST, 'id'),
'name' => filter_input(INPUT_POST, 'name'),
'price' => filter_input(INPUT_POST, 'price'),
'quantity' => filter_input(INPUT_POST, 'quantity')
);
// header("Location:index.php?addedtocart");
}
else { //product already exists, increase quantity
//match array key to id of the product being added to the cart
for ($i = 0; $i < count($row_ids); $i++){
if ($row_ids[$i] == filter_input(INPUT_POST, 'id')){
//add item quantity to the existing product in the array
$_SESSION['shopping_cart'][$i]['quantity'] += filter_input(INPUT_POST, 'quantity');
// header("Location:index.php?multtocart");
}
}
}
}
else { //if shopping cart doesn't exist, create first product with array key 0
//create array using submitted form data, start from key 0 and fill it with values
$_SESSION['shopping_cart'][0] = array
(
'id' => filter_input(INPUT_POST, 'id'),
'name' => filter_input(INPUT_POST, 'name'),
'price' => filter_input(INPUT_POST, 'price'),
'quantity' => filter_input(INPUT_POST, 'quantity')
);
}
}
if (filter_input(INPUT_POST, 'delete')) {
//loop thru intil products in shop cart == variable
foreach ($_SESSION['shopping_cart'] as $key => $row) {
if ($row['id'] == filter_input(INPUT_POST, 'id')) {
unset($_SESSION['shopping_cart'][$key]);
}
}
$_SESSION['shopping_cart'] =array_values($_SESSION['shopping_cart']);
}
?>
Shoppingcart.php
<div class="cart-container" align="right">
<div class="table-responsive">
<table class="table">
<table class="table">
<tr><th colspan="5"><h5>Order Details</h5></th></tr>
<tr>
<th width="40%">Product Name</th>
<th width="10%">Quantity</th>
<th width="20%">Price</th>
<th width="15%">Total</th>
<th width="5%">Action</th>
</tr>
<?php
if(!empty($_SESSION['shopping_cart'])):
$total = 0;
foreach($_SESSION['shopping_cart'] as $key => $product):
?>
<tr>
<td><?php echo $product['name']; ?></td>
<td><?php echo $product['quantity']; ?></td>
<td>$ <?php echo $product['price']; ?></td>
<td>$ <?php echo number_format($product['quantity'] * $product['price'], 2); ?></td>
<td>
<form method="post">
<input class="delete" type="submit" name="delete" value="Delete">
<input type="hidden" name="id" value="<?php echo $product['id']; ?>">
</form>
</td>
</tr>
<?php
$total = $total + ($product['quantity'] * $product['price']);
endforeach;
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<tr>
<!-- Show checkout button only if the shopping cart is not empty -->
<td colspan="5">
<?php
if (isset($_SESSION['shopping_cart'])):
if (count($_SESSION['shopping_cart']) > 0):
?>
Checkout
<?php endif; endif; ?>
</td>
</tr>
<?php
endif;
?>
</table>
</div>
</div>
Container.php
<?php
while ($row = mysqli_fetch_assoc($item)) {
?>
<div class='item-box'>
<img class='item_img' src="itemimg/<?php echo $row['img']; ?>"><figcaption><?php echo $row['title']; ?></ficgcaption>
<form method="post" class="add-form">
<div class='input-group xs-2'>
<input class="form-control" type="text" id="quantity<?php echo $row['id'] ?>" name="quantity" value="1">
<input class="btn btn-outline-primary btn-sm add-btns add_to_cart" type="submit" id="<?php echo $row['id'] ?>" name="add_to_cart" value="Add To Cart">
</div>
<input type="hidden" id="name<?php echo $row['id'] ?>" name="name" value="<?php echo $row['title'] ?>">
<input type="hidden" id="price<?php echo $row['id'] ?>" name="price" value="<?php echo $row['price']; ?>">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
</div>
</form>
<?php
}
?>
Your page will refresh because you are not telling your form to not submit by the default method (which is to reload the page as a POST). To stop the page from reloading and let ajax do the submission, you need to inject the event and then use preventDefault():
$(document).on('click', '.add_to_cart', function(e){
// This will stop the form from submitting and allow the rest of the
// ajax to continue working. If you don't have this, you will immediately
// submit the form which negates the use of ajax
e.preventDefault();
i create a form(form1) to search mysql data into table without reload the page using ajax, it's working fine, but when i want to insert data from the second form(formorder) the submit button not refresh or reload.
this my code
index.php
<html>
<head>
<title>Search Data Without Page Refresh</title>
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
</head>
<body>
<center>
<br>
<?php include("koneksi1.php");
$sql="select * from supplier";
$query=mysqli_query($koneksi,$sql);
?>
<form action="" name = "form1">
<select name="namea" style="width:300px; padding:8px;">
<?php
while($data=mysqli_fetch_assoc($query)){
echo "<option value='".$data['id_supplier']."'>".$data['id_supplier']."</option>";
}
?>
</select>
<input type="submit" value="Search" id="search-btn" style="padding:8px;"/>
</form>
<br>
<div id = "s-results">
<!-- Search results here! -->
</div>
<script type = "text/javascript">
$(document).ready(function(){
$('#s-results').load('search.php').show();
$('#search-btn').click(function(){
showValues();
});
$(function() {
$('form').bind('submit',function(){
showValues();
return false;
});
});
function showValues() {
$.post('search.php', { namea: form1.namea.value },
function(result){
$('#s-results').html(result).show();
});
}
});
</script>
</center>
</body>
</html>
search.php
<?php
include("koneksi1.php");
isset( $_REQUEST['namea'] ) ? $name=$_REQUEST['namea'] : $name='';
$name = mysqli_real_escape_string($koneksi,$name);
if( empty( $name )){
echo '<script> alert("Please search something!")</script>';
}else{
$sql = "select * from barang where id_supplier like '%$name%'";
$rs = mysqli_query($koneksi,$sql ) or die('Database Error: ' . mysql_error());
$num = mysqli_num_rows($rs);
if($num >= 1 ){
echo "<div style='margin:10px; color:green; font-weight: bold;'>$num records found!</div>";
echo "<table width='365' border ='0' cellspacing='5' cellpadding='5'>";
echo"<tr><th>RESULTS</th></tr>";
echo "<div class='table-responsive'>";
echo "<table class='table table-hover'>";
while($data = mysqli_fetch_array( $rs )){
?>
<tbody>
<?php
$kuantitas=0;
$kuantitas++;
?>
<form action="aksi.php" method="post" id="formorder">
<tr>
<td><?php echo $data['nama_barang']?></td>
<td><?php echo $data['stok']?></td>
<td><input type="text" name="kuantitas" size="4"></td>
<td><input type="text" name="harga_satuan" id="harga_satuan" size="10"></td>
<td><input type="text" name="ppn" id="ppn" size="3"> %</td>
<td><button type="submit" class="btn btn-success btn-sm" id="add" name="add">ADD</button></td>
</tr>
</form>
<?php }?>
</tbody>
</table>
</div>
<?php
}else{
echo "<tr><th>NO RESULTS</th></tr>";
}
}
?>
the button submit in formorder not working, what wrong with my code???