How to make a html table appear using ajax and jquery? - php

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>

Related

Php echo button onclick get id

I hava a dynamic list, loading from database in my php page.This list also have a delete button. When i click this button i need to get id of this button and delete from database that line with php code.
$dbh = new PDO("sqlite:database.sdb");
$sql ="SELECT * FROM clip";
foreach ($dbh->query($sql) as $row)
{
print 'Id: '. $row['id'] .'<br />';
echo '<input type="submit" id="'.$row['id'].'" value="delete" name="del">';
}
also this is my final code for button click;
$dbh->exec("delete clip where id='in here should be button id'");
How can i connect with this two code. Thanks already.
Given the level of your question I am assuming you are unfamiliar with jQuery and AJAX, but you should research both.
For a simple solution not using these you could do as follows:
Change the output to be <input type="button" id="'.$row['id'].'" value="Delete" onclick="do_delete(this.id)">;
Then you need a php script on the server side to handle the delete function, e.g. yourhandler.php
<?
//connect to DB here
if ($_POST['id']) {
$sql = "delete from clip where id=:delete_id";
$stmt = $dbh->prepare($sql);
$stmt->execute([':delete_id'=>$_POST['id']]);
}
?>
Then on the client side you need a form which submits when the button is clicked. Here is an example form code:
<form action="yourhandler.php" method="post" id="myform">
<!--Your PHP script which creates buttons-->
<input type="hidden" value="" name="id" id="delete_id">
</form>
<script>
function do_delete(which) {
var x = document.getElementById('delete_id');
x.value=which;
document.getElementById('myform').submit();
}
</script>
You can use this working jquery template for your task. It binds to all inputs that has a name="del".
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$('input[name="del"]').on('click', function() {
alert('button id is '+$(this).attr('id'));
var button_id = $(this).attr('id');
$.ajax({
method: 'post',
url: "delete.php",
data: {'did':button_id},
dataType: "html",
success: function(result) {
alert(result);
}
});
});
});
</script>
In your PHP delete file, you can retrieve the delete id via $_POST['did'].

How to show data from database without refreshing the page using jquery, PHP

Is there anyway to load the newly inserted rows to the database without refreshing the page using jQuery? I am able to send the data to the database without refreshing using jquery but I am stuck at showing that data back without refreshing the page. How do I display the data from the table without refreshing page and make it appear under the table in index.php which I have to display the retrieved data? Thanks
This is my index.php
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
$.ajax({
type: "POST",
url: 'send.php',
data: "user=" + $('#user').val() + "&comment=" + $('#comment').val(),
success: function(data){
$('input[type=text]').val('')
$('#status').html(data);
}
});
});
});
</script>
</head>
<body>
<div>
<input type="text" name="user" id="user">
<input type="text" name="comment" id="comment">
<input name="submit" type="submit" id="submit">
<div id="status"></diV>
</div>
<br>
<?php
$con=mysqli_connect("localhost","root","","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM comments");
echo "<table width='640' >
<tr>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr >";
echo "<td style='vertical-align:text-top'>" . $row['user'] . "</td>";
echo "<td><br><br><br>" . wordwrap($row['comment'], 90, '<br>',true) . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
And here is my send.php which submits the data to the table.
<?php
$mysqli = new mysqli("localhost", "root", "", "user");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$username = $_POST["user"];
$comment = nl2br($_POST['comment']);
$stmt = $mysqli->prepare("INSERT INTO comments (user, comment) VALUES (?,?)");
$stmt->bind_param('ss', $username, $comment);
$stmt->execute();
echo"comment posted successfully";
?>
This is a brief example for fetching data from a mysql database using JQuery AJAX and php. JQuery AJAX allows us to update a page's content without reloading the page:
http://openenergymonitor.org/emon/node/107
http://viralpatel.net/blogs/jquery-ajax-tutorial-example-ajax-jquery-development/
make send.php send you back the data you need to load the newly inserted row.
Let's say you inserted a comment that says "Hello world". If nothing goes wrong, send.php could, for instance, echo the content of the comment (Hello world in this case), and you could make use of that in the success function (from the data parameter).
look at the first answer in this question, might be useful.
You should append the new comment to the table with jquery in the success callback function of your ajax request.
To append:
$("table").append("<tr><td style='vertical-align:text-top'>"+$('#user').val()+"</td><td><br><br><br>"+$('#comment').val()+"</td></tr>");
Keep the thing you want to append in one line of code and make sure you don't clear the values of #user and #comment before you include them to the append string.

Display records on load page using jquery ajax in php

