Let's check how to insert and view data from the database without refresh using PHP, MySQL, AJAX and jQuery. Here, I am going to explain, in a usual insert and view take page refresh. So, It will make loading delay.
Check below files which will need to provide clear explanation.
1. DB.PHP
2. INDEX.PHP
3. ACTION.PHP
Here, is the explanation of above files.
Database Details :-
database name : 2my4edge
table name : comment
column names : id, msg, ip_add
DB.PHP
<?php
$conn = mysql_connect('localhost','root','') or die (mysql_error);
$db=mysql_select_db('2my4edge', $conn) or die (mysql_error);
?>
INDEX.PHP
<div class="container">
<div class="main">
<form method="post" name="form" action="">
<textarea style="width:500px; font-size:14px; height:60px; font-weight:bold; resize:none;" name="content" id="content" ></textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
</div>
We need to add the AJAX details in the same index.php file to make operation.
AJAX
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
You need to use above script to make the function without refreshing the page.
ACTION.PHP
<?php
include('db.php');
$check = mysql_query("SELECT * FROM comment order by id desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into comment(msg,ip_add) values ('$content','$ip')");
$fetch= mysql_query("SELECT msg,id FROM comment order by id desc");
$row=mysql_fetch_array($fetch);
}
?>
<div class="showbox"> <?php echo $row['msg']; ?> </div>
Check above showbox to see what was stored in the database.
0 comments:
Post a Comment