tumbin tumbin - 4 months ago 4
Ajax Question

ajax form submits blank description to only first ids

I have below code for submitting the form with ajax but only first instances out of 5 comment box are being submitted for balance I am getting discription=" and also being inserted to the wrong id. here is my code and live example. I want to allow users to comment on any items

http://way2enjoy.com/app/jokestest-991-1.php

$output .='<div id="'.$idd.'" align="left" class="messagelove_box" ><div class="content_box_1">
<div class="content_box_2z"><sup class="joke_icon"></sup></div>
<div class="content_box_3_title"></div>
<div class="content_box_3_text">'.nl2br($cont).'</div>



<script type="text/javascript">
var ajaxSubmit = function(formEl) {

var url = $(formEl).attr(\'action\');


var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden'. $idd.'").value;
$.ajax({
url: url,
data:{
\'action\':\'addComment\',
\'comment\':comment,
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {

console.log(result);
$.ajax({
url: url,
data:{
\'action\':\'getLastComment\',
\'joke_id\':joke_id
},
dataType: \'json\',
type:\'POST\',
success: function(result) {

$(\'#jokes_comment\').val("");
console.log(result[0].description);
$("#header ul").append(\'<li>\'+result[0].description+\'</li>\');



},
error: function(){
alert(\'failure\');


}
});

},
error: function(){
alert(\'failure\');


}
});

return false;
}

</script>
<div id="header" class="content_box_31_text"><ul id="commentlist" class="justList">'.$contpp.'</ul></div>
<form method="post" action="check/process2.php" class="button-1" onSubmit="return ajaxSubmit(this);"><input type="hidden" value="'. $idd.'" id="joke_id_hidden'. $idd.'"><input type="text" id="jokes_comment" value="" name="jokes_comment">
<input type="submit" value="comment"></form>


</div></div>
';

Answer

The code posted doesn't tell the full story, but looking at the URL mentioned does. The snippet you've posted is being repeated over and over again, identically in the page. That means that each definition of the ajaxSubmit function overwrites the previous one, and that you have multiple input elements all with the same id. No wonder the page is confused as to what to do. You only need one submit function, if it's written properly it can handle all the different comment inputs. And your comment inputs can't have the same id each time, but they can have the same CSS class, and since they are all within the form, when we submit a specific form, we know the context we are working in, and jQuery can automatically find all the fields in the form for us, without us having to write code to access them all individually.

So..with that design in mind, define your javascript like this, and make sure it only gets rendered once in your entire page output. I've re-written it slightly to take advantage of the easier syntax provided by jQuery.

$(".comment-form").submit(function(event) {
  event.preventDefault(); //prevent the default postback behaviour
  var form = $(this);
  var jokeID = form.find(".joke_id").val();

  $.ajax({
    url: form.attr("action"),
    type: "POST",
    dataType: "json",
    data: $(this).serialize(), //automatically finds all the form fields and puts the data in postback-friendly format
    success: function(result) {
      //I'm not convinced you need this second ajax call - can't you just write the contents of the input box directly into the list? But I'll leave it here in case you want it
      $.ajax({
        url: form.attr("action"),
        type: "POST",
        dataType: "json",
        data:{
           "action":"getLastComment",
           "joke_id": jokeID
        },
        success: function(result) {
          form.find(".jokes_comment").val("");
          $("#header-" + jokeID + " ul").append("<li>" + result[0].description + "</li>");
        },
        error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
                    alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
        }
      });          
    },
    error: function (jQXHR, textStatus, errorThrown) { //this is the correct definition of the error function as per jQuery docs
                    alert("An error occurred while contacting the server: " + jQXHR.status + " " + jQXHR.responseText + ".");
    }
  });
});

Secondly, make the PHP that generates the comment markup for each joke look like this:

<div id="header-'.$idd.'" class="content_box_31_text">
  <ul id="commentlist" class="justList">'.$contpp.'</ul>
</div>
<form method="post" action="check/process2.php" class="button-1 comment-form">
  <input type="hidden" value="'. $idd.'" name="joke_id"/>
  <input type="hidden" value="addComment" name="action" />
  <input type="text" class="jokes_comment" value="" name="comment" />
  <input type="submit" value="comment">
</form>
Comments