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
?>
Related
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";
?>
here is my view
<html>
<body>
<form method="post" name="myForm1" id="myForm1" enctype="multipart/form-data" >
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="submitbutton" type="submit">
</form>
<div id="abc"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> //no need to specify the language
$(document).ready(function() {
$('#myForm1').on("submit",function(e) {
//var form = $(this);
//dataString = $("#myForm1").serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('form_controller/insert_into_db'); ?>",
data: $(this).serialize(),
//dataType: "json",
success: function(data){
// top.location.href = "<?php echo site_url('form_controller/callform'); ?>";
//$.each(data.results, function(){
// $("#abc").append('<div><b>' + id.id + '</b></div><hr />');
//});
/*var site_url = "<?php// echo site_url('form_controller/callform/') ?>";
site_url = site_url +"/" + id;
$("#abc").load(site_url);*/
<?php //foreach(): ?>
var site_url = "<?php echo site_url('form_controller/callform'); ?>";
var mydata=window.JSON.stringify(data.trim());
alert(mydata);
//site_url = site_url +"/" +data.id;
alert(site_url);
$("#abc").load(site_url);
//$('#abc').html(data);
var item = data;
alert(item.id);
}//,
//error: function() { alert("Error posting feed."); }
});
});
});
</script>
</body>
</html>
controller
function index(){
$this->load->view('submit_form');
}
function callform($id){
$this->load->view('view_form',$id);
}
public function insert_into_db(){
$this->load->helper('url');
$this->load->model('form_model');
$data= $this->form_model->insertQ();
$this->output->set_output(json_encode($data));
}
}
model
<?php
class Form_model extends CI_Model{
function insertQ(){
$email = $this->input->post('email');
$text = $this->input->post('qText');
$this->db->query("insert into form (email,text) values('$email','$text')");
$this->load->database();
$query = $this->db->query("SELECT MAX(id) AS id FROM form");
return $query->result();
}
}
when insert record into database there is a auto increment id. I need to get that particular id
from database and return it to the success function in ajax. then I need to load another page
into a div and print that id on newly loaded content.here the problem is
in view I couldn't get data into variable.for site_url
You can get the inserted id
$id = $this->db->insert_id();
I got this simple form page that will submit the last name and first name of a user
<?php
include 'dbconnect.php';
if (isset($_POST['lname']) && isset($_POST['fname'])){
$ln = $_POST['lname'];
$fn = $_POST['fname'];
$sql = "INSERT INTO user_tbl (`lastname`,`firstname`) VALUES ('$ln','$fn')";
$result = mysql_query($sql);
}
?>
<!DOCTYPE html>
<html>
<head>
<script >var frm = $('#nameFrm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</head>
<body>
<form id = "nameFrm" name = "frmName" method = "POST" >
Last Name : <input type = "text" name = "lname"><br />
First Name: <input type = "text" name = "fname"><br />
<input type = "submit" value = "submit" name= "subbtn" >
</form>
</body>
my script does not work that script is suppose to avoid the page from reloading and i am pretty sure that it is reloading everytime the page is submitted
also when i seperate the php code
if (isset($_POST['lname']) && isset($_POST['fname'])){
$ln = $_POST['lname'];
$fn = $_POST['fname'];
$sql = "INSERT INTO user_tbl (`lastname`,`firstname`) VALUES ('$ln','$fn')";
$result = mysql_query($sql);
}
it still redirects it to the new php file
What to do is create a new file called requests.php / or whatever
in this file have a switch statement..
requests.php
<?php
if(isset($_POST['action']) && ($_POST['action']!='')){
$action = $_POST['action'];
switch($action){
case "submitForm" :
include 'dbconnect.php';
if ( (isset($_POST['lname'])) && (isset($_POST['fname'])) ){
$ln = mysql_real_escape_string($_POST['lname']);
$fn = mysql_real_escape_string($_POST['fname']);
$sql = "INSERT INTO user_tbl (`lastname`,`firstname`) VALUES ('$ln','$fn')";
mysql_query($sql);
echo "New values updated: ".$fn." ".$ln;
}
break;
}
}
?>
Then copy this crude html..
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadImg = jQuery('#loadingImage');
var fname = jQuery('#fname').val();
var lname = jQuery('#lname').val();
jQuery.ajax({
type: 'POST',
data:'action=submitForm&fname='+fname+'&lname='+lname,
url: 'requests.php',
beforeSend: function(){
loadImg.show();
},
complete: function(){
loadImg.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
</head>
<body>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
Last Name : <input type="text" id="lname" name="lname"><br />
First Name: <input type="text" id="fname" name="fname"><br />
<input type = "submit" value = "submit" name= "subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
<img src="http://craigmaslowski.com/images/activity-indicator.gif" />
</div>
<div id="results"></div>
</body>
What its doing is when you click the submit button, the jquery will fire,
it will grab the 2 values from fname & lname (these have been given an id)
the 2 values will then be added to the jquery.ajax URL, this url will be the form action url, which for this is requests.php
in requests.php the 2 post values are passed over and processed, the output will be sent back to the original page, were the data will be passed to the div#results, to show the output....
Also I've added a few other things, like a loading image, for both the beforeSend call and Complete,
**ALSO,
please be-aware that you should really think about moving from using the mysql_query syntax to mysqli_query.. have a look at MackieeE's comment!
**
Have a play around with it.. hopefully its what your looking for..
Good luck..
Marty
The browser executes the javascript BEFORE knowing the form.
Put the javascript AFTER the form or into a $(window).load():
<script>
$( window ).load(function() {
var frm = $('#nameFrm');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
});
</script>
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;
});
How can I submit this form with ajax.
Right now it creates a table from mysql query. When you click the Edit button behind a row, Javascript makes all the cells to input=text.
Now when you click the Submit button at the end of the line I would like it to submit edited data to mysql via ajax.
I don't understand where do I get the data that I need to POST with ajax.
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.9.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.qtip-1.0.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".edit").click(function(){
var tr = $(this).closest("tr");
var submit = "<input type='submit' name='Submit' value='Submit' />";
tr.find(".td").each(function(){
var name = $(this).attr("title");
var value = $(this).html();
var input = "<input type='text' name='"+name+"' value='"+value+"' />";
$(this).html(input);
});
tr.find(".button").html(submit);
});
});
// this is the id of the submit button
$(".button").click(function() {
$.ajax({
type: "POST",
url: "index.php?page=update_mysql",
data: $("#change").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
<form id="change" method="post" action="#">
<table>
<?PHP
$sql="SELECT * FROM names";
$result = mysql_query($sql)or die(mysql_error());
WHILE ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo '<tr class="row">';
echo '<td class="td" title="id">'.$row["id"].'</td>';
echo '<td class="td" title="first_name">'.$row["first_name"].'</td>';
echo '<td class="td" title="last_name">'.$row["last_name"].'</td>';
echo '<td class="button" title="button"><button class="edit">Edit</button></td>';
echo '</tr>';
}
?>
</table>
</form>
And update_mysql.php looks like this:
<?php
include 'firewall.php';
if ($_POST['Submit'] == "Submit") {
$id = $_POST['id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$sql_edit = "UPDATE names SET first_name = '$first_name', last_name = '$last_name' WHERE id = '$id'";
$result_edit = mysql_query($sql_edit) or die(mysql_error());
}
?>
Try this.
$(document).ready(function(){
$(".edit").click(function(){
var tr = $(this).closest("tr");
tr.find(".td").each(function(){
var name = $(this).attr("title");
var value = $(this).html();
var input = "<input type='text' name='"+name+"' value='"+value+"' />";
$(this).html(input);
});
var submit = "<input type='button' name='Submit' value='Submit' />";
tr.find(".button").html(submit);
});
});
$(".button input[type=button]").live('click', function() {
var data = $('form#change').serialize();
// post data using ajax
$.ajax({
type: "POST",
url: "index.php?page=update_mysql",
data: data,
success: function(data) {
alert(data); // show response from the php script.
}
});
});
NOTE: I have changed the "type" attribute of submit button to "type='button'". That will not fire default submit of browser. The same button is bound to collect form data and submit using ajax.
Happy Coding.
EDIT:
It takes you to "index.php?page=my_page#" coz form is submitted whey you click the <input type="submit">. Haven't you changed it to <input type="button"> yet? You don't need a submit button when its not there to submit the form. There are other non-submit button to bind javascript handlers to.
You can use jquery.serialize():
var data = $('form').serialize();