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();
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 am trying to develop an add to cart function via ajax, the problem is that no matter which product I add to cart, it adds the last item on the list and then increments the same product upon clicking on any other product. Here is my code:-
<?php
$i = 1;
while($row = mysqli_fetch_array($run_products)){
$op_id = $row['option_id'];
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row['option_desc'] . "</td>";
echo "<td>
<form action='' method='post' class='p_form'>
<input type='text' name='product_id' value='$op_id' pid='$op_id'>
<input type='text' name='quantity' value='1' pid='$op_id'>
<input class='btn btn-primary add' type='submit' name='add_to_cart' value='Add to Cart' id='product' pid='$op_id'>
</form>
</td>";
echo "</tr>";
$i++;
}
?>
Here is jquery:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.p_form',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
//data: {id:id},
data:$('.p_form').serialize(),
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
Here is action.php, the $product_id always returns as 4 (for example) if the last id in the last is 4
if (!empty($_POST)){
$product_id = $_POST['product_id'];
echo $product_id;
}
Need to do it like below:-
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {//instead of form click add event on form button click
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data:element.parent('.p_form').serialize(), //serialize clicked button parent form
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
Trigger click event on button click not on the form click:
This will work for you for each product.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data: {id:id}, //send id of product you wish to add
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
And on server side:
if (!empty($_POST)){
$product_id = $_POST['id'];//get only that id posted in ajax call
echo $product_id;
}
Ive been trying to make my html table appear when i click the submit button but all it does is inserts data into the database and the html table doesnt appear.
here is my index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("table.php");
});
});
</script>
</head>
<body>
<form action = "insert.php" method="post">
Firstname: <input type="text" name="firstname"></br>
Lastname: <input type="text" name="lastname"></br>
Middlename: <input type="text" name="middlename"></br>
<button type="submit">submit</button>
</form>
<div id="div1">
</div>
</body>
</html>
here is my table.php
<?php
$con = mysqli_connect("localhost","root","","study");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to mysql" . mysqli_connect_error();
}
echo '<table border = 1>';
echo '<tr>';
echo ' <th>FIRSTNAME</th>';
echo '<th>LASTNAME</th>';
echo ' <th>MIDDLENAME</th>';
echo ' <th>DELETE</th>';
echo ' </tr>';
$result = mysqli_query($con,"SELECT * FROM sample_employers");
while($row=mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['middlename'] . "</td>";
echo "<td> <input type='button' value='Delete' </td>";
echo "</tr>";
}
mysqli_close($con);
echo '</table>';
?>
I did some editing in my index.php. I put the submit button outside the form tag and the html table appears but the problem now is there is no data inserted to the database.So how am i going to make the html table appear and at the same time insert data to the database when i click the submit button.??
// example 1 GET
$(document).ready(function(){
$("#submitButt").click(function(e){ // u should give a id to the button.
e.preventDefault(); // this is to prevent the form submit by it self
// using ajax to submit
$("#div1").load("insert.php",
$(this.form).serialize(); // this will use GET to submit data
);
});
});
// example 2 POST
$(document).ready(function(){
$("#submitButt").click(function(e){ // u should give a id to the button.
e.preventDefault(); // this is to prevent the form submit by it self
// using ajax to submit
$("#div1").load("insert.php",
$(this.form).serializeArray(); // this will use POST to submit data
);
});
});
http://jsfiddle.net/9kcek/
use Tamper Data to check the request when u click the submit button.
If you press submit, then you will be redirected to insert.php. Hence, your click event will never be executed. You must prevent the redirect first in order for you to load your data.
Furthermore, you will need to switch the way in which your data is posted. As you want to directly insert the table on the current page, you should switch to an ajax approach. Your data will be sent to your insert.php in the background via $.ajax and then you can load your #div1 on success with the content of table.php.
<script>
$(document).ready(function () {
var $form = $('form');
$form.submit(function (event) {
event.preventDefault();
var formData = $form.serialize(),
url = $form.attr('action');
$.ajax({
type: "POST",
url: url,
data: formData,
success: function () {
$("#div1").load("table.php");
}
});
});
});
</script>
I have a little problem with my AJAX jQuery script and n number of forms...To be more precise, PHP script generate N number of forms (form include one textarea and one button), and in head tag I included jquery script. Problem is that jquery work only for first form and not with others (second, third...). I needed to work with all forms...This is the code:
<script>
$(document).ready(function() {
$("#submitForm").click(function() {
var text = $("#comment").val();
var id = $("#id").val();
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
And this is PHP code
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment'></textarea>
<input type='hidden' id='id' value='".$id."'/>
<input type='button' id='submitForm' value='Add Comment'>
</div>";
}
What is problem???
On your PHP side you should change with something similar to this to ensure that all the html elements has a unique id.
for($i=0; $i<$num; $i++)
{
echo "<div style='border: 1px solid black;'>
<textarea id='comment".$i."'></textarea>
<input type='hidden' id='id".$i."' value='".$id."'/>
<input type='button' id='".$i."' class='submitForm' value='Add Comment'>
</div>";
}
and change the Javascript with something similar to this to reflect the changes made on the php side
<script>
$(document).ready(function() {
$(".submitForm").click(function() {
var formNumber = $(this).attr("id"); // Get the form number that was clicked, the id attribute of the clicked button
var text = $("#comment"+formNumber).val(); // Get the comment of that particular form
var id = $("#id"+formNumber).val(); // get the id of that particula form
$.ajax(
{
url: "addcomment.php",
type: "POST",
data: "t="+ text +"&id="+id,
success: function(data)
{
alert(data);
}
});
});
});
</script>
For every form you're creating you're using the same ID.
IDs must be unique and only appear once on the page.
You should use a class instead as suggested in the comments.
So more like this:
<?php for ($i = 0; $i < $num; $i++): ?>
<div>
<textarea class="comment"></textarea>
<input type="hidden" class="id" value="<?php echo $id; ?>">
<input type="button" class="submitForm" value="Add Comment">
</div>
<?php endfor; ?>
I'm not sure where your $id variable comes from.
Your JavaScript will need to be updated as well to work with this, I'd do something like this (elaborated so you can see what's going on):
$('.submitForm').click(function(e) {
e.preventDefault(); // stops the default form action (if there is one)
var $submitButton = $(this);
var $div = $submitButton.parent(); // gets the div container
var id = $div.find('.id').val();
var text = $div.find('.comment').val();
// now do your ajax
});
I have a comments section on my websites that uses jQuery to animate comments in without reloading the page, as well as deleting comments.
Right now, I have it so when you write a comment, it sends it to a external JS, then to a php file where it processes. If it was successful, it will append the comment into the comment section. My delete action: jQuery deletes my the comment ID in the mysql database.
So my issue is I want to add a delete button via jQuery and somehow call back to the javascript file and tell it the id so the delete button knows the ID to put in the form so the delete file knows what to delete?
Here's my add_comment script:
$(function() {
$(".commentbutton").click(function() {
$.ajax({
type: "POST",
url: "http://myflashpics.com/process_addcomment.php",
data: $("#commentform").serialize(),
success: function() {
var theComment = $("#commentsss").val();
var theUserId = $("#user_id_two").val();
var thePhotoId = $("#photo_id").val();
var theProfilePicture = $("#user_profile_picture").val();
var theUsername = $("#user_username").val();
// Get new HTML data
var html = "<div class='comment_odd'><img src='" + theProfilePicture + "' class='comment_thumbnail'/><div class='comment_username'>" + theUsername + "</div><div class='comment_text'>" + theComment + "</div></div>";
// Append, then fade in
$(html).hide().appendTo(thecommentsdisplay).fadeIn(500);
}
});
return false;
});
});
Thanks in advance!Coulton
EDIT 1:
Here's my comments form (just to clarify):
user_id_two (the user's ID)
commentsss (comments field)
photo_id (the id of the photo being commented on)
user_profile_picture (profile to display on the user's profile picture in the banner)
user_username (username of the user commenting)
Here's also my delete button form:
<form method='post' action='' name='deleteform' id='deleteform'>
<input type='hidden' name='userid' value='<?php echo "$userid_session"; ?>' />
<input type='hidden' name='userpass' value='<?php echo "$password_session"; ?>' />
<input type='hidden' name='pictureid' id='pictureid' value='<?php echo "$picture_id"; ?>' />
<input type='hidden' name='profilepictureid' id='profilepictureid' value='<?php echo "$user_profile_picture_id"; ?>' />
</form>
And lastly my DELETE COMMENT jQuery:
$(function() {
$(".commentdeletebutton").click(function() {
var className = $(this).attr('class');
var theID = className.replace(/delete_button commentdeletebutton delete_(\d+)/, "$1");
commentDone = "#comment_" + theID;
formDone = "#commentdeleteform_" + theID;
$.ajax({
type: "POST",
url: "http://myflashpics.com/process_deletecomment.php",
data: $(formDone).serialize(),
success: function() {
$(commentDone).hide();
}
});
return false;
});
});
If you add an link for deleting, you can insert the complete url for deleting in the href, i.e. http://myflashpics.com/process_removecomment.php?id=xx.
So, you can bind a click event to that link and get the right url using $(this).attr('href') and doing the delete using ajax.
Edited for a more complete sample:
<? [[Loop your recordset]] { ?>
<div class="comment">
Delete
<div class="comment">
[[Comment content...]]
</div>
</div>
<? } ?>
<script>
$(function() {
$(".commentdeletebutton").click(function() {
$this = $(this);
$.ajax({
url: $this.attr('href'),
success: function(data) {
$this.parent().slideUp('fast', function() {
$this.parent().remove();
});
}
});
return false;
});
});
</script>