Removing appended div box using jquery ajax - php

I have to implement two functions, append and delete on set of comments. The insertion and deletion are working properly unless in one case.
When i try to remove newly added comment (before refreshing page), it wont remove. But when i refresh the page that comment removes swiftly.
Here's some code.
Following ajax is appending and removing the comment div.
<script type="text/javascript">
$(function() {
$(".commentbutton").click(function()
{
var element = $(this);
var postid = element.attr("id");
var commenttext = $("#commenttext"+postid).val();
var dataString = 'commenttext='+ commenttext+'&postid='+postid;
var postseq='#post'+postid;
if(commenttext=='')
{
alert("Please enter your comment");
}
else
{
//$("#flash").show();
//$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
$(postseq).append(html);
$(postseq).slideDown();
document.getElementById('commenttext'+postid).value='';
}
});
}
return false;
});
$('.delcombutton').click(function()
{
var commid = $(this).attr("id");
var dataString = 'delcomm=1&commid='+commid;
var delcomment = '#comment'+commid;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
cache: false,
success: function(html){
$(delcomment).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
</script>
Structure of my div
echo "<div id='post{$postseq}'>";
while($commentonpost=mysql_fetch_array($resultcomm)){
if($commentonpost['visible']==1){
echo '
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;" id="comment'.$commentonpost['commentid'].'">
<div style="width:10%;float:left;"><a href="profile.php?user='.$commentonpost['usernick'].'" >'.$commentonpost['fname']." ".$commentonpost['lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;">'.$commentonpost['comment'].'</div>
<div style="width:8%;float:right;margin-left:2%;">
';
if($commentonpost['usernick']==$_SESSION['user_nick']){
echo ' <form action="" method="post">
<input type="submit" name="delcomm" value="X" class="delcombutton" id="'.$commentonpost['commentid'].'">
</form>
';
}
echo '<h5 class="msg">'.datetime($commentonpost['date']).'</h5>
</div>
<br/>
</div>
';
}
}
echo "</div>";
echo '
<form name = "form'.$postseq.'" method = "post" action="" onsubmit="return validateform()" style="width:100%">
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;">
<div style="width:10%;float:left;"><a href="profile.php?user='.$_SESSION['user_nick'].'" >'.$_SESSION['user_fname']." ".$_SESSION['user_lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;"><textarea placeholder="Comment..." name="commenttext" id="commenttext'.$postseq.'" class="inputcomment" ></textarea></div>
<br>
<input type="submit" id="'.$postseq.'" name="SubmitComment" value="Comment " class="commentbutton" style="font-size:1em;width:100px;float:right;margin-top:4px;margin-right:9%;">
</div>
</form>
</div>
';
PS: Sorry for such a raw code, i have very limited internet now.

You have to use delegation for dynamically added elements:
$(document).on('click','.delcombutton',function(){...});

Use event delegation model with .on() for dynamically added elements
$(function() {
$(document).on('click', '.commentbutton', function() {
var element = $(this);
var postid = element.attr("id");
var commenttext = $("#commenttext"+postid).val();
var dataString = 'commenttext='+ commenttext+'&postid='+postid;
var postseq='#post'+postid;
if(commenttext=='') {
alert("Please enter your comment");
}
else {
//$("#flash").show();
//$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
$(postseq).append(html);
$(postseq).slideDown();
document.getElementById('commenttext'+postid).value='';
}
});
}
return false;
});
$(document).on('click', '.delcombutton', function() {
var commid = $(this).attr("id");
var dataString = 'delcomm=1&commid='+commid;
var delcomment = '#comment'+commid;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
cache: false,
success: function(html){
$(delcomment).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});

Related

Submit autocomplete with enter button without refreshing the page

I am trying to get the query results by hitting the enter button on the drop down of the autocomplete results. It works fine if I use the mouse to click the result i want but wont work if i use the enter key.
The first function gets the autocomplete results and the second submits the result to get the data from that particular id.
JQUERY
$(document).ready(function () {
$("#equipment").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
$('#eq_id').val(ui.item.id);
}
});
$(document).off("keypress", "#equipment");
$(document).on("keypress", "#equipment", function(event) {
//if (!e) e = window.event;
if (event.keyCode == '13'){
$('#loading').show();
var eq_id = $("#eq_id").val();
var dataString = 'eq_id=' + eq_id;
$.ajax({
type: "POST",
url: "updateForm.php",
data: dataString,
success: function(html){
$("#formAddEquip").hide();
$("#showuserresult").show();
$("#showuserresult").html(html);
$("#equipment").val("");
$('#loading').hide();
}
});
return false;
}
});
});
And here is the form
<form action="" method="post" id="#somesearch">
<label for="equipment" id="eq_id_label">Search Equipment</label>
<input type="text" id="equipment" name="equipment" />
<input type="hidden" id="eq_id" name="eq_id" />
</form>
Start with these improvements
$(function() { // only one "load"
$("#equipment").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
$('#eq_id').val(ui.item.id);
}
});
$("#somesearch ").on("submit", function(e) {
e.preventDefault(); // stop submission
});
$(document).on("keypress", "#equipment", function(event) {
//if (!e) e = window.event;
if (event.keyCode == '13') {
$('#loading').show();
var eq_id = $("#eq_id").val();
var dataString = 'eq_id=' + eq_id;
$.ajax({
type: "POST",
url: "updateForm.php",
data: dataString,
success: function(html) {
$("#formAddEquip").hide();
$("#showuserresult").show();
$("#showuserresult").html(html);
$("#equipment").val("");
$('#loading').hide();
}
});
}
});
});

