i have a message board. and you can comment on each message (bit like faceboook).
if you click the "comment" link a textarea slides down and you can write your comment.
but if you click "comment" then click cancel so that the textarea slides back up and them click comment again so that it slides back down again and leave a comment it will post the commment twice. so for every time the comment textarea slides into view and back it duplicates the comment.
$("body").on("click",".new_comment", function(e){ // new comment link
e.preventDefault();
var post = $(this).parents('.message_container').siblings('#post_comment');
clearInterval(refreshBoard); //stop autorefresh
$(post).slideDown(400, function() { //slide textarea down
$(".cancel_comment").on("click", function(e) { //cancel comment
e.preventDefault();
$(post).slideUp(400, function() { //slide textarea back up
$('#comments').load('messages.php'); //reload div
msgRefresh(); //starts autorefresh
});
});
});
//the following posts the comment along with info//
$("body").one("click", '.post_comment_button', function(e){
e.preventDefault();
var anchor = $(this).parents('.update_comment')
.parents('#post_comment').siblings('.comment_list').find('ul:first');
var comment = $(this).parents('.update_comment').children('textarea.post_comment').val();
var user = $(this).parents('.update_comment').children('input.user').val();
var msg_id = $(this).parents('.update_comment').children('input.message_id').val();
if (comment == '') $('#comments').load('messages.php');
else {
$.post('messages.php', {
comment: comment,
message_id: msg_id,
post_comment: 'true' }, function(data) {
//creatse new comment//
$('body').append(data);
var newcomment = "<li><div class='comment_container'>
<div class='date'>less than 1 minute ago</div>
<div class='name'>" + user + " </div>
<div class='info_bar'><div class='edit_comment'>
<a href='#' class='comment_edit'>Edit</a> </div>
<span>|</span><a href='#' class='delete_comment'>Delete</a></div>
<div class='fadeOut_comment'><div class='posted_comment'> " +
nl2br(htmlEntities(comment.trim())) + " </div></div></li>";
$(post).slideUp(400);
$(newcomment).fadeIn(500, function() {
$('#comments').load('messages.php');
}).appendTo(anchor);
});
}
});
});
so my question is why is this happening? and how do i stop it? if you need more info please ask. thankyou
This is happening because you're biding the .cancel_comment click handler every time someone clicks the .new_comment link.
On the first comment it fires one time and binds again, second comment fires two times and binds again, etc. By the 10th comment it will fire 10 times because you attached 10 event handlers.
Then, because you call msgRefresh(); inside this callback, it will append the same messages several times to the DOM.
To only bind it once take the following outside the .new_comment click callback.
$(".cancel_comment").on("click", function(e) { //cancel comment
e.preventDefault();
$(post).slideUp(400, function()
{ //slide textarea back up
$('#comments').load('messages.php'); //reload div
msgRefresh(); //starts autorefresh
});
});
And then bind it like this:
$("body").on("click", ".cancel_comment", function(e)
{
//cancel comment
});
I can see you're also biding at least one more event inside the .new_comment click callback. You should avoid doing this, do not bind anything inside a callback unless you really need to and you're 100% sure it won't be attached more than one time.
EDIT: The complete code might look something like this:
$("body").on("click", ".cancel_comment", function(e) { //cancel comment
e.preventDefault();
$(post).slideUp(400, function() { //slide textarea back up
$('#comments').load('messages.php'); //reload div
msgRefresh(); //starts autorefresh
});
});
$("body").on("click",".new_comment", function(e){ // new comment link
e.preventDefault();
var post = $(this).parents('.message_container').siblings('#post_comment');
clearInterval(refreshBoard); //stop autorefresh
$(post).slideDown(400, function() { //slide textarea down
});
//the following posts the comment along with info//
$("body").one("click", '.post_comment_button', function(e){
e.preventDefault();
var anchor = $(this).parents('.update_comment')
.parents('#post_comment').siblings('.comment_list').find('ul:first');
var comment = $(this).parents('.update_comment').children('textarea.post_comment').val();
var user = $(this).parents('.update_comment').children('input.user').val();
var msg_id = $(this).parents('.update_comment').children('input.message_id').val();
if (comment == '') $('#comments').load('messages.php');
else {
$.post('messages.php', {
comment: comment,
message_id: msg_id,
post_comment: 'true' }, function(data) {
//creatse new comment//
$('body').append(data);
var newcomment = "<li><div class='comment_container'>
<div class='date'>less than 1 minute ago</div>
<div class='name'>" + user + " </div>
<div class='info_bar'><div class='edit_comment'>
<a href='#' class='comment_edit'>Edit</a> </div>
<span>|</span><a href='#' class='delete_comment'>Delete</a></div>
<div class='fadeOut_comment'><div class='posted_comment'> " +
nl2br(htmlEntities(comment.trim())) + " </div></div></li>";
$(post).slideUp(400);
$(newcomment).fadeIn(500, function() {
$('#comments').load('messages.php');
}).appendTo(anchor);
});
}
});
});
Related
I need a person who can help me solve this problem.The code below is working well with the post and the php code.
//Getting the id of a buyer and loop through
//sending a request to the seller
$(document).ready(function(){
$('.buyerRequest').click(function(){
var id=$(this).attr('id').replace('id_','');
$.post('SendingOffer.php',{id:id},function(data){
if(data=="true"){
$(this).html('<b>Offer Send</b>').css('background','#dce6f1');
$(this).attr("disabled","disabled");
}else if(data=="false"){
alert('You have reached the maximum number you can send todays');
}
});
});
});
I have tested the php code,that is,if data returned is true output alert box and is working.For instance
if(data=="true"){
alert(id);
}
However,on including this code
if(data=="true"){
$(this).html('<b>Offer Send</b>').css('background','#dce6f1');
$(this).attr("disabled","disabled");
}
and clicking the current id,i am unable to disable it and change it's attributes to offer send.
How can i deal with this problem
This is my div code
echo"<li id='td_request'><a id='id_".$fetch_num['order_id']."' class='buyerRequest' href='#".$fetch_num['order_id']."'>Send Offer</a></li>";
There were a few problems. I assume this is a button. I created a div to apply the styling to. The problem is that this is defined by scope. Inside of the post callback, this refers to the actual post object, not an html element.
<script>
$(document).ready(function() {
$('.buyerRequest').click(function() {
var id=$(this).attr('id').replace('id_','');
$.post('SendingOffer.php', {"id":id}, function(data) {
console.log(data);
if (data.length>0) {
$('#my_div').html('<b>Offer Send</b>').css('background','#dce6f1');
$('#id_my_button').prop("disabled",true);
}
else {
alert('You have reached the maximum number you can send todays');
}
});
});
});
</script>
<input type='button' class='buyerRequest' id='id_my_button' value='my_button'>
<br/>
<div id='my_div'></div>
$(this) might not be a very good idea to use inside a $.post. You better use a reference to the html object.
for example
$("#mydiv").html('Offer Send').css('background','#dce6f1');
$(this) usually refers to the current object in the context, in this case the ajax request if i am not mistaken. For example...
$(".mydiv").each(function(){
//using $(this) here refers to the current instance of .mydiv; not the DOM or the body
});
So, try this
$(document).ready(function(){
$('.buyerRequest').click(function(){
var id=$(this).attr('id').replace('id_','');
$.post('SendingOffer.php',{id:id},function(data){
if(data=="true"){
$("#**yourdivid**").html('<b>Offer Send</b>').css('background','#dce6f1');
$("#**yourdivid**").attr("disabled","disabled");
}else if(data=="false"){
alert('You have reached the maximum number you can send todays');
}
});
});
});
Working Code
<a id='id_0' class='buyerRequest' href='#0'>Send Offer</a>
<div id='responseDIV'></div>
<script>
$(document).ready(function(){
$('.buyerRequest').click(function(){
var id=$(this).attr('id').replace('id_','');
$.post('SendingOffer.php',{id:id},function(data){
if(data=="true"){
$("#responseDIV").html('<b>Offer Send</b>').css('background','#dce6f1');
$("#id_0").removeAttr("href");
}else if(data=="false"){
alert('You have reached the maximum number you can send todays');
}
});
});
});
</script>
Maybe "this" is ambiguous here, try to change into:
var currentBtn = $(this);
var id = currentBtn.attr('id').replace('id_','');
$.post('SendingOffer.php',{id:id},function(data){
if(data=="true"){
currentBtn.html('<b>Offer Send</b>').css('background','#dce6f1');
currentBtn.attr("disabled","disabled");
}else if(data=="false"){
alert('You have reached the maximum number you can send todays');
}
});
if disabled attribute does not work, you can try:
currentBtn.prop("disabled", true);
It belongs to your jQuery's version , reference: jQuery .attr("disabled", "disabled") not working in Chrome
Hope this help :)
I want to post something after writing it into a textarea without clicking any button but on clicking outside the textarea..How can I achieve that?? My code...
<form action="javascript:parseResponse();" id="responseForm">
<textarea align="center" name="post" id="post">Write something</textarea>
<input type="button" id="submit" value="submit" />
</form>
AJAX:
$('#responseForm').submit(function({$('#submit',this).attr('disabled','disabled');});
function parseResponse(){
var post_status = $("#post");
var url = "post_send.php";
if(post_status.val() != ''){
$.post(url, { post: post_status.val()}, function(data){
$(function(){
$.ajax({
type: "POST",
url: "home_load.php",
data: "getNews=true",
success:function(r)
{
$(".container").html(r)
},
})
})
document.getElementById('post').value = "";
});
}
}
I want to remove the button...and when an user clicks outside the textarea it will automatically submit the information...The whole body outside the textarea will act as the submit button...when user writes any info on the textarea...How can I achieve that??
Try the following:
$(document).on("click", function(e) {
var $target = $("#YOUR_ELEMENT");
if ($target.has(e.target).length === 0) {
your_submit_function();
}
});
You could also attach your submit function to the blur event for improved functionality:
$(document).on("click", function(e) {
var $target = $("#YOUR_ELEMENT");
if ($target.has(e.target).length === 0) {
your_submit_function();
});
$("#YOUR_ELEMENT").on("blur", function() {
your_submit_function();
});
You can attach a click handler to the entire document, and then cancel the event if the user clicked inside the text area. Something like this might do the trick:
$( document ).on( "click", function( ev ) {
if( $( ev.target ).index( $( "#post" )) == -1 ) {
// User clicked outside the text area.
}
} );
I use code similar to this to accomplish essentially the same thing (check when a user clicked outside of something). This is a copy and paste (slight alterations) of that code, and I haven't tested for your purposes. Essentially, it adds a handler to the entire document for the click event, then only executes the code if the element clicked on was not your textarea.
I have site running Jquery, Ajax, PHP, and an HTML form. It uses two pages.
Pages...
Example.php & Processexample.php
When you click the edit button on example.php a form pops up in the NyroModal window posting to Processexample.php and allows you to edit customer data that's posted using Ajax.
After user clicks save on Porcessexample.php a SQL update is made and a success message is posted back to the Modal Box (end-user).
Here are the issues...
I can't get the NyroModal window to close after (data) success is called on processexample.php. I tried setting the Timeout in JQ/Javascript below but error occurs.
setTimeout("$.nyroModal.close()", 4000);
How do i get example.php page to display updated data automatically, or have the page reload after #send button is clicked and success is displayed in modal window.
HTML Form Code on processexample.php
<form id="AjaxForm" name="AjaxForm" action="#" method="post">
<input name="submitform" type="hidden" value="1"
<button id="send">Save Client</button>
JS Code on processexample.php --> See bold text in code where issue is.
$(document).ready(function() {
$("#AjaxForm").submit(function() { return false; });
$("#send").on("click", function(e){
var idval = $("#client").val();
var calval = $("#view").val();
var emailval = $("#customer_email").val();
var nameval = $("#customer_name").val();
var phoneval = $("#customer_phone").val();
var msgval = $("#customer_note").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'saveclient.php',
data: $("#AjaxForm").serialize(),
success: function(data) {
if(data == "true") {
$("#AjaxForm").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your information has been updated.</strong></p>");
**setTimeout("$.nyroModal.close()", 4000);**
});
}
}
});
}
});
});
</script>
I was able to work this out myself. Use location.reload(); after the success call.
I have a form with number of submit type as images. Each image has a different title. I need to find out the title of the clicked image. But my click function inside form submit is not working.
My form is:
<form action='log.php' id='logForm' method='post' >
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" title="<?=$url;?> id="<?="image".$j?> class="images" />
<?
}
?>
</form>
Jquery:
$("#logForm").submit(function(e)
{
$(".advt_image").click(function(event) {
var href=event.target.title;
});
var Form = { };
Form['inputFree'] = $("#inputFree").val();
// if($("#freeTOS").is(":checked"))
Form['freeTOS'] = '1';
$(".active").hide().removeClass('active');
$("#paneLoading").show().addClass('active');
var url="http://"+href;
$.post('processFree.php', Form, function(data)
{
if(data == "Success")
{
$("#FreeErrors").html('').hide();
swapToPane('paneSuccess');
setTimeout( function() { location=url }, 2500 );
return;
}
swapToPane('paneFree');
$("#FreeErrors").html(data).show();
});
return false;
});
How can I get the title value of clicked image inside this $("#logForm").submit(function())?
How can I use the id of clicked image for that?
You can use event.target property
$("#logForm").submit(function(e)
alert($(e.target).attr('title'));
});
http://api.jquery.com/event.target/
[UPDATE]
I just realized it wouldn't work. I don't think there is a simple solution to this. You have to track the click event on the input and use it later.
jQuery submit, how can I know what submit button was pressed?
$(document).ready(function() {
var target = null;
$('#form :input[type="image"]').click(function() {
target = this;
alert(target);
});
$('#form').submit(function() {
alert($(target).attr('title'));
});
});
[Update 2] - .focus is not working, but .click is working
http://jsfiddle.net/gjSJh/1/
The way i see it, you have multiple submit buttons. Instead of calling the function on submit, call it on the click of these buttons so you can easily access the one the user chose:
$('input.images').click(function(e) {
e.preventDefault(); //stop the default submit from occuring
alert($(this).attr('title');
//do your other functions here.
});
// Runtime click event for all elements
$(document).on('vclick', '.control', function (e) { // .control is classname of the elements
var control = e.target;
alert(e.currentTarget[0].id);
});
if you are not getting proper message in alert, just debug using Firebug.
Check following code you can get the title of clicked image.
Single click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").click(function(event) {
alert(event.target.title);
});
return false;
});
});
Double click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").dblclick(function(event) {
alert(event.target.title);
});
return false;
});
});
add following ondomready in your rendering page
$(document).ready(function(){
$("form input[type=image]").click(function() {
$("input[type=image]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
Now in your form's submitt action add follwing behaviour and yupeee!... you got it!....
$("#logForm").submit(function(e)
{
var title = $("input[type=image][clicked=true]",e.target).attr("title");
.....
.....
});
I'm learning how to apply ajax to my jquery/php/mysql script for the purpose of callback firing. This question is probably from my ignorance when it come to the name of this term.
The Question: Is there a way to reset ajax callback without reloading the page script.
The Goal: I have a mysql query displaying on jQuery Accordian 1, 2, and 3. The goal is to click a query result href from Accordian and display the results in jQuery UI Tab 3 without a page reload...So far the script fires on my first callback but it doesn't fire a second time. Is there a term or jquery command that will reset jquery/ajax?
index.php
<?php
...script... include'right.content.php';
?>
<script type="text/javascript" >
$(function() {
$("#submit").click(function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
</script>
index.php - html section
<div id="stage">
<?php include'test.arena/test.php';?>
</div>
right.content.php
while ($row = mysql_fetch_array($result)){
if($row['stats'] == "1"){
$data .= "<tr><td colspan='2'>".$row['order_number']."</td>
<td colspan='2'>
<input type='hidden' id='string3' value='".$row['details']."'>
<input type='hidden' id='string2' value='".$row['order_number']."'>
<input type='button' id='submit' value='View'></td>
<td>info</td></tr>";
test.arena/test.php
if(!isset($_POST['string2'])){
$_POST['string2'] = "";
}else{
$string3 = "PO Number:" .$_POST['string3'];
$string2 = "Order:" .$_POST['string2'];
echo $string3 ."</br>";
echo $string2 ."</br>";
}
Is the element with ID 'submit' inside the one with ID 'stage'? If so, try changing $("#submit").click(function(){ to $("#submit").live('click', function(){.
The problem is probably because your submit button is inside of the 'stage' div. This means that when you load the new 'stage' content, it will delete the old button and add a new one and the new one won't have any click thing attached.
The quick fix for this is to use a 'live' handler.
$(function() {
$("#submit").live('click', function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
But the other solution, which might make the problem clearer, is to re-add the click handler after the load finishes.
$(function() {
function submitClicked() {
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load(
'test.arena/test.php',
{ 'string2':name, 'string3':lname },
function() {
addClickHandler();
}
); // display results from test.php into #stage
}
function addClickHandler() {
$('#submit').click(submitClicked);
}
addClickHandler();
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});