How to update my sql table with out page refresh in php? - php

Hi i want to update my sql table field without page refresh in php how can i achieve i tried but my code is not working i do not know where i am wrong
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'assignlead.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<?php
include('conn.php');
$per_page = 3;
if($_GET)
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$select_table = "select * from clientreg order by id limit $start,$per_page";
$variable = mysql_query($select_table);
?>
<form class="form2" action="" method="POST" name="myForm" id="myForm">
<div style="width:100%;">
<?php
$i=1;
while($row = mysql_fetch_array($variable))
{
?>
<input type="checkbox" name="users[]" value="<?php echo $row["id"]; ?>" >
<?php
}
?>
<div class="buttons"> <span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input class="greybutton" type="submit" value="Send" />
</div>
<?php
$sql = mysql_query("SELECT *FROM login where role=1");
while ($row = mysql_fetch_array($sql)){
?>
<input type="checkbox" name="eid[]" value="<?php echo $row["eid"]; ?>" ><?php echo $row["username"]; ?>
<?php
}
?>
</div>
</form>
</div>
</body>
</html>
assignlead.php
<?php
$conn = mysql_connect("localhost","root","root");
mysql_select_db("helixcrm",$conn);
if(isset($_POST["submit"]) && $_POST["submit"]!="") {
$usersCount = count($_POST["id"]);
for($i=0;$i<$usersCount;$i++) {
mysql_query("UPDATE clientreg set eid='" . $_POST["eid"][$i] . "' WHERE id='" . $_POST["id"][$i] . "'");
}
}
?>
<?php
$rowCount = count($_POST["users"]);
for($i=0;$i<$rowCount;$i++) {
$result = mysql_query("SELECT * FROM clientreg WHERE Id='" . $_POST["users"][$i] . "'");
$row[$i]= mysql_fetch_array($result);
$id=$row[$i]['id'];
?>
<input type="hidden" name="id[]" class="txtField" value="<?php echo $row[$i]['id']; ?>"></td>
<?php
$rowCoun = count($_POST["eid"]);
for($j=0;$j<$rowCoun;$j++) {
$result = mysql_query("SELECT * FROM login WHERE eid='" . $_POST["eid"][$j] . "'");
$row[$j]= mysql_fetch_array($result);
$eid=$row[$j]['eid'];
?>
<input type="hidden" name="eid[]" class="txtField" value="<?php echo $row[$j]['eid']; ?>">
<?php
}
}
?>
i tried a lot but i am not able to get my output
How can i achieve my output
Thanks in advance