How to save data in textarea on enter key using ajax like facebook comment?

I have done the code like this in view page and controller done in codeigniter
While pressing enter key multiple times data saving to the table. Can anybody help to solve this problem
View Page
<form>
<div class="cmt-box">
<textarea class="form-control" name="txtArea" id="txtArea<?php echo $row->id;?>" onkeypress="onTestChange(1)" rows="1"></textarea>
</div></form>
script
function onTestChange(id) {
$("#txtArea"+id).keypress(function(e) {
if(e.which == 13) {
dataString=document.getElementById("txtArea"+id).value;
$.ajax({
type: "POST",
url: "<?php echo site_url('show/insertcomment'); ?>",
data: { comment :dataString, id:id},
success: function(data){
location.reload();
}
});
}
});
}
$(".class_txtarea").keypress(function(e) {
if(e.which == 13) {
dataString=document.getElementById(this).value;
$.ajax({
type: "POST",
url: "<?php echo site_url('show/insertcomment'); ?>",
data: { comment :dataString, id:id},
success: function(data){
location.reload();
}
});
}
});
HTML:
<div class="cmt-box">
<textarea class="form-control mytext" name="txtArea" id="txtArea<?php echo $row->id;?>" rows="1"></textarea>
</div>
Jquery:
$(document).ready(function(){
$('.mytext').keyup(function (evt) {
evt = evt || window.event;
if (evt.keyCode == 13) { /* pressed enter key */
$.ajax({
type: "POST",
url: "<?php echo site_url('show/insertcomment'); ?>",
data: { comment :dataString, id:id},
success: function(data){
location.reload();
}
});
}
});
});

can i fetch and populate different fields using function(data) jquery?

