I am new to JQuery and I am making an html page where the user can search for a Book ID once the search button is clicked. The problem is, the search button is not responding. Here's my code.
Here's the php file:
<?php
require("dbconnect.php");
$sql = "select * from tbl_books";
$result = mysql_query($sql, $conn) or die(mysql_error());
/** table **/
echo "<table border='1'
cellpadding='5'>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Category</th>";
echo "<th>Author</th>";
echo "</tr>";
while($row=mysql_fetch_array($result)) {
$id = $row['bid'];
$bname=$row['bname'];
$category=$row['category'];
$author=$row['author'];
echo "<tr>";
echo "<td>$bname</td>";
echo "<td>$category</td>";
echo "<td>$author</td>";
}
?>
Html
<!doctype html>
<html>
<header>
<title>
Main Page
</title>
<script type="text/javascript"
src="jquery-2.1.4.min.js"> </script>
<script>
$(function() {
$.post("bookoramaBookDisplay.php",
function(data){
$("#display").html(data);
});
});
</script>
<script>
$(function() {
$("#btnsearch").click(function() {
var search=$("#txtsearch").val();
$.post("bookoramaBookDisplay.php",
{txtsearch:search},
function(data){
$("#display").html(data);
});
});
});
</script>
</header>
<body>
<div id = "table2">
<div id = "taas">
<input type="text"
name = "txtsearch_name"
id = "txtsearch"
placeholder="Search Book">
<input type="button"
value="Search"
id = "btnsearch">
</div>
<div id = "baba">
<div id = "display">
</div>
</div>
</div>
A little help would be highly appreciated. Thank you!
Your query should be
$where='';
if($_POST[txtsearch]){
$where = "WHERE `bid`='".$_POST[txtsearch]."'";
}
$sql = "select * from tbl_books $where";
<!doctype html>
<html>
<head>
<title>
Main Page
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
cache: false ,
url: "bookoramaBookDisplay.php",
success: function(rmsg){
$("#display").html(rmsg);
}
});
$("#btnsearch").click(function() {
$.ajax({
type: 'POST',
cache: false ,
url: "bookoramaBookDisplay.php",
data: {txtsearch:search},
success: function(rmsg){
$("#display").html(rmsg);
}
});
});
});
</script>
</head>
<body>
<div id = "table2">
<div id = "taas">
<input type="text" name = "txtsearch_name" id = "txtsearch" placeholder="Search Book">
<input type="button" value="Search" id = "btnsearch">
</div>
<div id = "baba">
<div id = "display">
</div>
</div>
</div>
</body>
</html>
PHP
<?php
require("dbconnect.php");
$where='';
if($_POST[txtsearch]){
$where = "WHERE `bid`='".$_POST[txtsearch]."'";
}
$sql = "select * from tbl_books $where";
$result = mysql_query($sql, $conn) or die(mysql_error());
/** table **/
echo "<table border='1'
cellpadding='5'>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Category</th>";
echo "<th>Author</th>";
echo "</tr>";
while($row=mysql_fetch_array($result)) {
$id = $row['bid'];
$bname=$row['bname'];
$category=$row['category'];
$author=$row['author'];
echo "<tr><td>".$bname."</td><td>".$category."</td><td>".$author."</td></tr>";
}
echo "</table>";
?>
Related
I have javascript function written within a "generate.php" script and I have "call.php" in a separate script. How do I add a button in "call.php"script that triggers a function in "generate.php"?
"generate.php": javascript; function called by 'save'
<?php
include_once("connection.php");
$chart_data = '';
$db = new dbObj();
$connString = $db->getConnstring();
$id=$_GET['id'];
$query = $connString->prepare("SELECT ID FROM Datas WHERE ID=?");
$query->bind_param('s',$id);
$query->execute();
$result=$query->get_result();
while($row = mysqli_fetch_array($result))
{
$chart_data .= "{ ID:'".$row["ID"]."'},";
}
echo $chart_data;
$chart_data = substr($chart_data, 0);
?>
<!DOCTYPE html>
<html>
<head>
<title> PHP & Mysql</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas#1.0.0-rc.1/dist/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
</head>
<body>
<br /><br />
<div id="chart"></div>
<button id="save">Download</button>
<div class="container" style="width:900px;">
<h2 align="center">MySQL</h2>
<h3 align="center">Data</h3>
<br /><br />
<div id="bar-chart" data-colors="#29abe2,#ffc142,#1ab394, #FF0000, #FFFF00" ></div>
</body>
</html>
<script>
$("#save").click(function() {
html2canvas(document.getElementById('bar-chart')).then(canvas => {
var w = document.getElementById("bar-chart").offsetWidth;
var h = document.getElementById("bar-chart").offsetHeight;
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'pt', [w, h]);
doc.addImage(img, 'JPEG', 10, 10, w, h);
doc.save('xkey.pdf');
}).catch(function(e) {
console.log(e.message);
});
})
</script>
"call.php";
<?php
include_once("generate.php");
$connect = mysqli_connect("localhost", "root", "", "db01");
$output = '';
$sql = "SELECT * FROM Datas WHERE ID LIKE '%" .$_POST["search"]."%'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '<h4 align = "center">Search Result</h4>';
$output .= '<div class="table-responsive">
<table class = "table table bordered">
<tr>
<th>ID</th>
<th>Generate</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["ID"].'</td>
<td><button id="gen" name="generate" class="btn btn-primary"><i class="fa fa"" aria-hidden="true"></i>Generate</button></td>
</tr>
';
}
echo $output;
}
else
{
echo "Data not found";
}
?>
Your pos-PHP code must be located in same document. So either include it via <script src="generate.php"> or via <? require 'generate.php'; ?>
If you need the same functionality in separate scripts, you should extract your js function to a file. Don't forget to name it:
function giveItADescriptiveName() {
html2canvas(document.getElementById('bar-chart')).then(canvas => {
// etc
}).catch(function(e) {
console.log(e.message);
});
}
Then you can include that script in any file where you might need it:
<script src="path/to/where/you/saved/it/whatever-you-called-the-file.js"></script>
And ultimately, you pass your function as the handler:
<script>
$("#save").click(giveItADescriptiveName());
</script>
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???
How do I stop a page from scrolling to the top when button Add to cart is clicked?
since i have a lot of products showing up from database to my page, this refreshing the "index.php" to the top is make me frustrated.
Btw i'm following this tutorial http://www.onlinetuting.com/e-commerce-website-in-php-mysqli-video-tutorials/
PS: i'm a beginner so just help me with an example (the line where to put the code is important for me).
//index.php (short code only)
<!doctype html>
<?php
include ("functions/functions.php");
?>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="styles/style.css" type="text/css" media="all" />
<script src="js/jquery-3.0.0.min.js"></script>
</head>
<body>
<div class="container">
<div class="header"></div>
<div class="navigation">
<div> <?php getCats(); ?> <?php getBrands(); ?> </div>
<div> </div>
<div id="shopping_cart"> Go to Cart <?php total_items(); ?> <?php total_price(); ?> </div>
</div>
<div id="content">
<?php cart(); ?>
<div id="products"> <?php getPro(); ?> <?php getCatPro(); ?> <?php getBrandPro(); ?> </div>
</div>
<div id="footer"></div>
</div> <!--END OF "container" -->
</body>
</html>
//function.php
<?php
$con = mysqli_connect("localhost","root","","learning-php");
if (mysqli_connect_errno())
{
echo "The connection was not established: " . mysqli_connect_error();
}
//Creating the shopping cart
function cart(){
if(isset($_GET['add_cart'])){
global $con;
$ip = getIp();
$pro_id = $_GET['add_cart'];
$check_pro = "select * from cart where ip_add='$ip' AND p_id='$pro_id'";
$run_check = mysqli_query($con, $check_pro);
if(mysqli_num_rows($run_check)>0){
}
else {
$insert_pro = "insert into cart (p_id,ip_add) values ('$pro_id','$ip')";
$run_pro = mysqli_query($con, $insert_pro);
echo "<script>window.open('index.php','_self')</script>";
}
}
}
//Getting the total added items
function total_items(){
if(isset($_GET['add_cart'])){
global $con;
$ip = getIp();
$get_items = "select * from cart where ip_add='$ip'";
$run_items = mysqli_query($con, $get_items);
$count_items = mysqli_num_rows($run_items);
}
else {
global $con;
$ip = getIp();
$get_items = "select * from cart where ip_add='$ip'";
$run_items = mysqli_query($con, $get_items);
$count_items = mysqli_num_rows($run_items);
}
echo $count_items;
}
//Getting the total price of the items in the cart
function total_price(){
$total = 0;
global $con;
$ip = getIp();
$sel_price = "select * from cart where ip_add='$ip'";
$run_price = mysqli_query($con, $sel_price);
while($p_price=mysqli_fetch_array($run_price)){
$pro_id = $p_price ['p_id'];
$pro_price = "select * from products where product_id='$pro_id'";
$run_pro_price = mysqli_query($con,$pro_price);
while($pp_price = mysqli_fetch_array($run_pro_price)){
$product_price = array($pp_price['product_price']);
$values = array_sum($product_price);
$total +=$values;
}
}
echo "$ " . $total;
}
//Getting the categories
function getCats(){
global $con;
$get_cats = "select * from categories";
$run_cats = mysqli_query($con, $get_cats);
while ($row_cats=mysqli_fetch_array($run_cats)){
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<li><a href='index.php?cat=$cat_id'>$cat_title</a></li>";
}
}
//Getting the brands
function getBrands(){
global $con;
$get_brands = "select * from brands";
$run_brands = mysqli_query($con, $get_brands);
while ($row_brands=mysqli_fetch_array($run_brands)){
$brand_id = $row_brands['brand_id'];
$brand_title = $row_brands['brand_title'];
echo "<li><a href='index.php?brand=$brand_id'>$brand_title</a></li>";
}
}
//Showing the products
function getPro(){
if(!isset($_GET['cat'])){
if(!isset($_GET['brand'])){
global $con;
$get_pro = "select * from products";
$run_pro = mysqli_query($con, $get_pro);
while ($row_pro=mysqli_fetch_array($run_pro)){
$pro_id = $row_pro['product_id'];
$pro_cat = $row_pro['product_cat'];
$pro_brand = $row_pro['product_brand'];
$pro_title = $row_pro['product_title'];
$pro_price = $row_pro['product_price'];
$pro_image = $row_pro['product_image'];
echo "
<div id='products'>
<h3>$pro_title</h3>
<img src='admin_area/product_images/$pro_image' width='135' height='100'/>
<div class='details'>
<p><div id='prc'>Price:</br><b>$. $pro_price </b></div></p>
<p><div id='a2c'><a href='?add_cart=$pro_id'><button style='float:left;'>Add to Cart</button></a></div></p>
<p><div id='fDtl'><a href='full_details.php?pro_id=$pro_id' style='float:left;'>Full Details</a></div></p>
</div>
</div>
";
}
}
}
}
//Showing the products by categories
function getCatPro(){bla,bla,bla}
//Showing the products by brands
function getBrandPro(){bla,bla,bla}
?>
//what i mean is this line (function.php)
div#a2c
//effected to this line (index.php)
div#products
See What i mean
Override default form submit by calling preventDefault and call the action as a ajax call. Make sure that the script is loaded like put it in head section
refer this example:
var element = document.querySelector("form");
element.addEventListener("submit", function(event) {
event.preventDefault();
// actual logic, e.g. validate the form
alert("Form submission cancelled.");
});
<form>
<button type="submit">Submit</button>
</form>
Here is a complete example from http://www.tutorialspoint.com/jquery/events-preventdefault.htm:
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("a").click(function(event){
event.preventDefault();
alert( "Default behavior is disabled!" );
});
});
</script>
</head>
<body>
<span>Click the following link and it won't work:</span>
GOOGLE Inc.
</body>
</html>
I have the following script:
index.php
<?php include("db.php"); ?>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
</head>
<body>
<div align="center">
<table cellpadding="0" cellspacing="0" width="500px">
<?php $sql = "SELECT * FROM items ORDER BY ID DESC";
$items= mysql_query($sql);
while ($item= mysql_fetch_array($items)){
$id = $item[ID]; ?>
<tr style="border: solid 4px red;">
<td>
<div class="<?= $id ?>">
<button class="my-btn" type="button" value="<?= $id ?>">BUTTON <?= $id ?></button>
</div>
</td>
</tr>
<?php } ?>
</table>
<div id="flash" align="left" ></div>
<ol id="update" class="timeline"></ol>
<div id="old_updates"></div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
$(function() {
$(".my-btn").click(function() {
var dataString = $(this).val();
$("#flash").show().fadeIn(200).html('');
$.ajax({
type : "POST",
url : "update_data.php",
data : {'not' : dataString},
cache : false,
success : function(html){
$("#update").prepend(html).find("li:first").slideDown("slow");
$('#content').val('');
$("#flash").hide();
}
});
});
$('.delete_update').live("click",function() {
var ID = $(this).attr("id");
var dataString = 'msg_id='+ ID;
if(confirm("Sure you want to delete this update? There is NO undo!")){
$.ajax({
type : "POST",
url : "delete_data.php",
data : dataString,
cache : false,
success : function(html){
$(".bar"+ID).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
update_data.php
<?php
include('db.php');
if(isSet($_POST['not'])) {
$not = $_POST['not'];
mysql_query("insert into items (name) values ('$not')");
$sql_in = mysql_query("SELECT wave, ID FROM actions order by ID desc");
$r = mysql_fetch_array($sql_in);
$msg = $r['name'];
$id = $r['ID'];
}
?>
<li class="bar<?php echo $msg_id; ?>">
<div align="left">
<span style=" padding:10px"><?php echo $msg; ?> </span>
<span class="delete_button">
X
</span>
</div>
</li>
delete_data.php
<?php
include("db.php");
if($_POST['msg_id']) {
$id = $_POST['msg_id'];
$id = mysql_escape_String($id);
$sql = "delete from items where ID='$id'";
mysql_query( $sql);
}
?>
I posted the whle code to be more specific and easy to understand.
The problem appear only with the delete function.
When i hit the link to delete an item, this item don't disappear instantly but is removed from sql database.
To see the item deleted i need to refresh the page and i don't want that.
I think the problem is with the second function of script.js but i can't figured it out what exactly is.
This is the code that the user have a participation with.
<html>
<head>
<title></title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery.form.js"></script>
</head>
<body>
<?php
include 'connection.php';
$sql="SELECT * FROM blog";
$result=mysqli_query($link, $sql);
if(!$result)
{
$output='Error fetching students:'.mysqli_error($link);
}
?>
<div id="table">
<table border='1' cellpadding='10' id="table">
<tr>
<td><b>Title<b></td>
<td><b>Edit<b></td>
<td><b>Delete<b></td>
</tr>
<?php
while($row=mysqli_fetch_array($result))
{
echo '<tr class="record">';
echo '<td>'.$row['articletitle'] .'';
echo '<td>Edit';
echo "<input type='hidden' name='id' value='".$row['articleid']."'></td>";
echo '<td><div align="center">Delete</div></td>';
echo "</tr>\n";
}
echo '<form method="post" id="myForm" action="postview.php">';
echo '<input type="hidden" name="myID">';
echo '</form>';
?>
</table>
<button id="addrecord">Add New Post</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#addrecord").click(function(){
$("#table").load("addpost.php");
$("#addrecord").hide();
});//add
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?"))
{
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function(){}
});//ajax
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});//delete
$(".title").click(function(){
$('[name=myID]').val($(this).attr('id'));
$('#myForm').submit();
});//view
$(".edit").click(function(){
var data=$("#tryform").serialize();
$.ajax({
type: "POST",
url: "editpost.php",
data: data
}).done(function( msg ) {
$("#table").html(msg);
});//ajax
});//delete
});
</script>
</body>
</html>
and this the PHP script that the code above redirect to.
<?php
include 'connection.php';
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
?>
I'm having this kind of error:
Undefined index: id in C:\xampp\htdocs\ckeditor\samples\postview.php on line 4
You need to check if argument "id" is passed to the php script first
<?php
include 'connection.php';
if( (isset($_GET['id'])) && ($_GET['id'] != '') ){ //check if the argument "id" is passed to the script
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
}
?>
Not so much an answer to your question, but probably a good suggestion to make your code a lot cleaner- try using PHP Alternative Syntax and moving in and out of PHP to make your HTML clean.
<?php while($row=mysqli_fetch_array($result)):?>
<tr class="record">';
<td><?php echo $row['articletitle'];?>
<td>Edit
<input type='hidden' name='id' value='<?php echo $row['articleid'];?>'></td>
<td>
<div align="center">
Delete
</div>
</td>
</tr>
<?php endwhile;?>
<form method="post" id="myForm" action="postview.php">
<input type="hidden" name="myID">
</form>
$sql="SELECT * FROM blog WHERE articleid='".$id."'";
try this line
That isnt an error, but a notice, which is lowlevel It simple means $_GET['id'] doesnt hav a value
echo $example['something']; // will give undefined index notice
$example['something'] = 'abc';
echo $example['something']; // No notices
Your website should be domain.ext/?id=123, if not, this notice will show.