I've got a table of which I'm trying to add inline-edit to, but I'm really new to ajax. The JQuery code itself works, I can see the td's changing into input fields but I'm having trouble with posting the data.
When I click away from the table td that I'm trying to edit, it's suppose to post the data. But when I do that and refresh the page, the generated table isn't updated nor can I see changes in the database. It doesn't display an error, it only refreshes the page.
projectlist database table
projectid | Klant
4 | mike
12 | peterson
PHP
while($row = mysql_fetch_array($resultaat, MYSQL_ASSOC)){
$id = $row['projectid'];
<tr id="<?php echo $id ?>" class="tredit">
<form action="" method="post">
<td>
<span id="klant_<?php echo $id ?>" class="text"><?php echo $row["Klant"] ?></span>
<input type="text" class="ip" id="klant_ip_<?php echo $id ?>" value="<?php echo $row["Klant"] ?>">
</td>
</form>
</tr>
}
Ajax
$(document).ready(function(){
$(".tredit").click(function(){
var ID=$(this).attr('id');
$("#klant_"+ID).hide();
$("#klant_ip_"+ID).show();
}).change(function(){
var ID=$(this).attr('id');
var first=$("#klant_ip_"+ID).val();
var dataString = 'id='+ ID +'&Klant='+first;
//alert(dataString);
if(first.length > 0){
$.ajax({
type: "POST",
url: "post_table.php",
//data: dataString,
data: dataString,
cache: false,
success: function(html){
$("#klant_"+ID).html(first);
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
}
});
}else{
alert('Input something');
}
});
$(".ip").mouseup(function() {
return false
});
$(document).mouseup(function(){
$(".ip").hide();
$(".text").show();
});
});
post_table.php
<?php
include('config.php');
$klant = $_POST['Klant'];
$id = $_POST['id'];
$query = "update projectlist set Klant='$klant' where id='$id'";
mysql_query($query, $con);
?>
Solution
I got it working. It never ever occured to me to thoroughly check the post_table.php.
where id='$id' is wrong, it must be where projectid='$id'.
$(document).ready(function(){
$(".tredit").click(function(){
var ID=$(this).attr('id');
$("#klant_"+ID).hide();
$("#klant_ip_"+ID).show();
})
$(".tredit").change(function(){
var ID=$(this).attr('id');
var first=$("#klant_ip_"+ID).val();
var dataString = {"id":ID,"Klant":first};
//alert(dataString);
$("#klant_"+ID).html('<img src="load.gif" />');
if(first.length > 0){
$.ajax({
type: "POST",
url: "post_table.php",
data: dataString,
cache: false,
success: function(html){
$("#klant_"+ID).html(first);
}
});
}else{
alert('Input something');
}
});
$(".ip").mouseup(function() {
return false
});
$(document).mouseup(function(){
$(".ip").hide();
$(".text").show();
});
});
The php has to return something on the page
<?php
include('config.php');
$klant = $_POST['Klant'];
$id = $_POST['id'];
$query = "update projectlist set Klant='$klant' where id='$id'";
mysql_query($query, $con);
echo "success";
?>
Related
I real need your help since I'm a beginner in php and Ajax. My problem is that, I can not send data in the database via my appended form in post.php, also when the button of id #reply clicked it sends empty data to database by refreshing the page. When the reply link is pressed I only get the Result of reply link to be shown without other information (name and comment). I need your help to make my appanded form to be able to add/send data to the database without refreshing the page, I also need to disable the form from index.php to make replies when the reply button / link is pressed. Thank you.
post.php
<?php include("config.php"); //inserting
$action=$_POST["action"];
if($action=="addcomment"){
$author = $_POST['name'];
$comment_body = $_POST['comment_body'];
$parent_id = $_POST['parent_id'];
$q = "INSERT INTO nested (author, comment, parent_id) VALUES ('$author', '$comment_body', $parent_id)";
$r = mysqli_query($conn, $q);
if(mysqli_affected_rows($conn)==1) { header("location:index.php");}
else { }
}
// showing data
error_reporting( ~E_NOTICE );
function getComments($conn, $row) {
$action=$_POST["action"];
if($action=="showcomment"){ $id = $row['id'];
echo "<li class='comment'><div class='aut'>".$row['author']."</div><div class='comment-body'>".$row['comment']."</div>";
echo "<a href='#comment_fo' class='reply' id='".$row['id']."'>Reply</a>";
$result = mysqli_query($conn, "SELECT * FROM `nested` WHERE parent_id = '$id' ORDER BY `id` DESC");
}
if(mysqli_num_rows($result)>0) { echo "<ul>";
while($row = mysqli_fetch_assoc($result)) { getComments($conn,$row); }
echo "</ul>"; } echo "</li>";
}
if($action=="showcomment"){
$q = "SELECT * FROM nested WHERE parent_id = '".$row['id']."' ORDER BY `id` DESC";
$r = mysqli_query($conn, $q);
while($row = mysqli_fetch_assoc($r)){ getComments($conn,$row); }
}
?>
<!DOCTYPE HTML><head><script type='text/javascript'>
$(document).ready(function(){
$("a.reply").one("click", function() {
var id = $(this).attr("id");
var parent = $(this).parent();
$("#parent_id").attr("value", id);
parent.append(" <br /><div id='form'><form><input type='text' name='name' id='name'><textarea name='comment_body' id='comment_body'></textarea><input type='hidden' name='parent_id' id='parent_id' value='0'><button id='reply'>Reply</button></form></div>");
$("#reply").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){ showComment(); }
});
});
});
});
</script></head></html>
//index.php
<html><head><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function showComment(){
$.ajax({
type:"post",
url:"post.php",
data:"action=showcomment",
success:function(data){ $("#comment").html(data); }
});
}
showComment();
$(document).ready(function(){
$("#button").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
</script></head><body>
<form id="form_comment">
<input type="text" name="name" id='name'/>
<textarea name="comment_body" id='comment_body'></textarea>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
<input type="button" id="button" value="Comment"/>
</form>
<div id="comment"></div> </body></html>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault(); //add this line to prevent reload
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
Here is a simple incomplete ajax example.
FromPage.php
Here is the ajax that I'd use. The variables can be set however you like.
<script type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
var name = "John Smith";
$.ajax({
url: 'toDB.php',
type: 'post',
dataType: 'html',
data: {
carArray: cars,
firstName: name
},
success: function(data) {
console.log(data); //Testing
}
});
</script>
toDB.ph
This is the second page - the one that writes the values to the database etc.
<?php
$cars = $_POST['carArray'];
$FirstName=$_POST['firstName'];
//Used to test - it will print out the array
print("<pre>");
print_r($cars);
print("</pre>");
//Do something with $cars array and $FirstName variable
?>
i want to populate two fields when some one fill up card no.
<input type="text" id="name" name="name" class="form-control" Value="<?php echo $grow['name']; ?>">
<input type="text" id="address" name="address" class="form-control" Value="<?php echo $grow['address']; ?>">
but this code populate field one by one. can any one suggest be better code for populating two fields from database. Thank you
jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k=$(this).val();
var q="name";
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q='+q,
cache: false,
success: function(data)
{
if(data){
$("#name").val(data);
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
$("#address").val(data);
}
}
});
}else
$("#name").val("");
$("#address").val("");
}
});
});
});
</script>
getresult.php
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select * from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
echo $row[$q];
?>
Try to extract both name and address from database and json them
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select address,name from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
$result = array(
'name'=>$row['name'],
'address'=>$row['address']);
echo json_encode($result);
After that parse them via jquery
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
var parsedData = jQuery.parseJSON(data);
$("#name").val(parsedData.name);
$("#address").val(parsedData.address);
}
}
});
Javascript Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k = $(this).val();
var q = "name";
$.ajax({
type: 'POST',
url: "getresult.php",
data: 'k='+k,
cache: false,
success: function(data)
{
var jsonArr = $.parseJSON(data);
if(typeof response =='object')
{
$("#name").val(jsonArr.name);
$("#address").val(jsonArr.address);
}
else
{
$("#name").val("");
$("#address").val("");
}
}
});
});
});
</script>
PHP Code:
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k = $_POST['k'];
$sql = mysql_query("select * from inward where krishi='$k'");
$row = mysql_fetch_assoc($sql);
echo json_encode(array('name' => $row['name'], 'address' => $row['address']);
?>
I am deleting records using jQuery and Ajax. The code I wrote deletes a record but the HTML table is loaded again, which means the page refreshes which I want to avoid.
Here is my code:
comment.php
<script type="text/javascript">
$(document).ready(function(){
function loadList(){
$.ajax({
url: "load_list.php",
cache: false,
success : function(html){
$(".name_list").html(html);
}
});
}
loadList();
$("#Submit").click(function() {
if($(":text").val().length==0)
{
// $(this).next().html("Field needs filling");
$(":text").after('<span class="errorkeyup">Field cannot be empty</span>');
//return false;
success = false;
}
else
{
var name=$("#name").val();
var message=$("#message").val();
$.ajax({
type:"post",
url:"save_list.php",
data:"name="+name+"&message="+message,
success:function(data){
loadList();
}
});
return false;
}
});
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var id = $(this).attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(){
loadList();
}
});
// }
return false;
});
});
</script>
</head>
<body>
<div id="form">
<form method="post" name="form" action="">
<div id="content">
Name : <input type="text" name="name" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
</div>
<input type="button" value="Submit" id="Submit">
</form>
</div>
<div class="name_list"></div>
</body>
loadlist.php
<?php
include('connection.php');
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<table border="1">';
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td>
<a id='".$row['id']."' href=delete.php?id=".$row['id']."&type=Delete class=delete_button>Delete</a></td>";
echo"<td>
<a id='".$row['id']."' href=comment.php?id=".$row['id']."&type=edit class=edit_button>Edit</a></td>";
echo '</tr>';
$i++;
}
echo'</table>';
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
When you do the $.ajax() call for $('.delete_button'), you shouldn't call your loadList() function there because that is what reloads the table, instead you should just remove the one entry that's deleted from the table.
Perhaps you can remove it with something similar to this, placed inside the delete button success callback:
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function()
{
$(this).parent().parent().remove();
}
});
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
in this code remove line
header("location: comment.php");
Final code would be,
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
echo '1';
} else {
echo '0';
}
exit;
?>
In delete function, after executing delete query, you need to echo '1' or '0'. Lets say echo '1'; when deleted successfully and echo '0' when delete not succeed. So based on 1 or 0 you can remove those deleted row from table by ,
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var obj = $(this);
var id = obj.attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(response){
if(response == '1') {
obj.parent.remove();
}
}
});
// }
return false;
});
I am trying to remove table row after successful ajax call, but it is not working. No errors in firebug, it deletes the row on the back-end PHP, just doesnt remove the tr. Here is my code:
function closelead(rowid){
var rowid = rowid;
$.ajax({
type: "POST",
url: "ajax/close.php",
data: "rowid="+ rowid,
success: function(html){
$(this).closest('tr').remove();
}
});
}
and the html:
<table id="companytable">
<tr id="top"><th>Business Name</th><th>Phone</th><th>Carrier</th><th>X-Date</th><th></th><th></th><th></th></tr>
<?php
$query = "SELECT * FROM leads WHERE user = '$user' ORDER BY wccompcode";
$selectlead = mysql_query($query)or die(mysql_error());
while($leadlist = mysql_fetch_array($selectlead)){
$compcode = $leadlist['wccompcode'];
$compcode = sprintf("%03s", $compcode);
$selcomp = mysql_query("SELECT carname FROM carrierlist WHERE carcode = '$compcode'")or die(mysql_error());
while($carrier = mysql_fetch_array($selcomp)){
$carrier1 = $carrier['carname'];
}
?>
<tr id="<?php echo $leadlist['ID'];?>"><td id="busname"><?php echo $leadlist['busname'];?></td><td><?php echo $leadlist['phone'];?></td><td><?php echo $carrier1;?></td><td><?php echo date("m/d/Y",strtotime($leadlist['wcxdate']));?></td><td><input type="button" value="Call Back" class="searchbutton" /></td><td><input type="button" onclick="closelead(<?php echo $leadlist['ID'];?>)" value="Close" class="searchbutton" /></td><td><input type="button" value="Soft Quote" class="searchbutton" /></td></tr>
<?
}
?>
</table>
Try
function closelead(rowid){
var rowid = rowid;
$.ajax({
type: "POST",
url: "ajax/close.php",
data: "rowid="+ rowid,
success: function(html){
$('#'+rowid).remove();
}
});
}
function closelead(rowid){
var rowid = rowid;
$.ajax({
type: "POST",
url: "ajax/close.php",
data: "rowid="+ rowid,
success: function(html){
$('#'+rowid).closest('tr').remove();
}
});
}
I'm trying to build a small CMS system, I want to use AJAX and jQuery to do so.
If I do not use AJAX the code works, I have no idea why the data is not being passed properly. AJAX success returns "Success"
Any help is appreciated.
Here is my Javascript:
$(document).ready(function(){
var aboutContent = $('#aboutContent').attr('value');
$('#aboutUpdate').submit(function() {
$.ajax({
type: "POST",
url: "scripts/update.php",
data: "aboutUpdate="+aboutContent,
beforeSend: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('processing...'); },
success: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('Saved Successfully!').delay(500).fadeOut(250); },
error: function(){ $('#aboutStatus').fadeIn(250).css('color', '#ff464a').html('An error occurred!').delay(500).fadeOut(250); }
});
return false;
});
});
Here is my HTML:
<?
$query = "SELECT * FROM pageContent WHERE page = 'about'";
$result = mysql_query($query);
while($rows = mysql_fetch_array($result)){
?>
<div class="pageContent">
<h2>About</h2>
<form id="aboutUpdate" method="post">
<textarea class="editor" id="aboutContent" cols="50" rows="20"><? echo $rows['content']; ?></textarea>
<input type="submit" value="Save Now"><span class="updateStatus" id="aboutStatus"></span>
</form>
</div>
<?
}
?>
Here is the PHP (scripts/update.php):
$aboutContent = mysql_real_escape_string($_POST['aboutUpdate']);
if(isset($_POST['aboutUpdate'])){
$query="UPDATE pageContent SET content='$aboutContent' WHERE page='about'";
$result=mysql_query($query)or die(mysql_error());
if($result){
echo "Success";
}
else{
echo "Update Error";
}
}
else{
header("location:http://google.com");
}
Fixed the issue. Here is how:
First on the TEXTAREA I need to specify the attribute
name="aboutUpdate"
so the PHP isset can pull the data.
Second, I noticed a variable was 'undefined' when submitting.
var aboutContent = $('#aboutContent').attr('value');
Here is the working Javascript:
$('#aboutUpdate').submit(function() {
$.ajax({
type: "POST",
url: "scripts/update.php",
data: { aboutUpdate: $('#aboutContent').attr('value') },
beforeSend: function(){
$('#aboutStatus').fadeIn(250).css('color', '#017c04').html('processing...');
},
success: function(){
$('#aboutStatus').fadeIn(250).css('color', '#017c04').html('Saved Successfully!').delay(2500).fadeOut(250);
},
error: function(){
$('#aboutStatus').fadeIn(250).css('color', '#ff464a').html('An error occurred!').delay(2500).fadeOut(250);
}
});
return false;
});
HTML:
<?
$query = "SELECT * FROM pageContent WHERE page = 'about'";
$result = mysql_query($query);
while($rows = mysql_fetch_array($result)){
?>
<div class="pageContent">
<h2>About</h2>
<form id="aboutUpdate" method="post">
<textarea class="editor" id="aboutContent" name="aboutUpdate" cols="50" rows="20"><? echo $rows['content']; ?></textarea>
<input type="submit" value="Save Now"><span class="updateStatus" id="aboutStatus"></span>
</form>
</div>
<?
}
?>
PHP update.php:
$aboutContent = mysql_real_escape_string($_POST['aboutUpdate']);
if(isset($_POST['aboutUpdate'])){
$query="UPDATE pageContent SET content='".$aboutContent."' WHERE page='about'";
$result=mysql_query($query)or die(mysql_error());
if($result){
echo "Success";
}
else{
echo "Update Error";
}
}
Try your Ajax function like this:
$.ajax({
type: "POST",
url: "scripts/update.php",
data: { aboutUpdate: aboutContent },
beforeSend: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('processing...'); },
success: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('Saved Successfully!').delay(500).fadeOut(250); },
error: function(){ $('#aboutStatus').fadeIn(250).css('color', '#ff464a').html('An error occurred!').delay(500).fadeOut(250); }
});
Notice the change in the POST data line.
Absolutely sure, that with this data: "aboutUpdate="+aboutContent you are sending something totaly wrong.
It should be data: {aboutUpdate: aboutContent}
Plus I'm not sure, that textarea actually has attribute value. Try
$('#aboutContent').val()
or
$('#aboutContent').text()