Calling javascript function from a separate php script? - javascript

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>

Related

JavaScript/ajax site reaload

sorry for my bad english google help me :-)
with my script, if i enter something in the database, it is displayed without a page reload. Now I wanted to ask if this is so good or can it be improved? I know javascript/Ajax and what's not out there. I just want that if something is written into the db with a form, it's displayed immediately without page reload, like a kind of shoutbox.
<!DOCTYPE html>
<html lang="de" dir="ltr">
<head>
<meta charset="utf-8">
<title>Ausgabe</title>
</head>
<body onload = "table();">
<script type="text/javascript">
function table(){
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
document.getElementById("table").innerHTML = this.responseText;
}
xhttp.open("GET", "system.php");
xhttp.send();
}
setInterval(function(){
table();
}, 1);
</script>
<div id="table">
</div>
</body>
</html>
<?php
$host_name = '';
$database = '';
$user_name = '';
$password = '';
$link = new mysqli($host_name, $user_name, $password, $database);
if ($link->connect_error) {
die('<p>Verbindung zum MySQL Server fehlgeschlagen: '. $link->connect_error .'</p>');
}
$rows = mysqli_query($link, "SELECT * FROM tb_data");
?>
<table border = 1 cellpadding = 10>
<tr>
<td>#</td>
<td>Name</td>
</tr>
<?php $i = 1; ?>
<?php foreach($rows as $row) : ?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row["name"]; ?></td>
</tr>
<?php endforeach; ?>
</table>

How to get via onclick and POST data on redirect with POST

I'm working using ajax,javascript, php and still new with this.
Here the scenario, I have a button with onclick function in my index.html page when I click that button I want it to redirect me to another my getdata.php page while posting and id. So when I've been redirected to my getdata.php page I just need to query using that id.
The button that trigger redirection are located at index.html <button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>
The following codes I've been using right now. I hope I've got a lot of help right here.
index.html
<?php
session_start();
$conn = mysqli_connect("localhost","root","1234","a0");
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Cache-control" content="no-cache"> <!--The No-Cache-->
<!--Bootstrap 3.3.7 CSS-->
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--Data Tables-->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.1.1/css/responsive.bootstrap.min.css">
<!--Date Timepicker-->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!--Linear Icons-->
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
<!--Date Timepicker-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">MENU</button>
<a class="navbar-brand" href="#"><span class="icon-bag"></span> SUPPLIER</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container-fluid">
<h2 >List of Machine</h2>
<div class="table-responsive">
<div align="right">
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-success">New File <span class="fa fa-code-fork"></span></button>
</div>
<br>
<table id="user_data" class="table table table-bordered table-hover dt-responsive " width="100%">
<thead>
<tr>
<th width="5%">Image</th>
<th width="15%">Name</th>
<th width="10%">Date Added</th>
<th width="10%">Created By</th>
<th width="6%">Action</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Business Type </h4>
</div>
<div class="modal-body">
<label>Business Name</label>
<input type="text" name="businessname" id="businessname" class="form-control" />
<br />
<label>Select Business Image</label>
<input type="file" name="businessimage" id="businessimage" />
<span id="user_uploaded_image"></span>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
<script type="text/javascript" language="javascript" >
$(document).ready(function(){
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
});
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#businessname').val(data.businessname);
$('.modal-title').text("Update Business Type");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.businessimage);
$('#action').val("Save Changes");
$('#operation').val("Edit");
}
})
});
$(document).on('click', '.delete', function(){
var user_id = $(this).attr("id");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
alert(data);
dataTable.ajax.reload();
}
});
}
else
{
return false;
}
});
function generatepdf() {
var name = $(this).data('msid');
if (name != undefined && name != null) {
window.location = 'reports/getdata.php';
$.ajax({
url:"reports/getdata.php",
method:"POST"
});
}
};​
});
</script>
<!--Data Table JS-->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/dataTables.responsive.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.1.1/js/responsive.bootstrap.min.js"></script>
</body>
fetch.php
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM machine_supplier ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE machine_description LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY msid DESC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$image = '';
if($row["image1"] != '')
{
$image = '<img src="machine_images/'.$row["image1"].'" class="img-thumbnail" width="50" height="35" />';
}
else
{
$image = '';
}
$sub_array = array();
$sub_array[] = $image;
$sub_array[] = $row["machine_description"];
$sub_array[] = $row["model_number"];
$sub_array[] = $row["supplier"];
$sub_array[] = '<select class="form-control">
<option selected disabled>YOUR ACTIONS</option>
<option name="update" id="'.$row["msid"].'" class="update">UPDATE</option>
<option name="delete" id="'.$row["msid"].'" class="delete">DELETE</option>
</select>
<button class="btn btn-default print" name="print" data-username="{{"'.$row['msid'].'"}}" onclick="generatepdf()"><span class="icon-printer"></button>
';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
function.php
<?php
function upload_image()
{
if(isset($_FILES["image1"]))
{
$extension = explode('.', $_FILES['image1']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = 'machine_images/' . $new_name;
move_uploaded_file($_FILES['image1']['tmp_name'], $destination);
return $new_name;
}
}
function get_image_name($user_id)
{
include('db.php');
$statement = $connection->prepare("SELECT image1 FROM machine_supplier WHERE msid = '$user_id'");
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
return $row["image1"];
}
}
function get_total_all_records()
{
include('db.php');
$statement = $connection->prepare("SELECT * FROM machine_supplier");
$statement->execute();
$result = $statement->fetchAll();
return $statement->rowCount();
}
?>
getdata.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['print'])) {
$sql = "SELECT msid FROM machine_supplier WHERE";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//data
}
} else {
echo "0 results";
}
} else{
//redirect back
}
?>
</body>
</html>
Easy way is not using JS or Jquery for your requirement. Just use HTML form and PHP only like following in your index.php.
<?php
//In you index.php
//.....................
//..........................
//your other codes
//......................
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form method="post" action="getdata.php">
<input type="hidden" name="my_id" value="<?php echo $row['msid']; ?>" />
<input type="submit" value="REDIRECT AND POST MY ID" />
</form>
<?php
}
} else {
echo "0 results";
}
//.................
//.................
You just need to replace the button code with this form code and your ID will be posted and redirected to getdata.php page because of the form attribute action="getdata.php".
See the form method is post this means your form will be submitted using POST method. Now in your getdata.php file do following
<?php
$posted_id = $_POST['my_id'];
echo $posted_id;
//now get data from DB using this id
//get data from db where id = $posted_id
This is not full code for getdata.php but you will see at least your posted id(from index.php to getdata.php) using this code. There are lots to do like checking http method, error handling etc etc.

