How to fix ReferenceError jQuery? - javascript

I cant find the error from my code,took me hours trying to figure it out but still cant make it work.
I've checked on the browser console and it shows as ascreenshot below :
Here's my code :
<?php
session_start();
use Phpml\Classification\SVC;
use Phpml\SupportVectorMachine\Kernel;
include "koneksi.php";
include "function.php";
if(!isset($_SESSION['username'])){
header('location:login.php');
}else{
$username = $_SESSION['username'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Pelatihan SVM</title>
<link rel="stylesheet" type="text/css" href="styles/2nd.css">
<script src="jquery-3.1.1.min.js"></script>
<?php
cekUser();
?>
</head>
<body>
<div class="tab">
<button class="menuTab" onclick="switchMenu(event, 'useDatabase')" id="admin">Data Mentah</button>
<button class="menuTab" onclick="switchMenu(event, 'term')" id="nonAdmin">Data Feature Selection</button>
</div>
<div id="useDatabase" class="tabContent">
<?php
$start=0;
$limit=100;
if(isset($_GET['id'])){
$id=$_GET['id'];
$start=($id-1)*$limit;
}else{
$id=1;
}
$q = mysqli_query($db, "SELECT * FROM dataset_latih LIMIT $start, $limit")or die(mysqli_error($db));
$no=$start+1;
$q1=mysqli_query($db, "SELECT COUNT('label') AS 'label positif' FROM dataset_latih WHERE label='positif'");
$row=mysqli_fetch_assoc($q1);
$positif=$row['label positif'];
$q2=mysqli_query($db, "SELECT COUNT('label') AS 'label negatif' FROM dataset_latih WHERE label='negatif'");
$row2=mysqli_fetch_assoc($q2);
$negatif=$row2['label negatif'];
?>
<h2 align="center">Dataset Latih</h2>
<h3 style="text-align: center;">Positif : <?php echo $positif; ?> | Negatif : <?php echo $negatif; ?> | Total : <?php echo $positif+$negatif; ?></h3>
<table border=1 align="center" class="h-header">
<thead>
<tr>
<th width="25">No.</th>
<th width="1200">Komentar</th>
<th width="70">Kelas</th>
</tr>
</thead>
<?php
while ( $result = mysqli_fetch_assoc($q) ) {
echo "<tr>";
echo "<td>" . $no . "</td>";
echo "<td class='kiri'>" . $result['komentar'] . "</td>";
echo "<td>" . $result['label'] . "</td>";
echo "</tr>";
$no++;
}
?>
</table>
<div class='wrapper'>
<button class='button' id="prosesData">Proses</button>
</div>
<div class="paging" style="text-align: center;">
<?php
$rows=mysqli_num_rows(mysqli_query($db, "SELECT * FROM dataset_latih"));
$total=ceil($rows/$limit);
if ($id>1) {
echo "<a href='?id=".($id-1)."' class='button' id='table1'>Previous </a>";
}
for ($i=1; $i <=$total ; $i++) {
if ($i==$id) {
echo "<span class='active'>$i</span>";
}else{
echo "<a href='?id=".$i."' id='table1'> ".$i." </a>";
}
}
if ($id!=$total) {
echo "<a href='?id=".($id+1)."' class='button' id='table1'> Next</a>";
}
?>
</div>
</div>
<div id="term" class="tabContent">
<h2 align="center">Term Latih</h2>
<?php
$start=0;
$limit=100;
if(isset($_GET['id1'])){
$id1=$_GET['id1'];
$start=($id1-1)*$limit;
}else{
$id1=1;
}
$q = mysqli_query($db, "SELECT * FROM data_latih_ready LIMIT $start, $limit")or die(mysqli_error($db));
$no=$start+1;
$rowPersentase = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM selected_feature"))or die(mysqli_error($db));
$persentase = $rowPersentase['persentase'];
$td1 = '';
$td2 = '';
$td3 = '';
while ($row1 = mysqli_fetch_assoc($q)) {
$td1 .= "<td>$no</td>";
$td2 .= "<td>".$row1['term']."</td>";
$td3 .= "<td>".$row1['tf_idf_normalisasi']."</td>";
$no++;
}
?>
<h3 style="text-align: center;">Feature Selection : <?php echo $persentase; ?>%</h3>
<div class="v-header">
<table border="1" align="center" cellpadding="20">
<thead>
<tr>
<th>No.</th>
<?php echo $td1; ?>
</tr>
<tr>
<th>Term</th>
<?php echo $td2; ?>
</tr>
<tr>
<th>Normalisasi TF.IDF</th>
<?php echo $td3; ?>
</tr>
</thead>
</table>
</div>
<!-- <br> -->
<div class="paging2" style="text-align: center;">
<?php
$rows=mysqli_num_rows(mysqli_query($db, "SELECT * FROM data_latih_ready"));
$total=ceil($rows/$limit);
if ($id1>1) {
echo "<a href='?id1=".($id1-1)."' class='button' id='table2'>Previous </a>";
}
for ($i=1; $i <=$total; $i++) {
if ($i==$id1) {
echo "<span class='active'>$i</span>";
}else{
echo "<a href='?id1=".$i."' id='table2'> ".$i." </a>";
}
}
if ($id1!=$total) {
echo "<a href='?id1=".($id1+1)."' class='button' id='table2'> Next</a>";
}
?>
<div class="btnFeature">
<ul>
<li>
<button class="button" onclick="train();">Latih SVM</button>
</li>
<li>
<button class="button" id="featureSelection">Feature Selection</button>
</li>
</ul>
</div>
</div>
</div>
<div class="info" align="center">
<p>Tabel di atas merupakan tabel term dengan nilai yang telah disesuaikan dengan nilai <strong>Feature Selection</strong><br>
Silahkan menekan tombol <strong>Latih SVM</strong> jika <strong>Feature Selection</strong> sudah sesuai kebutuhan.
</p>
</div>
<?php
$cek = cekTabelToken();
?>
<script type="text/javascript">
// biar otomatis tab aktif waktu halaman svmLatih.php dibuka
document.getElementById("admin").click();
$(".info").hide();
$("#admin").click(function(){
$(".info").hide();
});
$("#nonAdmin").click(function(){
$(".info").show();
});
// var untuk cek tabel term kosong gk
var cek = "<?php echo "$cek"; ?>"
$("#prosesData").click(function(){
// kalau tabel term gk kosong, alert mau proses ulang gk
if (cek > 0) {
var conf = confirm("Preprocessing data latih sudah pernah dilakukan.\nIngin memproses ulang ?");
if (conf == true) {
$.ajax({
url: "action.php",
data:{action: "prosesUlangDataLatih"},
type: "POST",
// kalau berhasil kasih alert lalu redirect
success: function(){
alert("Preprocessing ulang selesai.");
setTimeout(function(){
window.location.href = 'featureSelection.php';
},1000);
}
});
}
}else{
// kalau tabel term kosong ya langsung aja proses
$.ajax({
url: "action.php",
data:{action: "preprocessing"},
type: "POST",
// kalau berhasil kasih alert lalu redirect
success: function(){
alert("Preprocessing selesai.");
setTimeout(function(){
window.location.href = 'featureSelection.php';
},1000);
}
});
}
});
// fungsi untuk switch tab
function switchMenu(evt, selectedMenu){
var i, tabContent, menuTab;
tabContent = document.getElementsByClassName("tabContent");
for (i = 0; i < tabContent.length; i++) {
tabContent[i].style.display = "none";
}
menuTab = document.getElementsByClassName("menuTab");
for(i = 0; i < menuTab.length; i++){
menuTab[i].className = menuTab[i].className.replace(" active", "");
}
document.getElementById(selectedMenu).style.display = "block";
evt.currentTarget.className += " active";
}
// tombol feature selection
$("#featureSelection").click(function(){
window.location = "featureSelection.php";
});
// tombol latih SVM
function train(){
$.ajax({
type: "POST",
url: "action.php",
data:{
action: "trainDatabase"
},
success: function(){
alert("Model SVM sudah dibuat.");
},
error: function(){
alert("Error");
}
});
}
</script>
</body>
</html>
I hope someone can help me to find the error, I've been stuck here for hours. Thank you.

Related

Sweetalert won't show but it will update

I want to show a sweetalert after clicking the set button but it won't function. This is my index page and the set button can function but it won't show the sweet alert. what might be the problem and what should I do?
index.php
<form method='post' action='updataStatus.php'>
<button type='submit' name='but_update' class="inline-block float ml-2 mt-1 btn-group pull-right btn-danger btn-sm">SET</button><button type="submit" id="dataExport" name="dataExport" value="Export to excel" class="inline-block float ml-2 mt-1 btn-group pull-right btn-info btn-sm">Export</button>
<div class="table-responsive">
<br>
<tbody><table class="table table-hover table-bordered" id="sampleTable2">
<thead>
<tr>
<th><input type="checkbox" class="select-all checkbox" name="select-all" id="checkAll" /></th>
<th>Name</th>
<th>Scholarship Program</th>
<th>Course</th>
<th>Semester</th>
<th>Allowance</th>
</tr>
</thead>
<?php
require_once "connection.php";
$query = "SELECT * FROM allowance";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result) ){
$id = $row['id'];
$Name = $row['Name'];
$Scholarship = $row['Scholarship'];
$Course = $row['Course'];
$Semester = $row['Semester'];
$statusAllowance = $row['statusAllowance'];
?>
<tr>
<!-- Checkbox -->
<td><input type='checkbox' name='update[]' value='<?= $id ?>' ></td>
<td><p name="Name"><?php echo $row['Name']; ?></p></td>
<td><p name="Scholarship"><?php echo $row['Scholarship'] ?></p></td>
<td><p name="Course"><?php echo $row['Course'] ?></p></td>
<td><p name="Semester"><?php echo $row['Semester'] ?></p></td>
<td><p name='statusAllowance_<?= $id ?>'><?php echo $row['statusAllowance'] ?></td>
</tr>
<
?php
}
?>
</table>
</tbody>
<?php
if(isset($_SESSION['success']) && $_SESSION['success'] !='')
{
?>
<script type="text/javascript">
swal({
title: "<?php echo $_SESSION['success']; ?>",
icon: "<?php echo $_SESSION['status_code']; ?>",
button: "yissh",
});
</script>
<?php
unset($_SESSION['success']);
}
?>
This is my code on the edit part and this works, only the alert won't show up.
updataStatus.php
<?php
require_once "connection.php";
if(isset($_POST['but_update'])){
if(isset($_POST['update'])){
foreach($_POST['update'] as $id){
$statusAllowance = 'Received';
if($statusAllowance != '' ){
$updateUser = "UPDATE allowance SET statusAllowance='".$statusAllowance."' WHERE id=".$id;
$query_run = mysqli_query($conn,$updateUser);
if($query_run){
$_SESSION['success'] = "YOUR DATA UPDATED";
header('Location: tracking.php');
}else{
$_SESSION['success'] = "YOUR DATA IS NOT UPDATED";
header('Location: tracking.php');
}
}
}
}
}
?>
considering you have not implemented another function to call sweetalert; by default, it should be Swal.fire({}) not just swal({})
https://sweetalert2.github.io/

Pagination does not work on page2 in php web page

Can someone help me on pagination syntax for php webpage. I have a set a pagination code to display 20 records per page. The records are displaying based on 'start date' and 'end date'.
The issue is, it works on page 1 but when I click on page 2 in pagination then it won't work. I assume the values of $_POST['startdate'] and $_POST['enddate] are not forwarding on page2.
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="multitab/bootstrap.min.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<style>
.inline{
display: inline-block;
float: right;
margin: 20px 0px;
}
input, button{
height: 34px;
}
</style>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<table>
<tr>
<td><b>Start date:</b></td>
<td><input type="date" id="startdate" name="startdate" size="10"> </td>
<td><b>End date:</b></td>
<td><input type="date" id="enddate" name="enddate" size="10" max=<?php echo date('Y-m-d');?>></td>
<td><input type="submit" value="Search" name="Search" onClick="return check()"></td>
</tr>
</table>
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("abc_db",$con);
$limit = 20;
if (isset($_GET["page"])) {
$pn = $_GET["page"];
}
else {
$pn=1;
};
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
$start_from = ($pn-1) * $limit;
$serial = (($pn-1) * $limit) + 1;
$today1= date("Y/m/d");
$days14_ago = date('Y/m/d', mktime(0, 0, 0, date("m") , date("d") - 14, date("Y")));
if ($startdate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$startdate1' LIMIT $start_from, $limit";
} else if ($enddate1 !=Null) {
$sql = "SELECT * FROM hd where datearrival='$enddate1' LIMIT $start_from, $limit";
} else {
$sql = "SELECT * FROM hd where datearrival between '$days14_ago' and '$today1' LIMIT $start_from, $limit";
}
if (($startdate !=Null) && ($enddate !=Null)) {
$sql = "SELECT * FROM hd where datearrival between '$startdate1' and '$enddate1' LIMIT $start_from, $limit";
}
$rs_result = mysql_query ($sql);
?>
<div class="container">
<button style="height:25px;width:70px;" onclick="window.location.reload(true);">Refresh</button>
<br>
<div>
<font face='cambria'><p><span style="display:inline-block; margin-left: 650px; ">
</span></p> </font>
<font face="Cambria" size="2"> <table class="table table-striped table-condensed table-bordered">
<thead>
<tr>
<th width="5%" valign="top">Sr#</th>
<th width="10%" valign="top">Date arrival</th>
<th width="10%" valign="top">Pno</th>
<th width="10%" valign="top">First name</th>
<th valign="top"></th>
<th valign="top"></th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_array($rs_result, MYSQL_ASSOC)) {
$pno1=$row['pno'];
$datearrival1=$row['datearrival'];
$sr_num = $serial++;
?>
<tr>
<td><?php echo $sr_num; ?></td>
<td><?php echo date("d/m/Y", strtotime($row['datearrival'])); ?></td>
<td><?php echo $row["pno"]; ?></td>
<td><?php echo $row["first_name"]; ?></td>
<td><p align="center">edit</font></td>
<td><p align="center">delete</font></td>
</tr>
<?php
};
?>
</tbody>
</table>
</font>
<div>
<ul class="pagination">
<?php
$sql = "SELECT COUNT(*) FROM hd where datearrival between '$startdate1' and '$enddate1'";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$k = (($pn+4>$total_pages)?$total_pages-4:(($pn-4<1)?5:$pn));
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."'> >> </a></li>";
}
?>
</ul>
<div class="inline">
<input id="pn" type="number" min="1" max="<?php echo $total_pages?>"
placeholder="<?php echo $pn."/".$total_pages; ?>" required>
<button onclick="go2Page();">Go</button>
</div>
</div>
</div>
</div>
<script>
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'qm.php?page='+pn;
}
/* start and end date- validation checks */
function check(){
var startdatea=document.getElementById("startdate").value;
var enddatea=document.getElementById("enddate").value;
if(Date.parse(startdatea)>Date.parse(enddatea)){
alert("Please select a different End Date.");
return false;
}
}
</script>
</body>
</html>
$_POST superglobal variable is populated by PHP when a POST HTTP request is processed. This is the case on the request for page 1.
However, your go2page() function is mutating location.href, which generates a GET HTTP request, and so does pagination links.
You should append your startdate and enddate params to the pagination URLs, to forward your params to the next/previous requests :
qm.php?page=<YOUR-PAGE-NUMBER>&startdate=<YOUR-START-DATE>&enddate=<YOUR-END-DATE>';
And use $_GET['startdate'] and $_GET['enddate] to retrieve those when processing GET requests.
More about $_POST https://www.php.net/manual/en/reserved.variables.post.php
More about GET AND POST HTTP requests : https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
There's an error in your isset($_POST['Search'])
your code:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
possible working solution:
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
}
Though I didn't try it yet, but I assume this is the cause, pagination in page2 will not work since the code is not executed after the error which is the pagination for page2.
EDIT: The . fixes things.
echo "Start date : ".$startdate1", ";
is different than
echo "Start date : ".$startdate1.", ";
Add values of your $_POST inside links and use them as $_GET so you would use both.
$startdate1=$enddate1=null; //to hide notice
if(isset($_POST['Search'])){
$startdate1 = $_POST['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_POST['enddate'];
echo "End date : ".$enddate1;
} else if (!empty($_GET['startdate']) && !empty($_GET['enddate'])){
$startdate1 = $_GET['startdate'];
echo "Start date : ".$startdate1.", ";
$enddate1 = $_GET['enddate'];
echo "End date : ".$enddate1;
}
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
For your need:
$pagLink = "";
if($pn>=2){
echo "<li><a href='qm.php?page=1&startdate=".startdate1."&enddate=".$enddate1."'> << </a></li>";
echo "<li><a href='qm.php?page=".($pn-1)."&startdate=".startdate1."&enddate=".$enddate1."'> < </a></li>";
}
for ($i=-4; $i<=4; $i++) {
if($k+$i==$pn)
$pagLink .= "<li class='active'><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
else
$pagLink .= "<li><a href='qm.php?page=".($k+$i)."&startdate=".startdate1."&enddate=".$enddate1."'>".($k+$i)."</a></li>";
};
echo $pagLink;
if($pn<$total_pages){
echo "<li><a href='qm.php?page=".($pn+1)."&startdate=".startdate1."&enddate=".$enddate1."'> > </a></li>";
echo "<li><a href='qm.php?page=".$total_pages."&startdate=".startdate1."&enddate=".$enddate1."'> >> </a></li>";
}
That would help you to move dates to next page.
You need to set it to all paging links. Also you can make extra if statement to not pass empty GET
EDIT:
As I already told: You need to set it to all paging links. Also you can make extra if statement to not pass empty GET (that includes javascript)
function go2Page()
{
var pn = document.getElementById("pn").value;
pn = ((pn><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((pn<1)?1:pn));
window.location.href = 'teztz.php?page='+pn+'&startdate=<?=startdate1;?>&enddate=<?=$enddate1;?>';
}

Load php page on div with JavaScript

Trying to load php results (from a different page) into a div on same page on link clicked
I have tried following the answer in here
But this didn't work for me. Below is what i have tried
price.php
<div class="pricepop"></div>
<?php
$sql = $db->prepare("SELECT * FROM commodityprices");
$result = $sql->execute();
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$id = $row['id'];
$_SESSION['id'] = $id;
$name = $row['name'];
$unit = $row['unit'];
$iprice = $row['iprice'];
$lprice = $row['lprice'];
$irate = $row['irate'];
$lrate = $row['lrate'];
$terms = $row['cterms'];
$asat = date('d/M/Y');
$market = $row['market'];
echo '<tr>
<td>'.$name.'</td>
<td>'.$unit.'</td>';
if ($irate == "Down")
{
echo '
<td style="background: #ef5a66; color: #fff"><i class="fa fa-caret-down"> </i> '.$iprice.'</td>';
}
else
{
echo '
<td style="background: #28bc88; color: #fff"><i class="fa fa-caret-up"> </i> '.$iprice.'</td>';
}
echo '<td>'.$terms.'</td>';
if ($lrate == "Down")
{
echo '
<td style="background: #ef5a66; color: #fff"><i class="fa fa-caret-down"> </i> '.$lprice.'</td>';
}
else
{
echo '
<td style="background: #28bc88; color: #fff"><i class="fa fa-caret-up"> </i> '.$lprice.'</td>';
}
echo '<td>'.$asat.'</td>
<td>'.$market.'</td>
<td><a class="comprice" href="pricedetails.php?id='.$id.'">View more</a>//Link to dispaly more results
</td>
</tr>';
}
pricedetails.php
<?php
$priceId = $_GET['id'];
$sql = $db->prepare("SELECT * FROM commodityprices WHERE id = ?");
$sql->bindParam(1, $priceId, SQLITE3_INTEGER);
$result = $sql->execute();
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$id = $row['id'];
$name = $row['name'];
$iprice = $row['iprice'];
$lprice = $row['lprice'];
$lrate = $row['lrate'];
$terms = $row['cterms'];
$asat = date('d/M/Y');
$market = $row['market'];
$priceperbags = $row['priceperbags'];
echo '<tr>
<td>'.$name.'</td>';
echo '<td>'.$terms.'</td>';
if ($lrate == "Down")
{
echo '
<td style="background: #ef5a66; color: #fff"><i class="fa fa-caret-down"> </i> '.$lprice.'</td>';
}
else
{
echo '
<td style="background: #28bc88; color: #fff"><i class="fa fa-caret-up"> </i> '.$lprice.'</td>';
}
echo '<td>'.$asat.'</td>
<td>'.$market.'</td>
<td class="comprice">'.$priceperbags.'</td>
</tr>';
}
The JavaScript
$(document).ready(function() {
$(".comprice").on("click", function (e) {
e.preventDefault();
$(".pricepop").load("pricedetails.php");
});
});
When i click on the view more link in price.php the results in pricedeatils.php is supposed to display in the .pricepop div (which is in price.php page) but when i click currently the .pricepop is blank. Please how do i solve this issue? Thanks.
Your code isn't loading the correct url. Modified so id parameter is part of the url.
Use this js script instead.
$(document).ready(function() {
$(".comprice").on("click", function (e) {
e.preventDefault();
$(".pricepop").load($(this).attr('href'));
});
});