i want to populate two fields when some one fill up card no.
<input type="text" id="name" name="name" class="form-control" Value="<?php echo $grow['name']; ?>">
<input type="text" id="address" name="address" class="form-control" Value="<?php echo $grow['address']; ?>">
but this code populate field one by one. can any one suggest be better code for populating two fields from database. Thank you
jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k=$(this).val();
var q="name";
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q='+q,
cache: false,
success: function(data)
{
if(data){
$("#name").val(data);
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
$("#address").val(data);
}
}
});
}else
$("#name").val("");
$("#address").val("");
}
});
});
});
</script>
getresult.php
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select * from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
echo $row[$q];
?>
Try to extract both name and address from database and json them
$k=$_POST['k'];
$q=$_POST['q'];
$sql=mysql_query("select address,name from inward where krishi='$k'");
$row=mysql_fetch_array($sql);
$result = array(
'name'=>$row['name'],
'address'=>$row['address']);
echo json_encode($result);
After that parse them via jquery
$.ajax
({
type: "POST",
url: "getresult.php",
data: 'k='+k+'&q=address',
cache: false,
success: function(data)
{
if(data){
var parsedData = jQuery.parseJSON(data);
$("#name").val(parsedData.name);
$("#address").val(parsedData.address);
}
}
});
Javascript Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#krishi").keyup(function()
{
var k = $(this).val();
var q = "name";
$.ajax({
type: 'POST',
url: "getresult.php",
data: 'k='+k,
cache: false,
success: function(data)
{
var jsonArr = $.parseJSON(data);
if(typeof response =='object')
{
$("#name").val(jsonArr.name);
$("#address").val(jsonArr.address);
}
else
{
$("#name").val("");
$("#address").val("");
}
}
});
});
});
</script>
PHP Code:
<?php
define('INCLUDE_CHECK',true);
include("mysql.php");
$k = $_POST['k'];
$sql = mysql_query("select * from inward where krishi='$k'");
$row = mysql_fetch_assoc($sql);
echo json_encode(array('name' => $row['name'], 'address' => $row['address']);
?>

Need to autosubmit form on page loads

i have a website with a jquery search form. I have the searchboxes in every page of the site indide the header. Once you enter the searchwords there it redirects you the the search.php
What i want to do is to make the form submitted as soon as the page loads, because i send the data to the searchbox inside the search.php
Example: in page 1 i enter something and click submit. In search.php loads and in the main search field i have somethis(what i entered before). But i have to click again the submit to see the results. Any idea how can i make the form autosubmit when im being redirected? So i can see the results instantly.
Here's the code:
<form method="get" id="myForm" name="myForm" >
<input type="text" name="search" id="search_box" value="<?php $_GET['q']; ?>" placeholder="Enter band, artist, name..." autofocus/>
<input type="submit" value="Go" />
<br />
</form>
and the jquery:
<script type="text/javascript">
$(function() {
//-------------- Update Button-----------------
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word==''){
} else {
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<p style="text-align:center;">Loading Results...</p>');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
//---------------- Delete Button----------------
});
</script>
$(function(){
$('#myForm').trigger('submit');
});
When the page is ready you simply trigger the submit using jquery.
$(function() {
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word==''){
} else {
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<p style="text-align:center;">Loading Results...</p>');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
$(document).ready(function(){
$('#myForm').submit();
});
You can try this way.
<form method="get" id="myForm" name="myForm" >
<input type="text" name="search" id="search_box" value="" placeholder="Enter band, artist, name..." autofocus/>
<input id="button-submit" type="submit" value="Go" />
</form>
<script type="text/javascript">
$(function() {
function _myFunction () {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word==''){
} else {
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<p style="text-align:center;">Loading Results...</p>');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
}
$("#button-submit").click(function(e) {
e.preventDefault();
_myFunction();
return false;
});
_myFunction(); //This is where the magic happens
});
</script>
By doing that, the page will trigger on loading the function that is used when you click on the button.

json jquery post request

<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var content = $('#content').html();
var data = {"content":content};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax.php",
data: {content:content},
success function (data) {
alert('Hello!');
}
});
});
});
</script>
<div id="content"><?php echo $content; ?></div>
ajax.php
echo json_encode($_POST['content']); ?>
Nothing happens... WhatI really want to achieve is to get that alert box and get the return data, but I am lost since I don't get any errors or nothing.
You miss " : " after success
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var content = $('#content').html();
var data = {"content":content};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax.php",
data: {content:content},
success: function (data) {
alert('Hello!');
}
});
});
});
</script>
<div id="content"><?php echo $content; ?></div>
As #sofl said, if you change it to success:function (data) { it will work!
Just remember that the $("a") from $("a").click(function() { called when click in a link tag like <a href"">.
If you are using an input ou button with a class="a" you should change the code to $(".a").click(function() {
(just add a . before a)
PS: If you're using a link, you should set the href="" to href="#" to work.

Categories