I have the following code and the SELECT is working correctly to pull in the form data, however, the UPDATE statement is not working. Any suggestions on what could be corrected to make it work would be greatly appreciated.
<?php
include 'includes/config.php';
require_once('includes/auth.php');
if ( isset( $_GET['aj'] ) && $_GET['aj'] == '1' ) {
if ( isset( $_GET['ax']) && $_GET['ax'] == 'education_details' ) {
$sql =
<<<SQL
SELECT *
FROM education
WHERE id = '{$_GET['rid']}'
ORDER BY date_completed DESC
SQL;
$sql_result = mysql_query($sql) or die("Get education detail error: " . mysql_error());
while ( $row = mysql_fetch_assoc($sql_result) ) {
$education_info = array(
'member_id' => $row['member_id'],
'name' => $row['name'],
'degree' => $row['degree'],
);
}
echo json_encode($education_info);
}
exit;
}
if ( isset($_POST['aj']) && $_POST['aj'] == '1' ) {
if (isset( $_POST['ax']) && $_POST['ax'] == 'save' ) {
$sql=
<<<SQL
UPDATE education
SET name = '{$education_info['name']}',
degree = '{$education_info['degree']}'
WHERE id = '{$education_info['rid']}'
SQL;
}
// echo json_encode($education_info);
exit;
}
?>
<html>
<head>
<link type="text/css" href="css/ui-lightness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#accordion').accordion({
header: "h3",
collapsible: true,
active: false
});
$('#dialog').dialog({
autoOpen: false,
open: true,
modal: true,
width: 525,
buttons: {
"Cancel": function() {
$(this).dialog("close");
}
}
});
$('#dialog_link').click(function() {
$('#dialog').dialog('open');
});
education_details.initialize();
});
var education_details = {
url : '<?= $_SERVER['PHP_SELF']; ?>',
initialize : function() {
$('#dialog_edit').dialog({
autoOpen: false,
open: true,
modal: true,
width: 525,
buttons: {
"Save" : function() {
$.post("educationie.php", {"aj":"1", "ax":"save" , "rid":$(this).attr("id")}, function(data) {
alert(data);
}, "json");
// $(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$('.edit_open').click(education_details.open);
},
open : function() {
$('#dialog_edit').dialog('open');
$.get(education_details.url, {"aj":"1","ax":"education_details","rid":$(this).attr("id")}, education_details.education_details_success, "json");
},
education_details_success : function(data) {
$("#dialog_edit input[name=name]").val(data.name);
$("#dialog_edit input[name=degree]").val(data.degree);
}
};
</script>
</head>
<body>
<?php
if ( $_POST['ax'] == "new" ) {
// echo "DID IT GO HERE"; exit;
$sql=<<<SQL
INSERT INTO education (member_id, name, degree)
VALUES (
'{$_SESSION['SESS_MEMBER_ID']}',
'{$_POST['name']}',
'{$_POST['degree']}'
)
SQL;
if(mysql_query( $sql ) or die ( "Insert failed." . mysql_error()) );
// echo $sql; exit;
// header( "Location: education.php");
}
?>
<button id="dialog_link" class="ui-button ui-state-default ui-corner-all">Add New</button>
<br>
<div id="dialog" title="Add New" style="display:none;">
<form action="<?= $_SERVER["PHP_SELF"];?>" method="post">
<input type="hidden" name="ax" value="new">
Institution<br><input type="text" name="name" /><br>
Degree(s) Earned<br><input type="text" name="degree" /><br>
<input type="submit" name="SUBMIT" value="submit" class="ui-button ui-state-default ui-corner-all"/>
</div>
<div id='dialog_edit' title='Edit' style="display:none;">
<form action="<?= $_SERVER["PHP_SELF"];?>" method="post">
Institution<br><input type="text" name="name" /><br>
Degree(s) Earned<br><input type="text" name="degree" /><br>
</form>
</div>
<div id="accordion">
<?
$sql = mysql_query(" SELECT *
FROM education
WHERE member_id = '" . $_SESSION['SESS_MEMBER_ID'] . "'
ORDER BY date_completed DESC");
while($row = mysql_fetch_array($sql)){
echo "<h3><a href=#>" . $row['name'] ."</a></h3>";
echo "<div>
<table>
<tbody>
<tr>
<td valign='top'>
<a id=\"" . $row['id'] . "\" class=\"edit_open\" href=\"javascript:void(0)\">Edit</a>
<br> Degree(s): ". $row['degree'] .
"</td>
<td style='padding-left:85px;'>
</td>
</tr>
</tbody>
</table>
</div>";
}
mysql_close($con);
?>
</div>
</body>
</html>
try setting error_reporting(E_ALL) and checking the errors in firebug...
the update references an undefined variable:
$education_info['name']}'
it wasn't set at that point, you probably want to use $_POST['name'] or something instead
(you might want to bind parameters in queries as it's easier as well)
You forgot to post the RID = where id
<?php
include 'includes/config.php';
require_once('includes/auth.php');
if ( isset( $_GET['aj'] ) && $_GET['aj'] == '1' ) {
if ( isset( $_GET['ax']) && $_GET['ax'] == 'education_details' ) {
$sql =
<<<SQL
SELECT *
FROM education
WHERE id = '{$_GET['rid']}'
ORDER BY date_completed DESC
SQL;
$sql_result = mysql_query($sql) or die("Get education detail error: " . mysql_error());
while ( $row = mysql_fetch_assoc($sql_result) ) {
$education_info = array(
'id' => $row['id'],
'member_id' => $row['member_id'],
'name' => $row['name'],
'degree' => $row['degree'],
);
}
echo json_encode($education_info);
}
exit;
}
if ( isset($_POST['aj']) && $_POST['aj'] == '1' ) {
if (isset( $_POST['ax']) && $_POST['ax'] == 'save' ) {
$sql=
<<<SQL
UPDATE education
SET name = '{$_POST['name']}',
degree = '{$_POST['degree']}'
WHERE id = '{$_POST['rid']}'
SQL;
}
$sql_result = mysql_query($sql) or die("Get education update error: " . mysql_error());
// echo json_encode($education_info);
exit;
}
?>
<!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" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script type="text/javascript">
$(document).ready(function(){
$('#accordion').accordion({
header: "h3",
collapsible: true,
active: false
});
$('#dialog').dialog({
autoOpen: false,
open: true,
modal: true,
width: 525,
buttons: {
"Cancel": function() {
$(this).dialog("close");
}
}
});
$('#dialog_link').click(function() {
$('#dialog').dialog('open');
});
education_details.initialize();
});
var education_details = {
url : '<?= $_SERVER['PHP_SELF']; ?>',
initialize : function() {
$('#dialog_edit').dialog({
autoOpen: false,
open: true,
modal: true,
width: 525,
buttons: {
"Save" : function() {
$.post("<?= $_SERVER['PHP_SELF']; ?>", {"aj":"1", "ax":"save" , "rid":$("#dialog_edit input[name=rid]").val(), "name":$("#dialog_edit input[name=name]").val(), "degree": $("#dialog_edit input[name=degree]").val()}, function(data) {
alert(data);
}, "json");
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$('.edit_open').click(education_details.open);
},
open : function() {
$('#dialog_edit').dialog('open');
$.get(education_details.url, {"aj":"1","ax":"education_details","rid":$(this).attr("id")}, education_details.education_details_success, "json");
},
education_details_success : function(data) {
$("#dialog_edit input[name=name]").val(data.name);
$("#dialog_edit input[name=degree]").val(data.degree);
$("#dialog_edit input[name=rid]").val(data.id);
}
};
</script>
</head>
<body>
<?php
if (!empty($_POST['ax']) && $_POST['ax'] == "new" ) {
// echo "DID IT GO HERE"; exit;
$sql=<<<SQL
INSERT INTO education (member_id, name, degree)
VALUES (
'{$_SESSION['SESS_MEMBER_ID']}',
'{$_POST['name']}',
'{$_POST['degree']}'
)
SQL;
if(mysql_query( $sql ) or die ( "Insert failed." . mysql_error()) );
//echo $sql; exit;
// header( "Location: education.php");
}
?>
<button id="dialog_link" class="ui-button ui-state-default ui-corner-all">Add New</button>
<br>
<div id="dialog" title="Add New" style="display:none;">
<form action="<?= $_SERVER["PHP_SELF"];?>" method="post">
<input type="hidden" name="ax" value="new">
Institution<br><input type="text" name="name" /><br>
Degree(s) Earned<br><input type="text" name="degree" /><br>
<input type="submit" name="SUBMIT" value="submit" class="ui-button ui-state-default ui-corner-all"/>
</form>
</div>
<div id='dialog_edit' title='Edit' style="display:none;">
<form action="<?= $_SERVER["PHP_SELF"];?>" method="post">
<input type="hidden" name="rid">
Institution<br><input type="text" name="name" /><br>
Degree(s) Earned<br><input type="text" name="degree" /><br>
</form>
</div>
<div id="accordion">
<?
$sql = mysql_query(" SELECT *
FROM education
WHERE member_id = '{$_SESSION['SESS_MEMBER_ID']}'
ORDER BY date_completed DESC");
while($row = mysql_fetch_array($sql)){
echo "<h3><a href=#>" . $row['name'] ."</a></h3>";
echo "<div>
<table>
<tbody>
<tr>
<td valign='top'>
<a id=\"" . $row['id'] . "\" class=\"edit_open\" href=\"javascript:void(0)\">Edit</a>
<br> Degree(s): ". $row['degree'] .
"</td>
<td style='padding-left:85px;'>
</td>
</tr>
</tbody>
</table>
</div>";
}
mysql_close($con);
?>
</div>
</body>
</html>
Related
I want to delete some records by using jQuery, i don't know what the error is, i cannot delete records. when i click edit button the records, it seems to work fine and record can be modified, but when i click delete button it does not work. here is my code:
index.php
<?php
include('database_connection.php');
$query = "SELECT * FROM apps_countries ORDER BY country_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<title>How to Make Editable Select Box using jQuery with PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" href="jquery-editable-select.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery-editable-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<h2 align="center">How to Make Editable Select Box using jQuery with PHP</h2><br />
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form method="post" id="sample_form">
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="form-group">
<label>Select Country</label>
<select name="country" id="country" class="form-control">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["country_name"].'">'.$row["country_name"].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<input type="hidden" name="action" id="action" value="add" />
<input type="hidden" name="hidden_id" id="hidden_id" value="" />
<input type="hidden" name="hidden_id1" id="hidden_id1" value="" />
<input type="submit" name="Save" id="save" class="btn btn-success" value="Save" />
</div>
</form>
<br />
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Country</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
fetch_data();
function fetch_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('tbody').html(data);
}
});
}
$('#country').editableSelect();
$('#sample_form').on('submit', function(event){
event.preventDefault();
if($('#name').val() == '')
{
alert("Enter Name");
return false;
}
else if($('#country').val() == '')
{
alert("Select Country");
return false;
}
else
{
$.ajax({
url:"action.php",
method:"POST",
data:$(this).serialize(),
success:function(data)
{
alert(data);
$('#sample_form')[0].reset();
$('#action').val("add");
$('#save').val('Save');
fetch_data();
}
});
}
});
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:'json',
success:function(data)
{
$('#hidden_id').val(id);
$('#name').val(data.name);
$('#country').val(data.country);
$('#action').val("edit");
$('#save').val('Edit');
}
});
});
$(document).on('click', '.Delete', function(){
var id = $(this).attr("id");
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:'json',
success:function(data)
{
$('#hidden_id1').val(id);
$('#name').val(data.name);
$('#country').val(data.country);
$('#action').val("delete");
$('#save').val('Delete');
}
});
});
});
</script>
fetch.php
<?php
include('database_connection.php');
$query = "SELECT * FROM sample_data ORDER BY id DESC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["country"].'</td>
<td><button type="button" name="edit" class="btn btn-primary btn-xs edit" id="'.$row["id"].'">Edit</button></td>
<td><button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row["id"].'">Delete</button></td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="3" align="center">Data not found</td>
</tr>
';
}
echo $output;
?>
action.php
<?php
include('database_connection.php');
if(isset($_POST["action"]))
{
if($_POST["action"] == "add")
{
$data = array(
':name' => $_POST["name"],
':country' => $_POST["country"]
);
$query = "
INSERT INTO sample_data (name, country)
VALUES (:name, :country)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
echo 'Data Inserted';
}
}
if($_POST["action"] == 'fetch_single')
{
$query = "SELECT * FROM sample_data WHERE id='".$_POST["id"]."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output['name'] = $row["name"];
$output['country'] = $row["country"];
}
echo json_encode($output);
}
if($_POST["action"] == "edit")
{
$data = array(
':name' => $_POST["name"],
':country' => $_POST["country"],
':id' => $_POST["hidden_id"]
);
$query = "
UPDATE sample_data
SET name = :name, country = :country
WHERE id = :id
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
echo 'Data Updated';
}
}
if($_POST["action"] == "delete")
{
$data = array(
':name'=> $_POST["name"],
':country' => $_POST["country"],
':id' => $_POST["hidden_id1"]);
$query = "DELETE * FROM sample_data WHERE id='".$_POST["id"]."'";
$statement = $connect ->prepare($query);
if($statement->execute($data))
{
echo 'data deleted';
}
}
}
?>
database_connection.php
<?php $connect = new PDO("mysql:host=localhost;dbname=sampl1", "root", ""); ?>
instead of button you can give tag like this
Delete
and featch id using $_REQUEST['id']
<?php
$id =$_REQUEST['id'];
// sending query
$query = "DELETE * FROM sample_data WHERE id='".$_POST["id"]."'";
$statement = $connect ->prepare($query);
if($statement->execute($data))
{
echo 'data deleted';
}
?>
I think your error could be here in this piece of code here.
Sometimes JQuery can be case sensitive.
Change this:
$(document).on('click', '.Delete', function(){
to this:
$(document).on('click', '.delete', function(){
At:
$(document).on('click', '.Delete', function(){ <-- CHANGE THIS LINE HERE AND LEMME KNOW IF IT WORKS
var id = $(this).attr("id");
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:'json',
success:function(data)
{
$('#hidden_id1').val(id);
$('#name').val(data.name);
$('#country').val(data.country);
$('#action').val("delete");
$('#save').val('Delete');
}
});
});
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 }
?>
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;
});
});
I am using ajax, to simply update the DB..The problem is that after update, I use a alert to display the output. However when I click the alert box,The entire page reloads. Is there any way to avoid it??
First Up(trailnew.php)- A select drop down button with three button.
When I choose the select drop down button and click edit button
Second- I get a form from aanew.php(with some other things)
Third-Validation of this form is done in aanew.php
Target-I want the success result to be viewed in trailnew.php, without reloads.
Any alternative ideas is highly welcomed..This is new to me..Thanks..
Here is the code.
Trailnew.php
<?php
session_start();
include('connect.php');
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$(document).ready(function(){
$("#form1").validate({
debug: false,
rules: {
plid:"required",
},
messages: {
plid: "Please select a pack name id..",
},
submitHandler: function(form) {
$.ajax
({
type: "POST",
url: "aanew.php",
data: $('#form1').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
});
</script>
</head>
<body>
<div class="result3"></div>
Packing List
</br>
<form id="form1" name="form1" action="" method="post">
<?php
echo '<select name="plid" id="plid">';
echo '<option value="" selected="selected">--Select the Pack Name--</option>';
$tempholder = array();
$sql="SELECT CONCAT( p.pl_no, '_', DATE_FORMAT( p.pl_dt, '%d/%m/%Y' ) , '_', g.acname ) AS plname, g.gl_id,p.pl_no,p.pl_dt,p.no_box,p.pl_id,g.acname FROM packlist p, glmast g WHERE g.gl_id = p.gl_id ORDER BY pl_dt DESC , pl_no DESC LIMIT 30";
$query = mysql_query($sql) or die(mysql_error());
$nr = mysql_num_rows($query);
for ($i=0; $i<$nr; $i++){
$r = mysql_fetch_array($query);
if (!in_array($r['plname'], $tempholder)){
$tempholder[$i] = $r['plname'];
echo "<option value='$r[pl_id]'>".$r["plname"]."</option>";
}
}
echo '</select>';
?><br/>
<input type="submit" name="delete" value="Delete"/><br/>
<input type="submit" name="edit" id="edit" value="Edit"/><br/>
</form>
<form>
<input type="submit" name="new" id="new" class="new" value="New" /><br/>
</form>
<?php
$e=isset($_POST['form2']) && $_POST['form2'];
if($e)
{
echo "Done";
}
?>
<div id="result1"></div>
</body>
</html>
aanew.php
<?php
session_start();
include('connect.php');
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$("#form2").validate({
debug: false,
rules: {
plnoedit:"required",
pldtedit:"required",
noboxedit:"required",
glidedit:"required",
},
messages: {
plnoedit: "Please select a pack list id..",
pldtedit: "Please select a item id id..",
noboxedit: "Please select a quantity id..",
glidedit: "Please select a value id..",
},
submitHandler: function(form) {
$.ajax
({
type: "POST",
url: "trailnew.php",
data: $('#form2').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
</script>
</head>
<body>
<div id="#result1"></div>
<?php
$e=isset($_POST['plid']) && $_POST['plid'];
$f=isset($_POST['edit']) && $_POST['edit'];
if($e&&$f)
{
$id=$_POST['plid'];
$query5=mysql_query("SELECT g.gl_id, p.pl_no, p.pl_dt, p.no_box, p.pl_id,g.acname
FROM packlist p, glmast g
WHERE g.gl_id = p.gl_id
AND p.pl_id ='".$id."'
LIMIT 0 , 30") or die(mysql_error());
$row=mysql_fetch_array($query5);
$pl_no=$row['pl_no'];
$pl_dt=$row['pl_dt'];
$no_box=$row['no_box'];
$acname=$row['acname'];
?>
<form name="form2" id="form2" method="post" action="">
<P>
<LABEL for="plnoedit">PackList No
<INPUT type="text" id="plnoedit" name="plnoedit" value= <?php echo $pl_no; ?> /></LABEL><BR><BR>
<input type="hidden" name="myFormsName" value="form5id" id="myFormsName">
<LABEL for="pldtedit">Date
<INPUT type="text" id="pldtedit" name="pldtedit" value= <?php echo $pl_dt; ?> /></LABEL><BR><BR>
<LABEL for="noboxedit">Box No
<INPUT type="text" id="noboxedit" name="noboxedit" value= <?php echo $no_box; ?> /></LABEL><BR><BR>
<LABEL for="glidedit">Party Name
<INPUT type="text" id="glidedit" name="glidedit" value= <?php echo $acname; ?> /></LABEL><BR><BR>
<INPUT type="submit" id="editsubmit" name="editsubmit" value="Submit"> <INPUT type="reset">
</P>
</form>
<?php
//pagination starts
$id=$_POST['plid'];
$per_page = 4;
$query12=mysql_query("SELECT `pld_id`,`pl_id`, `item_id`, `quantity`, `size`, `potency`, `box` FROM `packlistdtl` WHERE pl_id ='".$id."' GROUP BY `box` ORDER BY `box` desc") or die(mysql_error());
// figure out the total pages in the database
$total_results = mysql_num_rows($query12);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='view.php?page=$i'>$i</a> ";
}
echo "</p>";
// display data in table
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Box</th> <th>Item Name</th> <th>Size</th> <th>Potency</th> <th>Quantity</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
for ($i = $start; $i < $end; $i++)
{
$item_id=mysql_result($query12, $i, 'item_id');
$query13=mysql_query("SELECT `item_name` FROM `itemmast` WHERE item_id ='".$item_id."'") or die(mysql_error());
$row1=mysql_fetch_array($query13);
$item_name=$row1['item_name'];
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . mysql_result($query12, $i, 'box') . '</td>';
echo '<td>' .$item_name. '</td>';
echo '<td>' . mysql_result($query12, $i, 'size') . '</td>';
echo '<td>' . mysql_result($query12, $i, 'potency') . '</td>';
echo '<td>' . mysql_result($query12, $i, 'quantity') . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
// pagination
}
?>
</body>
</html>
Probably need to return false from click handler of link or button to prevent the default action
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({ ... });