No popup window appear with paginated table

I have paginated table and input field. I want to allow user to create new process. Created table allow user to view already existed processes.
hmtl code:
<div class="inner">
<center><table class="paginated">
<?php
$result = getProcessData();
if (mysqli_num_rows($result) > 0)
{
echo '
<thead>
<tr>
<th>Process</th>
<th>Created By</th>
</tr>
</thead>';
}
$count = 0;
if (mysqli_num_rows($result) > 0)
while($row = mysqli_fetch_array($result))
{
$process = $row['theme_name'];
$createdBy = $row['createby'];
echo '
<tbody>
<tr valign="top">
<td>' .$process. '</td>
<td>' .$createdBy. '</td>
</tr>
</tbody>';
$count++;
}
?>
</table></center>
<form id="reguserform" method="post" action="process.php#err" style="margin-top:40px;">
<?php
$res = verifyFormFields();
?>
<!-- Username field -->
<input type="text" class="input name" placeholder="Process name (required)" name="process" required/>
<!--<label class="tooll tool1">- No special Characters except _<br>- Character Limit: 4 to 20<br>- Username must be Unique</label>-->
<center><input type="submit" class="button small" name="submit" value="Create Process"/></center>
<div id="registerModal" class="reveal-modal small" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog" data-options="close_on_background_click:false">
<h2 id="modalTitle">Success!</h2>
<div>
<div id="testRegister" style="font-weight: 400;font-size: 1.5em; font-family: 'Raleway', Arial, sans-serif;"></div>
<div class="right">
Ok
</div>
</div>
</div>
<?php
if($count == 1)
{
if($res=="")
{
registerProcess();
echo"<script>document.getElementById('testRegister').innerHTML=registerStr;callShowAlert();</script>";
}
else{
echo "
<a style='color:red';>
$res
</a>
";
}
}
?>
</form>
</div>
I validate the field and the inserting process into database:
function registerProcess(){
$con = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME);
global $process;
// To protect MySQL injection (more detail about MySQL injection)
$process = cleanInputData($process);
$process = mysqli_real_escape_string($con, $process);
//query result
$result = insertNewProcess(NULL,$process,$_SESSION['login_user'],1);
// Check result
if (!$result) {
$msg2= "Process is already added. You cannot add same process twice!";
echo $msg2;
die('Invalid queryyyy: ' . mysqli_error($con));
}
// the message
$msg = "Process is added!";
// use wordwrap() if lines are longer than 70 characters
echo "<script>var registerStr = 'Process Is Added';</script>";
//echo "<meta http-equiv='refresh' content='0'>";
}
function verifyFormFields(){
global $process;
if(empty($process)){
return "<p id ='err'>Please Input Process</p>";
}
else return "";
}
Also I use javascript to call pop up window and make table paginated:
<script type="text/javascript">
(function() {
$(document).foundation();
});
function callShowAlert()
{
$('#registerModal').foundation('reveal', 'open');
}
function popUpNo()
{
$('#registerModal').foundation('reveal', 'close');
location.href = 'process.php';
}
var testVal = 0;
</script>
<script>
$(document).ready(function() {
$('table.paginated').each(function() {
var currentPage = 0;
var numPerPage = 5;
var $table = $(this);
$table.bind('repaginate', function() {
$table.find('tbody tr').hide().slice(currentPage * numPerPage, (currentPage + 1) * numPerPage).show();
});
$table.trigger('repaginate');
var numRows = $table.find('tbody tr').length;
var numPages = Math.ceil(numRows / numPerPage);
var $pager = $('<div class="pager"></div>');
for (var page = 0; page < numPages; page++) {
$('<span class="page-number"></span>').text(page + 1).bind('click', {
newPage: page
}, function(event) {
currentPage = event.data['newPage'];
$table.trigger('repaginate');
$(this).addClass('active').siblings().removeClass('active');
}).appendTo($pager).addClass('clickable');
}
$pager.insertBefore($table).find('span.page-number:first').addClass('active');
});
} );
</script>
it works perfect, I got popup window and system inserts record to database but only if there is only input field and submit button. When I put table it doesnt work. System does not reload and not insert record into database. Why?
So I solved this problem by simply putting table after form:
<div class="inner">
<form id="reguserform" method="post" action="process.php#err" style="margin-top:40px;">
<?php
$res = verifyFormFields();
?>
<!-- Username field -->
<input type="text" class="input name" placeholder="Process name (required)" name="process" required/>
<!--<label class="tooll tool1">- No special Characters except _<br>- Character Limit: 4 to 20<br>- Username must be Unique</label>-->
<center><input type="submit" class="button small" name="submit" value="Create Process"/></center>
<div id="registerModal" class="reveal-modal small" data-reveal aria-labelledby="modalTitle" aria-hidden="true" role="dialog" data-options="close_on_background_click:false">
<h2 id="modalTitle">Success!</h2>
<div>
<div id="testRegister" style="font-weight: 400;font-size: 1.5em; font-family: 'Raleway', Arial, sans-serif;"></div>
<div class="right">
Ok
</div>
</div>
</div>
<?php
if($count == 1)
{
if($res=="")
{
registerProcess();
echo"<script>document.getElementById('testRegister').innerHTML=registerStr;callShowAlert();</script>";
}
else{
echo "
<a style='color:red';>
$res
</a>
";
}
}
?>
</form>
<center><table class="paginated">
<?php
$result = getProcessData();
if (mysqli_num_rows($result) > 0)
{
echo '
<thead>
<tr>
<th>Process</th>
<th>Created By</th>
</tr>
</thead>';
}
$count = 0;
if (mysqli_num_rows($result) > 0)
while($row = mysqli_fetch_array($result))
{
$process = $row['theme_name'];
$createdBy = $row['createby'];
echo '
<tbody>
<tr valign="top">
<td>' .$process. '</td>
<td>' .$createdBy. '</td>
</tr>
</tbody>';
$count++;
}
?>
</table></center>
</div>
So as I got it, table cannot be updated before from.

