The code below is a attempt to create a comment system using ajax and php here php part works well comment is inserted into table but seems I didn't get my hands on ajax yet. Ajax does not work comment is not shown unless I reload page. On reloading page comment appears perfectly where it should be so help me on fixing my ajax code.
<?php
if(isset($_POST['content'])) {
$comment=strip_tags($_POST['content']);
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, blog) VALUES (:comment, :userto, :userfrom, :blog)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':blog'=>$blogId));
}
?>
<div class='db'>
<table>
<tr>
<td>
<img src='<?php echo $tar['profile_pic']; ?>' style='width:40px;height:40px;'/>
</td>
<td>
<a href='<?php echo $tar['username']; ?>'><?php echo $tar['first_name'].' '.$tar['last_name']; ?></a>
<p><?php echo $tar['comment']; ?></p>
</td>
<td>
<a href='#' id='<?php echo $tar['id']; ?>' class='delcomment' style='color:#555555;text-decoration:none;' title='Delete'>X</a>
</td>
</tr>
</table>
</div>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content=' + test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "",
data: dataString,
cache: false,
success: function(html) {
$(".db").show(html);
}
});
}
return false;
});
});
</script>
<form method='post' name='form' action='' class='commentbox'>
<textarea cols='30' rows='2' name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit'class='comment_button'/>
</form>
You dont need to use the variable dataString and you need to change the $.ajax() function for this:
var test = $("#content").val();
$.ajax({
type: "POST",
url: "",
data: {
content: test;
},
success: function(response) {
$(".db").append(response);
}
});
change the following line to avoid page refreshes:
$(".comment_button").click(function(event) {
event.preventDefault();
or change the attrubute type="submit" of your button for type="button", like this:
<button type='button' name='submit' class='comment_button'>Comment</button>
I hope it helps you...
Try this.
And make sure jQuery library is also included in your page.
HTML PAGE
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var comment = test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "process.php",
data: {content : comment},
cache: false,
success: function(html) {
$("#db").append(html);
}
});
}
return false;
});
});
</script>
<div id="db">
<!--Returned comment will appear here -->
</div>
<form method='post' name='form' action='process.php' class='commentbox'>
<textarea cols='30' rows='2' name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit'class='comment_button'/>
</form>
PHP PAGE
process.php
<?php
if(isset($_POST['content'])) {
$comment=strip_tags($_POST['content']);
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, blog) VALUES (:comment, :userto, :userfrom, :blog)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':blog'=>$blogId));
}
?>
<table>
<tr>
<td>
<img src='<?php echo $tar['profile_pic']; ?>' style='width:40px;height:40px;'/>
</td>
<td>
<a href='<?php echo $tar['username']; ?>'><?php echo $tar['first_name'].' '.$tar['last_name']; ?></a>
<p><?php echo $tar['comment']; ?></p>
</td>
<td>
<a href='#' id='<?php echo $tar['id']; ?>' class='delcomment' style='color:#555555;text-decoration:none;' title='Delete'>X</a>
</td>
</tr>
</table>
Use
$(".db").append(html);
if you already have existing comments like:
<div class = "db">
Comment 1
Comment 2
...
</div>
.append will add more HTML to existing tag.
Related
I have the following code:
PHP
<?php include("db.php"); ?>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
</head>
<body>
<div align="center">
<table cellpadding="0" cellspacing="0" width="500px">
<?php $sql = "SELECT * FROM items ORDER BY ID DESC";
$items= mysql_query($sql);
while ($item= mysql_fetch_array($items)){
$id = $item[ID]; ?>
<script type="text/javascript">
$(function() {
$(".<?= $id ?>").click(function() {
var element = $(this);
var boxval = $("#<?= $id ?>").val();
var dataString = 'not='+ boxval;
$("#flash").show();
$("#flash").fadeIn(200).html('');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow"); document.getElementById('content').value='';$("#flash").hide();
}
});
return false;
});
});
</script>
<tr style="border: solid 4px red;">
<td>
<div class="<?= $id ?>">
<button type="submit" id="<?= $id ?>" name="not" value="<?= $id ?>">BUTTON <?= $id ?></button>
</div>
</td>
</tr>
<?php } ?>
</table>
<div id="flash" align="left" ></div>
<ol id="update" class="timeline"></ol>
<div id="old_updates"></div>
</div>
</body>
</html>
This code works fine and allows me to insert data in sql without refresh.
But, how can I put the javascript as external script and the variables passing coretly for each item?
I want to reorganize like this:
PHP
<?php include("db.php"); ?>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
</head>
<body>
<div align="center">
<table cellpadding="0" cellspacing="0" width="500px">
<?php $sql = "SELECT * FROM items ORDER BY ID DESC";
$items= mysql_query($sql);
while ($item= mysql_fetch_array($items)){
$id = $item[ID]; ?>
<tr style="border: solid 4px red;">
<td>
<div class="<?= $id ?>">
<button type="submit" id="<?= $id ?>" name="not" value="<?= $id ?>">BUTTON <?= $id ?></button>
</div>
</td>
</tr>
<?php } ?>
</table>
<div id="flash" align="left" ></div>
<ol id="update" class="timeline"></ol>
<div id="old_updates"></div>
</div>
<script src="script.js"></script>
</body>
</html>
When script.js is this
<script type="text/javascript">
$(function() {
$(".<?= $id ?>").click(function() {
var element = $(this);
var boxval = $("#<?= $id ?>").val();
var dataString = 'not='+ boxval;
$("#flash").show();
$("#flash").fadeIn(200).html('');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value='';$("#flash").hide();
}
});
return false;
});
});
</script>
Either the script you're using currently and the example of what you want to achieve are wrong.
You should never mix your scripts this way. It causes alot dependencies and makes your app very sensitive for any code changes.
Don't use id attributes when you deal with dynamic elements. Make a group/sets of elements (that behave the same way for a specific action) by giving them the same class.
Don't use mysql_* functions
Button:
<button class="my-btn" type="button" value="<?= $id ?>">BUTTON <?= $id ?></button>
HINT: set type=button rather than type=submit attribute on your button if you don't want it to submit a form. Then you don't have to return false; on click.
script.js:
$(function() {
$(".my-btn").click(function() {
var dataString = $(this).val();
$("#flash").show().fadeIn(200).html('');
$.ajax({
type : "POST",
url : "update_data.php",
data : {'not' : dataString},
cache : false,
success : function(html){
$("#update").prepend(html).find("li:first").slideDown("slow");
$('#content').val('');
$("#flash").hide();
}
});
});
});
I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes
inserting.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
} return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>
demo_insert.php
PHP Code display recently inserted record from the database.
<?php
include('db.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
mysql_query("insert into messages(msg) values ('$content')");
$sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<b><?php echo $r['msg']; ?></b>
In your wellcome controller you can add the following:
public function inserting()
{
$this->load->view('inserting');
}
public function process()
{
$content=$this->input->post('content');
if($this->db->insert('mytable', array('msg' => $content))){
echo "<b>{$content}</b>";
}
You should then use inserting.php as your view, in application/views, and the ajax url would be /process.
Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php
For example, there is such a JS-code:
function openAlbum() {
$("#tracks").html('Some text...');
var uid = $("#uid").val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
}); }
And this html/php-code that is displayed in a cycle:
for ($i = 0; $i < count($searchAlbum); $i++) {
echo '<div id="cover"><form action=""><input type="hidden" id="uid" value="'.str_replace('https://example.com/', '', $searchAlbum[$i]->href).'"/><img src="'.$searchAlbum[$i]->images[1]->url.'"/><br><br><span>'.$searchAlbum[$i]->name.'</span><input type="submit" style="position: absolute;;left: -99999px;" /></form></div>';
}
Problem: currently by clicking grabs only the first input value on the page with id="uid".
How do I put a JS var uid value from the div, which clicked a link?
P.S. Sorry for my bad english.
I'm going to change the way you kinda do this a bit...
<?php
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div class="cover">
<form action="">
<input type="hidden" class="uid" value="<?php echo str_replace('https://example.com/', '', $searchAlbum[$i]->href); ?>"/>
<img src="<?php echo $searchAlbum[$i]->images[1]->url; ?>"/>
<span><?php echo $searchAlbum[$i]->name; ?></span>
<input type="submit" style="position: absolute;left: -99999px;" />
</form>
</div>';
<?php
}
?>
Script:
$(document).on('click','.cover img',openAlbum);
function openAlbum() {
$("#tracks").html('Some text...'); var uid = $(this).parent().find('.uid').val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
//$("#results").empty();
//$("#results").append(html);
$("#results").html(html);
}
});
}
This should cover everything. I switched all ids to classes and changed how you execute your jQuery.
Thank you all for your help!
As a result, I will be able to solve the problem.
JS-code:
function openAlbum(uid)
{
$("#results").html('Some text...');
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
});
}
HTML-code:
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div id="cover"><a href="#" onclick='openAlbum("<? echo $searchAlbum[$i]->id; ?>");'><img src="<? echo $searchAlbum[$i]->images[1]->url; ?>"/></a><br><br><span><? echo $searchAlbum[$i]->name; ?></span></div>
<?
}
Since id in HTML must be unique, it is taking only the first element's value. Make the ids unique or use class attribute as Cayce K has answered.
I am actually trying to make comments and also edit option when the comment enters it will show in a 'div'through ajax.
<?php
$q="select * from discuss where rownum=1 order by id desc";
$s=oci_parse($conn, $q);
$r=oci_execute($s) or die(oci_error());
echo "<table border=1>";
while($m=oci_fetch_assoc($s))
{
echo "<tr style='background-color:red'><th style='float:left;color:white'>Name : ".$m['NAME']."</th><th style='float:right;color:white'>Date: "."".$m['DATE_TIME']."</th></tr>";
echo "<tr class='edit_option' style='width:1000px;height:10px;background- color:white'><div><td id='input_text' style='width:1000px;height:10px;background- color:white'>".$m['COMMENTS']."</div><div class='anchor_edit' id='anchor_id_edit'><span onclick=\"edit_text('".$m['COMMENTS']."')\">edit</span></div></td></tr>";
}
echo "</table>";
?>
<script>
function edit_text(edit_option){
alert(edit_option);
}
</script>
onclick the function value is coming to edit_text() function getting alert, here i am not getting how can iput logic for this comment.
when edit option is clicked the user has to get his/her comment in a input text 'value' so the user can edit comment.
onclick how can i do the edit comment, please anyone can help!!
This may be help to you
Here I take a sample array input data
PHP SCRIPT
<?php
$r=array(
array('COMMENT-ID'=>'1','NAME'=>'Comment1','COMMENTS'=>'Comment1Comment1Comment1Comment1','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'2','NAME'=>'Comment2','COMMENTS'=>'Comment2Comment2Comment2Comment2','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'3','NAME'=>'Comment3','COMMENTS'=>'Comment3Comment3Comment3Comment3','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'4','NAME'=>'Comment4','COMMENTS'=>'Comment4Comment4Comment4Comment4','DATE_TIME'=>'12547896321')
);
echo "<div>";
foreach($r as $m)
{ ?>
<div>
<div>
Name : <?php echo $m['NAME']; ?>
</div>
<div>
Date: <?php echo $m['DATE_TIME']; ?>
</div>
</div>
<div class="comment">
<div class="comment-text" id="comment<?php echo $m['COMMENT-ID']; ?>">
<?php echo $m['COMMENTS']; ?>
</div>
<div class="commentEditBtn">
Edit
</div>
<div class="editedText"></div>
<div class="commentInput" data-id="<?php echo $m['COMMENT-ID'] ?>">
<input type="text" name="comment" /><br/>
<button class="commentSubmit">Submit</button>
</div>
</div><br/>
<?php }
echo "</div>";
?>
jQuery
$(".commentEditBtn").on('click',function(){
$('.commentinput').hide();
var parentDiv = $(this).parent();
var commentText = parentDiv.find('.comment-text').html();
parentDiv.find('.commentInput input').val(commentText.trim());
parentDiv.find('.commentInput').show();
});
$(".commentInput > input").keypress(function(){
var commentData = $(this).val();
$(this).parent().parent().find('.editedText').html(commentData.trim()).show();
});
$(".commentInput .commentSubmit").on('click',function(){
var commentId = $(this).parent().attr('data-id');
var commentText = $(this).parent().find('input').val().trim();
$(this).parent().parent().find('.editedText').html('').hide();
$.ajax({
url: "AJAX_POST_URL",
type: "POST",
data: {
commentId: commentId,
commentText: commentText
},
dataType: 'json',
success: function (data) {
if (data.error == 'false') {
$('#comment' + commentId).html(commentText);
}
}
});
});
CSS
.commentInput{display: none;}
.editedText{display: none;}
Check out this jquery plugin: http://jsfiddle.net/2u89gnn8/1/
You can make, for example, an h1 editable when a user clicks a button:
$('h1').editable({
"enable": true,
"trigger": $('button')
});
So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique