A page with several divs and a form in each one

1

I'm making a page with elements that can be commented:

element_1 (id_1)  --->escribe tu comentario ---> OnClick abre div con un formulario
element_2 (id_2)  --->escribe tu comentario ---> OnClick abre div con el mismo formulario
element_3 (id_3)  --->escribe tu comentario ---> OnClick abre div con el mismo formulario
etc.

Like any site with comments, when you click, via AJAX, the corresponding form is opened (which is always the same), with a textarea to write your comment. Each form includes a captcha.

Form

<form action="#" method="post" id="<?php echo $post_id; ?>" class="comment">
   <textarea name="comment_post" maxlength=400 id="comment_post"></textarea><br />

   Enter code...
   <img src="grafica/img.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
   <input id="6_letters_code" name="6_letters_code" type="text"><br>
   <span style="margin-left:105px;position: relative;top: -15px;"><small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small></span><br/>
   <input type="button" class="submit" value=" Submit Comment " />
</form>

Send comment

$(function() {
$(".submit").click(function() {
var comment_post = $("#comment_post").val();
var captcha = $("#6_letters_code").val();
     $.ajax({
        type: "POST",
... se envia el formulario ...

Refresh captcha

function refreshCaptcha()
{
    var img = document.images['captchaimg'];
    img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}

When we open a div it works (send and captcha), but when we open a second div , the form submission and refreshCaptcha() stop working .

I suspect that this happens by putting several forms in divs without refreshing page. If anyone knows how to solve it, I would appreciate it.

    
asked by kalimero 11.04.2017 в 15:54
source

1 answer

0

I think some information is missing.

Are the forms static ?, that is, are they always on the page or are you loading them with AJAX? Or how do you make the form "that is always the same" go to the second div?

I ask you this because if you are bringing the form with AJAX or if you are moving it from its place it propagates that the script does not know it exists, because javaScript is executed only once, so you would have to recreate the event " $ (". submit"). click (function () {...}) "in the AJAX's success or better yet, you can create a function and send it to call in the success, like this:

(function($){
function btnSubmit(){
    $('.submit').click(function(){
        $.ajax({
            type: 'POST',
            url: '...',
            success: function(result){
                btnSubmit();
            }
        });
    });
}}(jQuery));
    
answered by 12.04.2017 в 10:06