How do i stop a page from scrolling to the top when button clicked in php?

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>

Search on Table JQuery

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>";
?>

Onclick function is not working on a particular span

I am having a problem that my Onclick event is not triggering on a tag. The same onclick event is working properly when binded to a image.
I am making a follow and unfollow function in php and jquery .It is not working so I decided to test a alert after clicking the follow or unfollow button . Then also it is not working .
The code is this
<?php
if ($my_id != $id) {
$check_follow_not = mysqli_query($conn, "SELECT * FROM follower WHERE user_id='$my_id' AND following='$id'");
$check_follow_not_rows = mysqli_num_rows($check_follow_not);
if ($check_follow_not_rows == 0) {
$editfollowunfollow = "<span class='btn_f_uf'><a onclick=\"don();\">Follow</a></span>";
} else {
$editfollowunfollow = "<span class='btn_f_uf'><a onclick=\"don();\">UnFollow</a></span>";
}
} else {
$editfollowunfollow = "<span class='btn_f_uf'><a>Edit Profile</a></span>";
}
echo $editfollowunfollow;
?>
The php code is okay, the problem is with the jquery code
The don() function is this
function don(){
alert();
}
This function is working fine on a image in same file . But not working in the follow and unfollow button.
Thanks in advance . I appreciate all answer
EDIT
Css code of class btn_f_uf
.btn_f_uf{
border:0;
outline:0;
padding:10px;
background:#53a93f;
border-radius:5px;
color:white;
float:right;
margin-right:20px;
margin-top:25px;
display:inline-block;
}
EDIT 2
The profile page whole code
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>Profcee</title>
<link rel="stylesheet" href="style/style.css">
<script src="js/jquery-2.1.3.js"></script>
<script src="js/check.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery-ui.min.js"></script>
</head>
<?php
session_start();
if(isset($_GET['id'])){
include "function/checklogin.php";
include "config/connect.php";
$my_profile_image = $_SESSION['profile_image'];
$my_email = $_SESSION['email'];
$my_id = $_SESSION['id'] ;
$my_name = ucfirst($_SESSION['name']);
$my_background_image = $_SESSION['background_image'];
$id = $_GET['id'];
$check = mysqli_query($conn,"SELECT * FROM users WHERE id='$id'");
$check_num = mysqli_num_rows($check);
if($check_num == 0){
header("location:home.php");
}else{
$fetch = mysqli_fetch_assoc($check);
$name = ucfirst($fetch['name']);
$email = $fetch['email'];
$profile_image = $fetch['profile'];
$background_image = $fetch['background'];
if($my_id != $id){
$check_follow_not = mysqli_query($conn,"SELECT * FROM follower WHERE user_id='$my_id' AND following='$id'");
$check_follow_not_rows = mysqli_num_rows($check_follow_not);
if($check_follow_not_rows == 0){
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>Follow</a></span>";
} else{
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>UnFollow</a></span>";
}
}else{
$editfollowunfollow = "<span class='btn_f_uf'><a>Edit Profile</a></span>";
}
?>
<?php
include "header.php"; ?>
<div id="profile_full">
<div id="background_image">
<img src="<?php echo $background_image;?>" width="100%" height="400px" onclick="don();">
</div>
<div id="profile_image">
<img src="<?php echo $profile_image?>" width="250px" height="250px">
</div>
<div id="profile_header">
<h1><?php echo $name;?></h1>
<div id="profile_follower">
<?php
$follower = mysqli_query($conn,"SELECT * FROM follower WHERE following='$id'");
$follower_count = mysqli_num_rows($follower);
?>
<h2><?php echo $follower_count;?> Follower</h2>
</div>
<div id="profile_following">
<?php
$following = mysqli_query($conn,"SELECT * FROM follower WHERE user_id='$id'");
$following_count = mysqli_num_rows($following);
?>
<h2><?php echo $following_count;?> following </h2>
</div>
<?php echo $editfollowunfollow;?>
</div>
</div>
<?php
include "footer.php";
?>
<?php
}
}else{
header("location:home.php");
}
?>
The check.js file
$(document).on("click",".btns", function(e){
e.preventDefault();
alert();
});
Like other said, give it class name btns and removeonclick inline javascript on that anchor tag :
.....
if($check_follow_not_rows == 0){
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>Follow</a></span>";
} else{
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>UnFollow</a></span>";
}
....
And in js code :
$(document).on("click",".btns", function(e){
e.preventDefault();
alert();
});
If you wanna stick with function don(), use this(but must be sure to remove onclick inline javascript) :
$(document).on("click",".btns", don );
In don function :
function don(){
alert();
return false;
}

Categories

Resources