Add to cart with ajax in codeigniter

I'm trying add to cart using CodeIgniter and it is working fine but, when I want to do the same through ajax its getting some problem. Can you please look at my codes and tell me where do I get some mistakes? I'm confused how to use ajax to call the add function of the controller . What should I add or do in the ajax code to make this function work?
<html>
<head>
<title>Codeigniter cart class</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway:500,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<script type="text/javascript">
$(document).ready(function() {
$("#myform").submit(function(event) {
event.preventDefault();
var insert_data= $("#myform").serializeArray();
$.ajax({
url: "<?php echo base_url(); ?>" + "index.php/shopping/add",
type: "POST",
data: insert_data,
success: function(response)
{
if (response)
{
//window.location.replace("http://127.0.0.1/codeigniter_cart2/index.php/shopping");
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping";
}
else{
alert('sorry');
}
}
});
});
});
</script>
</head>
<body>
<div id='content'>
<div class="row">
<div class="col-sm-5">
<h2 align="center">Items</h2>
<?php
?>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
foreach ($products as $product) {
$id = $product['serial'];
$name = $product['name'];
$price = $product['price'];
?>
<tr class="well">
<td style="padding-left:15px;"><?php echo $name; ?></td>
<td>
Rs. <?php echo $price; ?></td>
<?php
?>
<?php
echo form_open('',array('id' => 'myform'));
echo form_hidden('id', $id);
echo form_hidden('name', $name);
echo form_hidden('price', $price);
?> <!--</div>-->
<?php
$btn = array(
'class' => 'fg-button teal',
'value' => 'Add',
'name' => 'action',
'id' => 'add_button'
);
?>
<td>
<?php
// Submit Button.
echo form_submit($btn);
echo form_close();
?>
</td>
</tr>
<?php } ?>
</table>
</div>
<div class="col-sm-7">
<!-- <div id="cart" >-->
<h2 align="center">Items on Cart</h2>
<div>
<?php $cart_check = $this->cart->contents();
if(empty($cart_check)) {
echo 'To add products to your shopping cart click on "Add" Button';
} ?> </div>
<table id="table" border="0" cellpadding="5px" cellspacing="1px">
<?php
// All values of cart store in "$cart".
if ($cart = $this->cart->contents()): ?>
<tr id= "main_heading" class="well">
<td style="padding-left:15px;"><?>Name</td>
<td>Price(Rs)</td>
<td>Qty</td>
<td>Amount</td>
<td>Remove</td>
</tr>
<?php
// Create form and send all values in "shopping/update_cart" function.
echo form_open('shopping/update_cart');
$grand_total = 0;
$i = 1;
foreach ($cart as $item):
echo form_hidden('cart[' . $item['id'] . '][id]', $item['id']);
echo form_hidden('cart[' . $item['id'] . '][rowid]', $item['rowid']);
echo form_hidden('cart[' . $item['id'] . '][name]', $item['name']);
echo form_hidden('cart[' . $item['id'] . '][price]', $item['price']);
echo form_hidden('cart[' . $item['id'] . '][qty]', $item['qty']);
?>
<tr class="well">
<td style="padding-left:15px;">
<?php echo $item['name']; ?>
</td>
<td>
<?php echo number_format($item['price'], 2); ?>
</td>
<td>
<?php echo form_input('cart[' . $item['id'] . '][qty]', $item['qty'], ' type="number" max="99" min="1" value="1" style="width:50px;"'); ?>
</td>
<?php $grand_total = $grand_total + $item['subtotal']; ?>
<td>
Rs <?php echo number_format($item['subtotal'], 2) ?>
</td>
<td>
<?php
// cancle image.
$path = "<img src='http://127.0.0.1/codeigniter_cart2/images/cart_cross.jpg' width='25px' height='20px'>";
echo anchor('shopping/remove/' . $item['rowid'], $path); ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
<td style="padding-left:30px;"><b>Order Total: Rs <?php
//Grand Total.
echo number_format($grand_total, 2); ?></b></td>
<td colspan="5" align="right"><input type="button" class ='fg-button teal' value="Clear cart" onclick="window.location = 'shopping/remove/all'">
<?php //submit button. ?>
<input type="submit" class ='fg-button teal' value="Update Cart">
<?php echo form_close(); ?>
</td>
</tr>
<?php endif; ?>
</table>
</div>
<!-- <div id="products_e" align="center">-->
<!--</div>-->
<!-- </div>-->
</div>
</div>
</body>
Now my controller:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Shopping extends CI_Controller {
public function __construct()
{
parent::__construct();
//load model
$this->load->model('billing_model');
$this->load->library('cart');
}
public function index()
{
$data['products'] = $this->billing_model->get_all();
$this->load->view('shopping_views', $data);
}
function add()
{
$insert_data = array(
'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'price' => $this->input->post('price'),
'qty' => 1
);
$this->cart->insert($insert_data);
redirect('shopping');
return TRUE;
}
function remove($rowid) {
// Check rowid value.
if ($rowid==="all"){
// Destroy data which store in session.
$this->cart->destroy();
}else{
// Destroy selected rowid in session.
$data = array(
'rowid' => $rowid,
'qty' => 0
);
// Update cart data, after cancle.
$this->cart->update($data);
}
// This will show cancle data in cart.
redirect('shopping');
}
function update_cart(){
// Recieve post values,calcute them and update
$cart_info = $_POST['cart'] ;
foreach( $cart_info as $id => $cart)
{
$rowid = $cart['rowid'];
$price = $cart['price'];
$amount = $price * $cart['qty'];
$qty = $cart['qty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'amount' => $amount,
'qty' => $qty
);
$this->cart->update($data);
}
redirect('shopping');
}
}
How should I apply this code to ajax?
Thanks for the help.
it's not necessary to use "success:"
However if you want to check error or debug
1) press F12 on Browser to open Developer Mode
2) do action (add cart)
3) on tab "Network" find your ajax request and see your error
Modify your add() function as follows:
function add(){
$insert_data = array('k1' => 'v1', 'k2' => 'v2');
$success = $this->cart->insert($insert_data);
if($success){
$res = array('status' => 200, 'msg' => 'success', 'somekey' => 'somevalue');
}else{
$res = array('status' => 500, 'msg' => 'database err');
}
echo json_encode($res);
}
Now the add() function has responded the ajax request with some json-formated data, you can parse the response data in javascript. The (success:) function should be like this:
function(response) {
if (response){
var res = JSON.parse(response);
if(res.status == 200){
window.location.href="http://127.0.0.1/codeigniter_cart2/index.php/shopping";
}else{
//error handler
alert(res.msg);
}
}else{
alert('sorry');
}
});
function __construct(){
parent::__construct();
$this->load->library(array('session','cart'));
$this->load->library('');
$this->load->helper('url');
$this->load->database();
}
public function product_list(){
$this->db->select('*');
$this->db->from('product');
$this->db->order_by('product_id','desc');
$rs = $this->db->get();
return $rs->result_array();
}
public function product_byId($pid){
$this->db->select('*');
$this->db->from('product');
$this->db->where('product_id',$pid);
$rs = $this->db->get();
return $rs->row_array();
}
Download full code from here http://phpcooker.com/codeigniter-shopping-cart

Categories