I want to load data when page is loaded but if i try doing that then delete function doesn't work and whenever I insert the effect should be seen in table without refreshing page Please check my code what changes to be done in this
index.php
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#Submit").click(function(e) {
var name = $('#name').val();
var message=$('#message').val();
if($(":text").val().length==0)
{
$(":text").after('<span class="error">Field cannot be empty</span>');
$('#name').addClass('error');
$('#message').addClass('error');
return;
}
else{
$('#name').removeClass('error');
$('#message').removeClass('error');
//$('#propspectDiv').removeClass('error');
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');
$.ajax({
url : 'data.php',
data:{
"name" : name,
"message" : message
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
},
complete:function(){
$('#myform').each(function(){
this.reset();
});
}
});
}
});
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
});
</script>
</head>
<body>
<form id="myform">
<div id="wrapper">
Name : <input type="text" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Submit" id="Submit" />
<div id="propspectDiv"></div>
<table id="data" border="1" style="display:none;"></table>
</div>
</form>
</body>
data.php
<?php
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
include('connection.php');
$sql = "INSERT INTO login (username,message) VALUES ('$name','$message')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
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 id=td1>
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
echo '</tr>';
$i++;
}
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: index.php");
}
?>
Looks like your grabbing the ID attribute of the link, but not setting it...
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
There is no ID attribute on your existing delete link:
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
Also - you probably don't need to have the link href pointing to delete.php as its irrelevant when the jquery click event does all the work.
Also, because you are inserting the html (including the delete method) via jquery you may need to use the "on" event
I'm doing this off the cuff so the code may have some minor bugs but I believe this is the path you want to take...
Revised it might look like this:
JQUERY
$("a").on("click", function(e) {
e.preventDefault();
$.post('delete.php',{ id: $(this).attr("id")});
return false;
});
LINK
echo"<td id=td1>
<a id='".$row['id']."' href='#'>Delete</a>";
echo '</tr>';
couple things to note...
1 - above i'm not actually VERIFYING the record was deleted before I remove the appropriate table row - you may want to implement something to check this
2 - an alternative to removing the table row would be to just update the table in general by repulling the data and outputting it - if you know what i mean

How to submit inline edit with ajax?

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

having problem in getting response of a complete ajax-php request in a div

I'm having problem in getting the response in a div of an ajax request which is made by onclick event by a form & a php page.
The code:
<html>
<head>
<script language="javascript">
function commentRequest(counter) {
new Ajax.Request("comment.php",
{
method: 'post',
postBody: 'commentbox='+ $F('commentbox_'+counter)+'&idc2='+$F('idc2_'+counter),
onComplete: showResponse2
});
}
function showResponse2(counter)
{
document.getElementById('showcomments_'+counter).innerHTML= counter.responseText;
}
</script>
</head>
<body>
<form id="form1" method="post" action="insert.php">
<textarea name="text1" id="text1"></textarea>
<input type="submit" name="nbbutton" value="Submit"/>
</form>
<?php
$con = mysql_connect("localhost","myuser","Muddser#1");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
MySQL_select_db("mydb", $con);
$result = mysql_query("SELECT * FROM table1 ORDER BY sl_no desc");
while($row = mysql_fetch_array($result))
{
echo "$row['text1']";
}
$id=$row['sl_no'];
$queryout="SELECT * FROM comments WHERE idc='$idc'";
$resultout=mysql_query($queryout) or die(mysql_error());
while($row1 = mysql_fetch_array($resultout))
echo "<div id='showcomments_$idc'>";
echo "<div id='comment'><form name='comment' id='commentfrm'onSubmit='return false;'>";
echo "<input type='text' value='Post a Comment' name='commentbox' id='commentbox_$idc'
tabindex='30' size='56'>";
echo "<input type='hidden' name='idc2' value='$idc' id='idc2_$idc'>";
echo " <input type='submit' name='submit' value='Post' id='commentbtn'
tabindex='40' onClick='commentRequest($idc)'>";
echo "</form></div>";
echo "$row1['comment']";
echo "</div>";
</body>
</html>
In the above thing, I submit some value of a textfield in a table & I get the output on the same page as the form is on.
in these outputs, I've made a provision of commenting on each outputs.
to comment I've created a form which calls an ajax function commentRequest($idc) as u can see it in the head tag.
after commeting by ajax, I wanna show the response of the form submission in tht very page in the div named showcomments_$idc.
Here, though I'm able to submit the value bt I'm totally unable to show the response in the desired div...
Plz help me if ne1 can...
I need it so badly as I've been stuck in between of my project...
Thanks in advance...
Regards,
Muddser
In your showResponse2() function you are treating counter as both string (when searching for element id) and object containing AJAX response (when assigning respose text). Change your function commentRequest to:
function commentRequest(counter) {
new Ajax.Request("comment.php",
{
method: 'post',
postBody: 'commentbox='+ $F('commentbox_'+counter)+'&idc2='+$F('idc2_'+counter),
onComplete: function(response) {
document.getElementById('showcomments_'+counter).innerHTML= response.responseText;
}
});
}

Categories