Jquery .hover not functioning - php

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({ ... });

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 :)

AJAX success function not fetching data from MYSQL database

Apologies for similarities between this post and my previous one. I'd appreciate if someone could help me once again spot where I'm going wrong. Everything else appears to be working fine but what is puzzling me is the 'quiet' response on the AJAX success function. Nothing in the console either.
I've tested the JSON output with the json_encode and print_r functions and got the following - so I presume the JSON string should be ok to work with the AJAX:
Array
(
[proj_start_date] => 2017-04-17
[proj_end_date] => 2018-04-30
[wo_nbr_new] => 10002-06
)
{"proj_start_date":"2017-04-17","proj_end_date":"2018-04-30","wo_nbr_new":"10002-06"}
Below is the code for the main file:
<?php
include 'connect_db.php';
$sql = "SELECT * FROM projects ORDER BY proj_nbr";
$result = mysqli_query($connect,$sql);
$rowCount = mysqli_num_rows($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add New Work Order</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Add New Work Order</h1>
<div id="forms-add" name="forms-add">
<form action="add_workorders.php" method="POST">
<label>Work Order Number (Auto-generated):</label>
<input type="text" id="wo_nbr" name="wo_nbr"size="8"maxlength="8" value = "" readonly style="float: right">
<br><br>
<fieldset>
<legend>Project Details</legend>
<label>Project Number:</label>
<select class= "selects" id="proj_nbr" name="proj_nbr" required onchange="">
<option value="">Select a project </option>
<?php
if($rowCount>0)
{
while ($row=mysqli_fetch_assoc($result))
{
echo '<option value="'.
$row['proj_id'].'">'.
$row['proj_nbr'].
' - '.
$row['proj_desc'].
' </option>';
}
}
else
{
echo '<option value="">Project not available</option>';
}
?>
</select>
<br><br>
<label>Start Date:</label>
<input type="text" id="proj_start_date" name="proj_start_date"size="8"maxlength="8" value = "" readonly style="float: right">
<br><br>
<label>End Date:</label>
<input type="text" id="proj_end_date" name="proj_end_date"size="8"maxlength="8" value = "" readonly style="float: right">
</fieldset>
<br><br>
<button type="submit" name="submit" >Save Work Order</button>
</form>
</div>
</body>
<script type="text/javascript" src="test_ajax.js"></script>
<script>
$(document).ready(function()
{
$('#proj_nbr').change(function()
{
var id=$('#proj_nbr').val();
//alert(id); //this works ok
if (id != '')
{
$.ajax({
url: "get_proj_nbrs2.php",
method:"POST",
data: {id:id}, //data to SEND to PHP file
dataType: "JSON",
success: function(output)
{
console.log(output); //this doesn't return anything in the console??
$('#wo_nbr').val(output.wo_nbr_new);
$('#proj_start_date').val(output.proj_start_date);
$('#proj_end_date').val(output.proj_end_date);
}
});
}
else
{
alert("Please select a Project");
}
});
});
</script>
</html>
And the following is the code in the PHP file:
<?php
include 'connect_db.php';
if (isset($_POST['id']) && !empty($_POST['id']))
{
$sql2 = "SELECT p.proj_nbr as wo_proj_nbr,p.start_date as proj_start_date,p.end_date as proj_end_date, MAX(w.wo_nbr) AS wo_nbr,
CASE WHEN SUBSTRING(MAX(w.wo_nbr),7,2)+1 <= 9 THEN CONCAT(p.proj_nbr,'-0',SUBSTRING(MAX(w.wo_nbr),7,2)+1)
ELSE CONCAT(p.proj_nbr,'-',SUBSTRING(MAX(w.wo_nbr),7,2)+1) END AS wo_nbr_new
FROM workorders as w
INNER JOIN projects as p on p.proj_id = w.proj_id
WHERE w.proj_id = '".$_POST['id']."'";
$result2 = mysqli_query($connect,$sql2);
while($row=mysqli_fetch_array($result2))
{
if($result2 ==true)
{
$proj_nbr = $row['wo_proj_nbr'];
$output['proj_start_date'] = $row['proj_start_date'];
$output['proj_end_date'] = $row['proj_end_date'];
if ($row['wo_nbr_new'] != NULL)
{
$output['wo_nbr_new'] = $row['wo_nbr_new'];
echo json_encode($output);
}
elseif($row['wo_nbr_new'] == NULL)
{
$output['wo_nbr_new'] = $proj_nbr."-01";
echo json_encode($output);
}
}
}
}?>
<?php
include 'connect_db.php';
if (isset($_POST['id']) && !empty($_POST['id']))
{
$result = array();
$sql2 = "SELECT p.proj_nbr as wo_proj_nbr,p.start_date as proj_start_date,p.end_date as proj_end_date, MAX(w.wo_nbr) AS wo_nbr,
CASE WHEN SUBSTRING(MAX(w.wo_nbr),7,2)+1 <= 9 THEN CONCAT(p.proj_nbr,'-0',SUBSTRING(MAX(w.wo_nbr),7,2)+1)
ELSE CONCAT(p.proj_nbr,'-',SUBSTRING(MAX(w.wo_nbr),7,2)+1) END AS wo_nbr_new
FROM workorders as w
INNER JOIN projects as p on p.proj_id = w.proj_id
WHERE w.proj_id = '".$_POST['id']."'";
$result2 = mysqli_query($connect,$sql2);
if($result->num_rows > 0)
{
while($row=mysqli_fetch_array($result2))
{
$proj_nbr = $row['wo_proj_nbr'];
$output['proj_start_date'] = $row['proj_start_date'];
$output['proj_end_date'] = $row['proj_end_date'];
if ($row['wo_nbr_new'] != NULL)
{
$output['wo_nbr_new'] = $row['wo_nbr_new'];
}
elseif($row['wo_nbr_new'] == NULL)
{
$output['wo_nbr_new'] = $proj_nbr."-01";
}
array_push($result,$output);
}
echo json_encode($result);
}
else
{
echo "no rows found";
}
}?>
You was echo each row so you will get result from success function in ajax as each separate sting. so it can't parse. hope this method will solve your problem.
Please confirm that you id value is not empty and matches to database field values as well. if so then change the 'id' to 'theid' (might be reserved word) in both the ajax e.g.
data: {theid:id}, //data to SEND to PHP file
and in php e.g.
if (isset($_POST['theid']) && !empty($_POST['theid'])) {
$sql2 = "SELECT p.proj_nbr as wo_proj_nbr,p.start_date as proj_start_date,p.end_date as proj_end_date, MAX(w.wo_nbr) AS wo_nbr,
CASE WHEN SUBSTRING(MAX(w.wo_nbr),7,2)+1 <= 9 THEN CONCAT(p.proj_nbr,'-0',SUBSTRING(MAX(w.wo_nbr),7,2)+1)
ELSE CONCAT(p.proj_nbr,'-',SUBSTRING(MAX(w.wo_nbr),7,2)+1) END AS wo_nbr_new
FROM workorders as w
INNER JOIN projects as p on p.proj_id = w.proj_id
WHERE w.proj_id = '".$_POST['theid']."'";
// code goes here
}
use type at method. method POST depends on jquery version
$.ajax({
url: "get_proj_nbrs2.php",
type:"POST",
data: {id:id}, //data to SEND to PHP file
dataType: "JSON",
success: function(output)
{
}
});

Filter Records based on combobox value php ajax

I want to display records based on the value of the combobox (dropdown list) using ajax. Display list of examinees based on the examdate. Help. I am a newbie in PHP and AJAX.
I want to display records based on the value of the combobox (dropdown list) using ajax. Display list of examinees based on the examdate. Help. I am a newbie in PHP and AJAX.
I want to display records based on the value of the combobox (dropdown list) using ajax. Display list of examinees based on the examdate. Help. I am a newbie in PHP and AJAX.
<?php
include 'configuration.php';
$queryselect = mysql_query("SELECT examdateno, examdate from tbl_examdate ORDER BY examdate DESC");
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="onclick edit jquery php, grid in php, onclick change text box in jquery, onclick edit table row, insert update delete using jquery ajax, simple php data grid" />
<meta name="description" content="This article is about simple grid system using PHP, jQuery. Insert a new record to the table using by normal Ajax PHP. It will show the editable textbox when user clicks on the label." />
<link rel="stylesheet" type="text/css" href="css/grid.css" />
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/component.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
// Function for load the grid
function LoadGrid(dte) {
var gridder = $('#as_gridder');
var UrlToPass = 'action=load';
var value = $('#examdate').val();
gridder.html('loading..');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass,
success: function (responseText) {
gridder.html(responseText);
}
});
}
// Seperate Function for datepiker() to save the value
function ForDatePiker(ThisElement) {
ThisElement.prev('span').html(ThisElement.val()).prop('title', ThisElement.val());
var UrlToPass = 'action=update&value=' + ThisElement.val() + '&crypto=' + ThisElement.prop('name');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass
});
}
LoadGrid(); // Load the grid on page loads
// Execute datepiker() for date fields
$("body").delegate("input[type=text].datepicker", "focusin", function () {
var ThisElement = $(this);
$(this).datepicker({
dateFormat: 'yy/mm/dd',
onSelect: function () {
setTimeout(ForDatePiker(ThisElement), 500);
}
});
});
// Show the text box on click
$('body').delegate('.editable', 'click', function () {
var ThisElement = $(this);
ThisElement.find('span').hide();
ThisElement.find('.gridder_input').show().focus();
});
// Pass and save the textbox values on blur function
$('body').delegate('.gridder_input', 'blur', function () {
var ThisElement = $(this);
ThisElement.hide();
ThisElement.prev('span').show().html($(this).val()).prop('title', $(this).val());
var UrlToPass = 'action=update&value=' + ThisElement.val() + '&crypto=' + ThisElement.prop('name');
if (ThisElement.hasClass('datepicker')) {
return false;
}
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass
});
});
// Same as the above blur() when user hits the 'Enter' key
$('body').delegate('.gridder_input', 'keypress', function (e) {
if (e.keyCode == '13') {
var ThisElement = $(this);
ThisElement.hide();
ThisElement.prev('span').show().html($(this).val()).prop('title', $(this).val());
var UrlToPass = 'action=update&value=' + ThisElement.val() + '&crypto=' + ThisElement.prop('name');
if (ThisElement.hasClass('datepicker')) {
return false;
}
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass
});
}
});
// Function for delete the record
$('body').delegate('.gridder_delete', 'click', function () {
var conf = confirm('Are you sure want to delete this record?');
if (!conf) {
return false;
}
var ThisElement = $(this);
var UrlToPass = 'action=delete&value=' + ThisElement.attr('href');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass,
success: function () {
LoadGrid();
}
});
return false;
});
// Add new record
// Add new record when the table is empty
$('body').delegate('.gridder_insert', 'click', function () {
$('#norecords').hide();
$('#addnew').slideDown();
return false;
});
// Add new record when the table in non-empty
$('body').delegate('.gridder_addnew', 'click', function () {
$('html, body').animate({scrollTop: $('.as_gridder').offset().top}, 250); // Scroll to top gridder table
$('#addnew').slideDown();
return false;
});
// Cancel the insertion
$('body').delegate('.gridder_cancel', 'click', function () {
LoadGrid()
return false;
});
// For datepiker
$("body").delegate(".gridder_add.datepiker", "focusin", function () {
var ThisElement = $(this);
$(this).datepicker({
dateFormat: 'yy/mm/dd'
});
});
// Pass the values to ajax page to add the values
$('body').delegate('#gridder_addrecord', 'click', function () {
// Do insert vaidation here
if ($('#fname').val() == '') {
$('#fname').focus();
alert('Enter the First Name');
return false;
}
if ($('#lname').val() == '') {
$('#lname').focus();
alert('Enter the Last Name');
return false;
}
if ($('#age').val() == '') {
$('#age').focus();
alert('Enter the Age');
return false;
}
if ($('#profession').val() == '') {
$('#profession').focus();
alert('Select the Profession');
return false;
}
if ($('#date').val() == '') {
$('#date').focus();
alert('Select the Date');
return false;
}
// Pass the form data to the ajax page
var data = $('#gridder_addform').serialize();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: data,
success: function () {
LoadGrid();
}
});
return false;
});
});
</script>
</head>
<body>
<header>
<img src="images/qes_logob.png" alt="logo">
<button class="hamburger">☰</button>
<button class="cross">˟</button>
</header>
<div class="menu">
<ul>
<a href="encodeinterview.php">
<li>Encode Grades</li>
</a>
<a href="viewinterview.php">
<li>View Grades</li>
</a>
<a href="../index.php">
<li>Logout</li>
</a>
</ul>
</div>
<script>
$(function () {
$(".cross").hide();
$(".menu").hide();
$(".hamburger").click(function () {
$(".menu").slideToggle("slow", function () {
$(".hamburger").hide();
$(".cross").show();
});
});
$(".cross").click(function () {
$(".menu").slideToggle("slow", function () {
$(".cross").hide();
$(".hamburger").show();
});
});
});
</script>
<form>
<h1>Exam Dates</>
<select name="examdate" id="examDate" onchange="LoadGrid(this.value)">
<option>Select Exam Date</option>
<?php
while ($row = mysql_fetch_array($queryselect)) {
echo "<option value={$row['examdateno']}>{$row['examdate']}</option>\n";
}
?>
</select>
</form>
<div class="as_wrapper">
<div class="as_grid_container">
<div class="as_gridder" id="as_gridder"></div> <!-- GRID LOADER -->
</div>
</div>
</body>
</html>
AJAX
<?php
include 'configuration.php';
include 'functions/functions.php';
$action = $_REQUEST['action'];
$q = intval($_POST['q']);
switch($action) {
case "load":
$query = mysql_query("select s.sno, s.fname, s.lname, s.examdate, s.interviewgrade, s.gwa from student s inner join tbl_examdate e on s.examdate=e.examdate where e.examdateno=$q");
$count = mysql_num_rows($query);
if($count > 0) {
while($fetch = mysql_fetch_array($query)) {
$record[] = $fetch;
}
}
$department = array('Software Architect', 'Inventor', 'Programmer', 'Entrepreneur');
?>
<table class="as_gridder_table">
<tr class="grid_header">
<td><div class="grid_heading">Sno</div></td>
<td><div class="grid_heading">First Name</div></td>
<td><div class="grid_heading">Last Name</div></td>
<td><div class="grid_heading">Age</div></td>
<td><div class="grid_heading">Profession</div></td>
<td><div class="grid_heading">Date</div></td>
<td><div class="grid_heading">Actions</div></td>
</tr>
<tr id="addnew">
<td> </td>
<td colspan="6">
<form id="gridder_addform" method="post">
<input type="hidden" name="action" value="addnew" />
<table width="100%">
<tr>
<td><input type="text" name="fname" id="fname" class="gridder_add" /></td>
<td><input type="text" name="lname" id="lname" class="gridder_add" /></td>
<td><input type="text" name="age" id="age" class="gridder_add" /></td>
<td><select name="profession" id="profession" class="gridder_add select">
<option value="">SELECT</option>
<?php foreach($department as $departments) { ?>
<option value="<?php echo $departments; ?>"><?php echo $departments; ?></option>
<?php } ?>
</select></td>
<td><input type="text" name="date" id="date" class="gridder_add datepiker" /></td>
<td>
<input type="submit" id="gridder_addrecord" value="" class="gridder_addrecord_button" title="Add" />
<img src="images/delete.png" alt="Cancel" title="Cancel" /></td>
</tr>
</table>
</form>
</tr>
<?php
if($count <= 0) {
?>
<tr id="norecords">
<td colspan="7" align="center">No records found <img src="images/insert.png" alt="Add New" title="Add New" /></td>
</tr>
<?php } else {
$i = 0;
foreach($record as $records) {
$i = $i + 1;
?>
<tr class="<?php if($i%2 == 0) { echo 'even'; } else { echo 'odd'; } ?>">
<td><div class="grid_content sno"><span><?php echo $i; ?></span></div></td>
<td><div class="grid_content editable"><span><?php echo $records['fname']; ?></span><input type="text" class="gridder_input" name="<?php echo encrypt("fname|".$records['id']); ?>" value="<?php echo $records['fname']; ?>" /></div></td>
<td><div class="grid_content editable"><span><?php echo $records['lname']; ?></span><input type="text" class="gridder_input" name="<?php echo encrypt("lname|".$records['id']); ?>" value="<?php echo $records['lname']; ?>" /></div></td>
<td><div class="grid_content editable"><span><?php echo $records['age']; ?></span><input type="text" class="gridder_input" name="<?php echo encrypt("age|".$records['id']); ?>" value="<?php echo $records['age']; ?>" /></div></td>
<td><div class="grid_content editable"><span><?php echo $records['profession']; ?></span>
<select class="gridder_input select" name="<?php echo encrypt("profession|".$records['id']); ?>">
<?php foreach($department as $departments) { ?>
<option value="<?php echo $departments; ?>" <?php if($departments == $records['profession']) { echo 'selected="selected"'; } ?>><?php echo $departments; ?></option>
<?php } ?>
</select>
</div></td>
<td><div class="grid_content editable"><span><?php echo date("Y/m/d", strtotime($records['posted_date'])); ?></span><input type="text" class="gridder_input datepicker" name="<?php echo encrypt("posted_date|".$records['id']); ?>" value="<?php echo date("Y/m/d", strtotime($records['posted_date'])); ?>" /></div></td>
<td>
<img src="images/insert.png" alt="Add New" title="Add New" />
<img src="images/delete.png" alt="Delete" title="Delete" /></td>
</tr>
<?php
}
}
?>
</table>
<?php
break;
case "addnew":
$fname = isset($_POST['fname']) ? mysql_real_escape_string($_POST['fname']) : '';
$lname = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$age = isset($_POST['age']) ? mysql_real_escape_string($_POST['age']) : '';
$profession = isset($_POST['profession']) ? mysql_real_escape_string($_POST['profession']) : '';
$date = isset($_POST['date']) ? mysql_real_escape_string($_POST['date']) : '';
mysql_query("INSERT INTO `grid` (fname, lname, age, profession, posted_date) VALUES ('$fname', '$lname', '$age', '$profession', '$date')");
break;
case "update":
$value = $_POST['value'];
$crypto = decrypt($_POST['crypto']);
$explode = explode('|', $crypto);
$columnName = $explode[0];
$rowId = $explode[1];
if($columnName == 'posted_date') { // Check the column is 'date', if yes convert it to date format
$datevalue = $value;
$value = date('Y-m-d', strtotime($datevalue));
}
$query = mysql_query("UPDATE `grid` SET `$columnName` = '$value' WHERE id = '$rowId' ");
break;
case "delete":
$value = decrypt($_POST['value']);
$query = mysql_query("DELETE FROM `grid` WHERE id = '$value' ");
break;
}
?>
You are not passing exam date in your ajax, i e q, but you are using that in $_POST, so pass the value from ajax to your file.
function LoadGrid(dte) {
var gridder = $('#as_gridder');
var UrlToPass = 'action=load';
var value = $('#examdate').val();
gridder.html('loading..');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {action:"load",q:dte}, <----- this line.
success: function (responseText) {
gridder.html(responseText);
}
});
}

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 }
?>

How to update my sql table with out page refresh in 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;
});
});

Categories