jQuery AJAX POST to PHP file to UPDATE database not updating - php

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

Related

How to post data (form) without page refresh PHP, jQuery, Ajax

Please help me how to submit form (comments) without page refresh for
HTML markup:
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="submit" id="comq"name="compost" class="butn2">post comment</button>
</form>
PHP code (pnf.php):
if(isset($_POST["compost"]))
{
$comment=$_POST['comments'];
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if($stmt)
{
echo "hello world";
}
}
jQuery and Ajax:
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
I have tried many times and don't know what mistake I made, Ajax and jQuery are not working, please anyone help - thanks in advance
You have made couple of mistakes.
First:: You should put button type="button" in your HTML form code
Second:: You have made a syntax error. $("#comment").vol(); should be replaced with $("#comment").val(); in your jQuery AJAX
As you mentioned that you have to send request without refreshing page I modified your JS-code with preventing default submitting form:
$(document).ready(function () {
$("#commentf").submit(function (e) {
e.preventDefault();
var comment = $("#comment").val();
$.ajax({
type: "POST",
url: "pnf.php",
data: {
"done": 1,
"comments": comment
},
success: function (data) {
}
})
});
});
Javascript
$('form').on('submit', function(event){
event.preventDefault();
event.stopPropagination();
var dataSet = {
comment: $('#comment').val();
}
$.ajax({
url: "link.to.your.api/action=compost",
data: dataSet,
method: 'post',
success: function(data){
console.log('request in success');
console.log(data);
},
error: function(jqXHR) {
console.error('request in error');
console.log(jqXHR.responseText');
}
});
});
PHP
$action = filter_input(INPUT_GET, 'action');
swicht($action){
case 'compost':
$comment = filter_input(INPUT_POST, 'comment');
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if(!$stmt)
{
http_response_code(400);
echo 'internal error';
}
echo 'your data will be saved';
break;
default:
http_response_code(404);
echo 'unknown action';
}
you have to prevent the submit on the form (look in javascript).
after that you send the request to the server and wait for success or error.
in php try to do it with a switch case. and try to not touch super globals directly, use filter_input function.
hope this helps
Modified JQuery Code...
$( document ).ready(function() {
console.log( "ready!" );
$("#comq").click(function() {
var comment=$("#comment").val();
console.log('comment : '+comment);
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
HTML Code
<form id="commentf" method="post">
<textarea class="textinput" id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<input type="button" id="comq" name="compost" class="butn2" value="Post Comment">
</form> </div>
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="button" id="comq"name="compost" class="butn2">post comment</button>
</form>
script
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
PHP code (pnf.php):
comment=$_POST['comments'];
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
if($stmt)
{
echo "hello world";
}
if you are using jquery make sure to include jquery libraries before your script file.
latest jquery cdn minified version
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
example
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="yourjsfile.js" type="text/javascript"></script>

how to insert data with ajax and php without page refresh

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

Ajax doesn't post inline table edit

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

jquery/php form in modal window

I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.

Delete record using jquery ajax but table is loaded again

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;
});

Categories