Update your javascript like this :
$(document).ready(function(){
$('#myForm').submit(function(){
$.ajax({
url : 'assignlead.php',
data : $(this).serialize(),
type : 'POST',
success : function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
// !important for ajax form submit
return false;
});
});

Related

How to obtain the option selected from the drop down menu and insert it into a mysql table

I've been trying to do a dynamic drop down menu using php/mysql with ajax. But I'm new to php and ajax so i don't know how to insert the selected option into a mysql table. I created a form where the action leads to a insertsql.php file but its not working.I'm using wamp server. Any help would be greatly appreciated.
index1.php
<?php
//index.php
$connect = mysqli_connect("localhost", "root", "", "projects");
$pname = '';
$query = "SELECT pname FROM project_details GROUP BY pname ORDER BY pname ASC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$pname .= '<option value="'.$row["pname"].'">'.$row["pname"].'</option>';
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>zz
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Dynamic Dependent Select Box using JQuery Ajax with PHP</h2><br /><br />
<form method = "POST" action = "insertsql.php" >
<select name="pname" id="pname" class="form-control action">
<option value="">Select Project</option>
<?php echo $pname; ?>
</select>
<br />
<select name="user" id="user" class="form-control action">
<option value="">Select User Name</option>
</select>
<br />
<input type="submit" name="update" value="Update">
<p id="dem"></p>
<p id="demo"></p>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "pname")
{
result = 'user';
}
$.ajax({
url:"fetch.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
</script>
fetch.php
<?php
//fetch.php
if(isset($_POST["action"]))
{
$connect = mysqli_connect("localhost", "root", "", "projects");
$output = '';
if($_POST["action"] == "pname")
{
$query = "SELECT fname,lname FROM users WHERE pname = '".$_POST["query"]."' GROUP BY fname";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select User</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["fname"].' '.$row["lname"].'">'.$row["fname"]." ".$row["lname"].'</option>';
}
}
echo $output;
}
?>
insertsql.php
<?php
include('sqlconfig.php');
$pname= $_POST['pname'];
$username=$_POST['user'];
$date=$_POST['wdate'];
$hours=$_POST['hours'];
echo "$pname";
echo "<br>$username<br>";
$sql="INSERT INTO worklogging(pname,username,wdate,wkhours) VALUES ('$pname','$username','$date','$hours')";
if(!mysqli_query($con,$sql))
{echo 'not inserted';}
else
{echo 'Inserted';
}
?>
This is the part where the data from the dropdown menu is inserted into the mysql table. Thank you all for the help :)

Form and PHP result display on same page

I have a form on one page linking to a PHP file (action), now the PHP result is being displayed in this PHP file/page. But I want the result to be displayed on the page with the form. I have searched thoroughly and couldn't find it anywhere. Perhaps any of you can help?
Code: /citizens.php (main page)
<form method="post" action="/infoct.php">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="submit">
</form>
Code: /infoct.php
<!DOCTYPE html>
<html>
<head>
<!-- <meta http-equiv="refresh" content="0; url=/citizens.php" /> -->
</head>
<body>
<?php {
$ID2 = isset($_POST['ID']) ? $_POST['ID'] : false;
}
$connect = mysql_connect('localhost', 'root', 'passwd');
mysql_select_db ('inhabitants');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID2";
$res = mysql_query($sql);
echo "<P1><b>Citizen Identification number is</b> $ID2 </p1>";
while($row = mysql_fetch_array($res))
{
echo "<br><p1><b>First Name: </b></b>", $row['Name'], "</p1>";
echo "<br><p1><b>Surname: </b></b></b>", $row['Surname'], "</p1>";
echo "<br><p1><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p1>";
echo "<br><p1><b>Address: </b></b></b></b></b>", $row['Address'], "</p1>";
echo "<br><p1><b>Background information: </b><br>", $row['RPS'], "</p1>";
}
mysql_close ($connect);
?>
</body>
</html>
My fixed code thanks to Marc B
<form method="post">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ID = isset($_POST['ID']) ? $_POST['ID'] : false;
$connect = mysql_connect('fdb13.biz.nf:3306', '1858208_inhabit', '12345demien12345');
mysql_select_db ('1858208_inhabit');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID";
$res = mysql_query($sql);
if ($ID > 0) {
echo "<p><b>Citizen Identification number is</b> </p>";
while($row = mysql_fetch_array($res))
echo "<br><p><b>Surname: </b></b></b>", $row['Surname'], "</p>";
echo "<br><p><b>First Name: </b></b>", $row['Name'], "</p>";
echo "<br><p><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p>";
echo "<br><p><b>Address: </b></b></b></b></b>", $row['Address'], "</p>";
echo "<br><p><b>Background information: </b><br>", $row['RPS'], "</p>";
mysql_close ($connect);
}
else {
echo "<p>Enter a citizen ID above</p>";
}
}
?>
DB Snap
A single-page form+submit handler is pretty basic:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted, process it ...
... display results ...
... whatever else ...
}
?>
<html>
<body>
<form method="post"> ... </form>
</body>
</html>
That's really all there is.
Use code on the same page (citizens.php)
<?php
if (isset($_POST)) {
Do manipulation
}
?>
Else use ajax and remove action method from form.
<form method="post" id="contactForm">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="buttom" id="submitId">
</form>
<script>
$("#submitId").click(function(){
var Serialized = $("#contactForm").serialize();
$.ajax({
type: "POST",
url: "infoct.php",
data: Serialized,
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function(){
alert('error handing here');
}
});
});
</script>
And in your infact.php in the end Echo the data so that ajax will have the data in return.
You could just put everything in infoct.php, like this:
<!DOCTYPE html>
<html>
<head>
<!-- <meta http-equiv="refresh" content="0; url=/infoct.php" /> -->
</head>
<body>
<form method="post" action="/infoct.php">
<input type="text" name="ID" placeholder="ID" value="<?php isset($_POST['ID']) ? $_POST['ID'] : '' ?>">
<input name="set" type="submit">
</form>
<?php
if (isset($_POST['ID'])) {
$ID2 = $_POST['ID']; // DO NOT FORGET ABOUT STRING SANITIZATION
$connect = mysql_connect('localhost', 'root', 'usbw');
mysql_select_db ('inhabitants');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID2";
$res = mysql_query($sql);
echo "<P1><b>Citizen Identification number is</b> $ID2 </p1>";
while($row = mysql_fetch_array($res))
{
echo "<br><p1><b>First Name: </b></b>", $row['Name'], "</p1>";
echo "<br><p1><b>Surname: </b></b></b>", $row['Surname'], "</p1>";
echo "<br><p1><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p1>";
echo "<br><p1><b>Address: </b></b></b></b></b>", $row['Address'], "</p1>";
echo "<br><p1><b>Background information: </b><br>", $row['RPS'], "</p1>";
}
mysql_close ($connect);
}
?>
</body>
</html>
Do not forget about string sanitization !
I have found the solutions to the folowing problems:
Display results on same page
Thanks to Marc B
A single-page form+submit handler is pretty basic:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted, process it ...
... display results ...
... whatever else ...
}
?>
<html>
<body>
<form method="post"> ... </form>
</body>
</html>
That's really all there is.
Only first value is showing
I resolved this problem by adding this to my code:
while($row = mysql_fetch_array($res)) {
$surname=$row['Surname'];
$name=$row['Name'];
$dob=$row['DOB'];
$address=$row['Address'];
$RPS=$row['RPS'];
Now all the values are being displayed instead of only the first one.
Display results on same page
Well I've stumbled upon this with the same problem
and I found out you can simply require the other file.
include_once("PATH_TO_FILE")'.
in /citizens.php
<?php include_once="infoct.php" ?>
<form> ... </form>
<div>
<?php $yourdata ?>
</div>
$yourdata should be html.
Do not forget about string sanitization !
Make sure to remove action from the form
Better than having all logic and Html in one file.

when try to add more field and select then its conflict first row

When i am trying to select option value form row one there's no problem but if i add more and select optional value in second row then its getting conflict first. Every time when you select optional value then only first row conflict i want first row change while changing first select option . Second row select change only second row values.
index.php
<?php
if(!empty($_POST["save"])) {
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$itemCount = count($_POST["item_name"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
if(!empty($_POST["item_name"][$i]) || !empty($_POST["item_price"][$i])) {
$itemValues++;
if($queryValue!="") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_name"][$i] . "', '" . $_POST["item_price"][$i] . "')";
}
}
$sql = $query.$queryValue;
if($itemValues!=0) {
$result = mysql_query($sql);
if(!empty($result)) $message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
function addMore() {
$("<DIV>").load("input.php", function() {
$("#product").append($(this).html());
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php if(isset($message)) { echo $message; }?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index:item_index},`
success:function(result){
alert(result);
$('#div1').html(result);
}
});
}
</script>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV>
<DIV class="float-left"><select name="item_index" id="item_index" class="required input-small" onchange="salesdetail(this.value);" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$result = mysql_query("select * from item");
while($row=mysql_fetch_assoc($result))
{
echo "<option>".$row['item_name']."</option>";
}
?>
</select>
</DIV>
<DIV class="float-left" id="div1"><input type="text" id="unit_price" name="unit_price" /></DIV>
</DIV>
and getsaleinfo.php
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$supplier= $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
if($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini" value="<?php echo $row['item_price'];?>" >
</div>
<?php }
?>
database
CREATE TABLE IF NOT EXISTS `item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_name` varchar(255) NOT NULL,
`item_price` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `item` (`id`, `item_name`, `item_price`) VALUES
(1, 'hello', 21),
(2, 'hi', 22);
try this...
$('body').on('change','#item_index',function() { //works for ajax loaded contents
var id = $("#item_index").val();
var formid = new FormData();
formid.append('item_index',id);
$.ajax({
url : 'getsaleinfo.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formid,
type : 'post',
success : function(data){
alert(result);
$('#div1').html(result);
//document.getElementById("div1").innerHTML=data;
}
});
}
insted of onchange call this will do...
When you change the selection in the dropdown list, it sends the request to the server:
getsaleinfo.php with item_index:'hello'
That executes
select * from item where item_name='hello' (one line)
That sends
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini"
value="<?php echo $row['item_price'];?>" >
</div>
back to the caller.
The javascript puts that whole thing inside #div1 replacing whatever was there.
From what I'm gathering, addMore() is loading the whole of input.php every time and appending it to #product.
First of all that means you're repeated adding the jquery and function definition, but secondly (and the main problem) - each one adds a NEW div with ID=div1.
When you call
$('#div1').html(result)
in your salesdetail function, that just refers to the first one (since according to HTML you can only have one instance of each ID and the others are ignored.
/*------------------------index.php--------------------------*/
<?php
if (!empty($_POST["save"])) {
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$itemCount = count($_POST["item_index"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for ($i = 0; $i < $itemCount; $i++) {
if (!empty($_POST["item_index"][$i]) || !empty($_POST["unit_price"][$i])) {
$itemValues++;
if ($queryValue != "") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_index"][$i] . "', '" . $_POST["unit_price"][$i] . "')";
}
}
$sql = $query . $queryValue;
if ($itemValues != 0) {
$result = mysql_query($sql);
if (!empty($result))
$message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
var cnt = 1;
function addMore() {
$("<DIV>").load("input.php?cnt=" + cnt, function() {
$("#product").append($(this).html());
cnt++;
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item) {
jQuery(':checkbox', this).each(function() {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php
if (isset($message)) {
echo $message;
}
?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
/*------------------------input.php--------------------------*/
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index, item_id)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index: item_index, item_id: item_id},
success: function(result) {
alert(result);
$('#div_' + item_id).html(result);
}
});
}
</script>
<?php $_REQUEST['cnt'] = (isset($_REQUEST['cnt'])) ? $_REQUEST['cnt'] : 0; ?>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_ind[]" id="item_ind_<?php echo $_REQUEST['cnt']; ?>" /></DIV>
<DIV class="float-left"><select name="item_index[]" id="item_index_<?php echo $_REQUEST['cnt']; ?>" class="required input-small" onchange="salesdetail(this.value, '<?php echo $_REQUEST['cnt']; ?>');" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$result = mysql_query("select * from item");
while ($row = mysql_fetch_assoc($result)) {
echo "<option>" . $row['item_name'] . "</option>";
}
?>
</select></DIV>
<DIV class="float-left" id="div_<?php echo $_REQUEST['cnt']; ?>"><input type="text" id="unit_price_<?php echo $_REQUEST['cnt']; ?>" name="unit_price[]" /></DIV>
</DIV>
getsaleinfo.php
/*------------------------getsaleinfo.php--------------------------*/
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$supplier = $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
$_REQUEST['item_id'] = (isset($_REQUEST['item_id'])) ? $_REQUEST['item_id'] : '';
if ($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<input type="text" name="unit_price[]" id="unit_price_<?php echo $_REQUEST['item_id']; ?>" class="input-mini" value="<?php echo $row['item_price']; ?>" >
</div>
<?php }
?>

Index page comments not inserting into database using AJAX

I'm trying to insert a comment into a database but I keep getting an Object object alert whenever trying to submit it and it never makes it to the database. The files are all in the same folder.
Any help is appreciated, thanks in advance.
index.php
<?php require_once('include/header.php'); require_once('include/browser.php'); ?>
<div class="content">
<section>
<div class="article">
<?php
$userNameQuery = "SELECT * FROM (SELECT * FROM `tbl_posts` ORDER BY 'post_id' DESC)
t ORDER BY `post_id` DESC
LIMIT 3";
$result = mysqli_query($connection, $userNameQuery)
or die("Error in query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result)){
$post_id = $row ['post_id'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['post_title']; ?></h1>
</div>
<div class="textcontainer">
<?php echo $row['post_content']?>
</div>
<?php
if (!empty($row['imagePath'])) //This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="<?php echo $row['imagePath']; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['post_timestamp']; ?>
<b>Author :</b> Admin
</div>
<?php
//Selecting comments which correspond to the post
$selectCommentQuery = "SELECT * FROM `tbl_comments`
LEFT JOIN `tbl_users`
ON tbl_comments.tbl_comments_users_id = tbl_users.id
WHERE tbl_comments.tbl_comments_post_id ='$post_id'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
//showing the comments
echo '<div class="comment-block_' . $post_id .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Comment by: <?php echo $commentRow['username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['comment_content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['comment_timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['cleanUsername']) )
{
?>
<form method="POST" class="post-form" action="index.php" >
<label>New Comment</label>
<textarea name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $post_id ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once('include/footer.php'); ?>
comments.js
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('.comment',form);
if (comment.val().length > 1)
{
$.ajax({
url: 'postComments.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data so we can enter into database
beforeSend: function(){
//Changing submit button value text and disabling it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Please fill the field!");
}
});
});
postComments.php
<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
session_start();
require_once('ajaxconnection.php');
$connection2 = connectToMySQL();
$userId = $_SESSION['userID'];
$username = $_SESSION['cleanUsername'];
$comment = $_POST['comment'];
$postId = $_POST['post_id'];
$date_format = " Y-m-d g : i : s";
$time = date ($date_format);
$insertCommentQuery = "INSERT INTO `tbl_comments`
(`comment_content`,`tbl_comments_users_id`,`tbl_comments_post_id`)
VALUES ('$comment', $userId, $postId)";
$result = mysqli_query($connection,$insertCommentQuery);
$obj = array();
$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
<div class="commentusername"><h1> Username :'.$username.'</h1></div>
<div class="commentcontent">'.$comment.'</div>
<div class="commenttimestamp">'.$time.'</div>
</div>';
echo json_encode($obj);
connectToMySQL(0);
endif?>
ajaxconnection.php
<?php
function connectToMySQL()
{
$connection2 = mysqli_connect("localhost","root","","ascaniobajada2ed8s")
or die('Error connecting to the database');
return $connection2;
}
?>
JQuery .Ajax returns error like this (jqXHR, textStatus, errorThrown). So use it like this to see the real error and not just object object
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}

Jquery .hover not functioning

I am trying to highlight a table row using Jquery's .hover() method.
I have the following code:
var x;
var namen;
window.onload = function(){
x = true;
y = true;
$("submitnieuw").observe('click', addturf);
$("submitdelete").observe('click', verwijderturf);
$("stats").on("click", "tr", select);
setInterval(function (){
jQuery("#recent").load("vandaag.php");
if(x){
jQuery("#stats").load("stats.php");
}
}, 10000);
$("tr").not(':first').hover(
function () {
$(this).addClassName("selected");
},
function () {
$(this).removeClassName("selected");
}
);
alert("test");
};
function select(naam){
//highlight the selected list element
if (y){
var name = naam.findElement('tr').id;
if (name !== ""){
x = false;
y = false;
jQuery.ajax('details.php',{
data: {
'Naam': name,
'door': $("door2").value
},
type: 'post',
success: function(data){
$("stats").innerHTML = data;
},
error: ajaxFailure
});
}
}
else{
x = true;
y = true;
jQuery("#stats").load("stats.php");
jQuery("#recent").load("vandaag.php");
}
}
function verwijderturf() {
var box = document.getElementById("naamverwijder");
var naam = box.options[box.selectedIndex].value;
document.getElementById("naamnieuw").selectedIndex=0;
$("redennieuw").value = "";
jQuery.ajax('server.php',{
data: {
'mode': 'verwijderturf',
'naam': naam,
'door': $("door2").value
},
type: 'post',
success: update,
error: ajaxFailure
});
}
function addturf() {
var box = document.getElementById("naamnieuw");
var naam = box.options[box.selectedIndex].value;
document.getElementById("naamnieuw").selectedIndex=0;
var reden = $("redennieuw").value;
$("redennieuw").value = "";
jQuery.ajax('server.php',{
data: {
'mode': 'addturf',
'naam': naam,
'door': $("door2").value,
'reden': reden
},
type: 'post',
success: update,
error: ajaxFailure
});
}
function update(ajax){
jQuery("#stats").load("stats.php");
jQuery("#recent").load("vandaag.php");
}
function ajaxFailure(ajax, exception) {
alert("Error making Ajax request:" +
"\n\nServer status:\n" + ajax.status + " " + ajax.statusText +
"\n\nServer response text:\n" + ajax.responseText);
if (exception) {
throw exception;
}
}
selected is defined in the css I have included in my index.php.
This is my index.php
<?php
include_once("db.php");
session_start();
if (!isset($_SESSION['uid'])){
header("location:main_login.php");
exit();
}
if (!isset($_SESSION['upass'])){
header("location:main_login.php");
exit();
}
$sql="SELECT * FROM users WHERE Naam='".$_SESSION['uid']."' AND Wachtwoord='".$_SESSION['upass']."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count < 1){
header("location:main_login.php");
exit();
}
?>
<?php
$date = date("y-m-d");
$vandaag = mysql_query("SELECT Type, Naam, Reden, Door FROM turfjes WHERE turfjes.Datum = '" . $date . "'");
$names = mysql_query("SELECT Naam From users");
$names2 = mysql_query("SELECT Naam From users");
$names3 = mysql_query("SELECT Naam From users");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tomaten turfjes pagina | 258</title>
<link rel="stylesheet" type="text/css" href="css/reset.css" media="all" />
<link rel="stylesheet" type="text/css" href="css/style.css" media="all" />
<script type="text/javascript" src="js/jquery.js"></script>
<script>
jQuery.noConflict();
</script>
<script src="js/prototype.js" type="text/javascript"> </script>
<script src="js/scriptaculous.js" type="text/javascript"></script>
<script src="js/script.js" type="text/javascript"> </script>
</head>
<body>
<div id="container">
<div id="header">
</div>
<div id="info">
<div id="recent">
<fieldset>
<legend>Vandaag</legend>
<table border="0">
<tr>
<td>Type</td>
<td>Naam</td>
<td>Reden</td>
<td>Door</td>
<?php
while($a = mysql_fetch_array($vandaag)){
?> <tr>
<td><?php echo($a['Type']);?></td>
<td><?php echo($a['Naam']);?></td>
<td><?php echo($a['Reden']);?></td>
<td><?php echo($a['Door']);?></td>
</tr>
<?php
}
?>
</table>
</fieldset>
</div>
<div id="stats">
<fieldset>
<legend>Turfjesteller</legend>
<table border="0">
<tr>
<td>Naam</td>
<td>Aantal</td>
<td>Gedaan</td>
<td>Resterend</td>
</tr>
<?php
while($r = mysql_fetch_array($names)){
echo("<tr id=".$r['Naam'].">");
?>
<td><?php echo($r['Naam']);?></td>
<?php
$sql="SELECT * FROM turfjes WHERE Naam='".$r['Naam']."' AND Type='Adtje'";
$result=mysql_query($sql);
$count=mysql_num_rows($result); //count = adtjes
$sql2="SELECT * FROM turfjes WHERE Naam='".$r['Naam']."' AND Type='Turfje'";
$result2=mysql_query($sql2);
$count2=mysql_num_rows($result2); //count2 = turfje
?>
<td><?php echo($count2);?></td>
<td><?php echo($count);?></td>
<td><?php echo($count2-$count);?></td>
</tr>
<?php
}
?>
</table>
</fieldset>
</div>
</div>
<div id="actie">
<div id="nieuw">
<fieldset>
<legend>Nieuwe turfjes</legend>
<label>Naam</label>
<select id = "naamnieuw">
<option value="" selected></option>
<?php
while($r = mysql_fetch_array($names2)){
echo("<option value='".$r['Naam']."'>".$r['Naam']."</option>");
}
?>
</select>
<br>
<label>Reden</label> <input type="text" name="redennieuw" id="redennieuw"/> <br>
<label>Door</label> <input type="text" name="door" id="door" disabled="disabled" value =<?php echo($_SESSION['uid']) ?>> <br>
<div id = "buttonz"><button type="button" id="submitnieuw">Turfje uitdelen</button></div>
</fieldset>
</div>
<div id="verwijder">
<fieldset>
<legend>Verwijderen turfjes</legend>
<label>Naam</label>
<select id = "naamverwijder">
<option value="" selected></option>
<?php
while($r = mysql_fetch_array($names3)){
echo("<option value='".$r['Naam']."'>".$r['Naam']."</option>");
}
?>
</select>
<br>
<label>Door</label> <input type="text" name="door" id="door2" disabled="disabled" value =<?php echo($_SESSION['uid']) ?>> <br>
<div id = "buttonz"><button type="button" id="submitdelete">Turfje verwijderen</button></div>
</fieldset>
</div>
<form name="logout" method="post" action="logout.php">
<div id = "buttonz"><input type="submit" name="logout" value="Log uit"></div>
</form>
</div>
</div>
</body>
</html>
The test alert is not executed so I know that my hover is not working. I checked and everything before the hover is executed however and still functional.
I am not quite sure what I am doing wrong.
Can anybody help me please?
My syntax seems to be just fine, according to online checkers.
There's no such thing as addClassName in jQuery, did you mean addClass?
Try this:
$("tr").not(':first').hover(
function () {
$(this).addClass("selected");
},
function () {
$(this).removeClass("selected");
}
);
Also, your selector could be "simplified" to $("tr:not:(first)")
It seems (not sure due to your code being php) that you want to apply hover on elements that aren't present on load. If that's the case, you cannot simply do
$("tr").not(':first').hover(
You must use jquery on so that it will be applied to all elements appearing.
To replace a hover by a on, you have to hook the 'mousenter' and 'mouseleave' events :
$('body').on('mousenter', 'tr:not(:first)', function({ ... });
$('body').on('mouseleave', 'tr:not(:first)', function({ ... });

Categories