简体   繁体   中英

Ajax to submit form generated dynamically by PHP do-while loop

I have an evaluation bar(progress bar generated by javascript), users can select a value and click to submit it. The issue is that I'm using PHP to generate the evaluation bars dynamically (using a do-while loop). I can't figure out how to setup AJAX to recognized and submit any of the forms. Now it's submitting only the first one, even though I submit any of others.

My PHP code:

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form3")) { 
$insertSQL = sprintf("INSERT INTO tblpersonalidad (idUser, idPost, intEvaluacion, dateFecha) VALUES (%s,%s,%s,%s)",
                   GetSQLValueString($_POST['idUser'], "int"),
                   GetSQLValueString($_POST['idPost'], "int"),
                   GetSQLValueString($_POST['intEvaluacion'], "int"),
                   GetSQLValueString($_POST['dateFecha'], "timestamp"),
                   );

mysql_select_db($database_conexionproject_poll, $conexionproject_poll);
$Result1 = mysql_query($insertSQL, $conexionproject_poll) or die(mysql_error());

$insertGoTo = "";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}

 do {
 <form id="form3" name="form3">

      <div class="progress-user">
           <div class="progress-bar-user progress-bar-danger-user"></div>
           <div class="progress-bar-user progress-bar-warning-user"></div>
           <div class="progress-bar-user progress-bar-success-user"><span class="rating">0%</span></div>
     </div>

      <input class="mi-input" name="intEvaluacion" type="hidden" value="" />
      <input type="hidden" name="MM_insert" value="form3" />                       
      <input type="hidden" name="intActivo" value="1" />
      <input type="hidden" name="idPost" value="<?php echo $row_Datos_polls['idPost']; ?>" />
      <input type="hidden" name="idUser" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
  </form>

    } while ($row_Datos_polls = mysql_fetch_assoc($Datos_polls));


<script>

$('.progress-user').on('mousemove', function (e) {
var self = this;  
var offset = $(self).offset(); 
var width = $(self).width();
var relX = Math.round(10 * (e.pageX - offset.left)/width) * 10;
setBarRating(self, relX);
$(self).siblings('.mi-input').val(relX);
});

$("#form3").submit(function(a) {
var url = "<?php echo $editFormAction; ?>"; // the script where you handle the form input.

$.ajax({
       type: "POST",
       url: url,
       data: $('#form3').serialize(), // serializes the form's elements.
       success: function(data)
       {
           alert(data); // show response from the php script.
       }
     });

e.preventDefault(); // avoid to execute the actual submit of the form.
        });

$('.progress-user').click(function() {
$("#form3").submit();
});


var setBarRating = function (self, percentage) {
$(self).find('.progress-bar-success-user span.rating').text(percentage + '%'); 
if (percentage <= 50) {
$(self).find('.progress-bar-danger-user').width(percentage + '%');
$(self).find('.progress-bar-warning-user').width(0);
$(self).find('.progress-bar-success-user').width(0);
} else if (percentage > 50 && percentage <= 80) {
$(self).find('.progress-bar-danger-user').width('50%');
$(self).find('.progress-bar-warning-user').width((percentage - 50) + '%');
$(self).find('.progress-bar-success-user').width(0);
} else if (percentage > 80) {
$(self).find('.progress-bar-danger-user').width('50%');
$(self).find('.progress-bar-warning-user').width('30%');
$(self).find('.progress-bar-success-user').width((percentage - 80) + '%');
}
};
</script>

I'll really appreciate any help. I haven't could realized what is the modification to the AJAX + PHP code. Many thanks for your time.

You're generating several forms with id=”form3”. You're also listening to $(“form3”).submit(). You're submitting those forms by listening clicks to '.progress-user':

$('.progress-user').click(function() { $("#form3").submit(); });

So, not matter wich .progress-user do you click on, the first #form3 will be the form submitted.

You should generate unique id's to your forms and bars when creating them inside the loop. IE;

$i = 0;
do {
<form id="<?php echo 'form' . $i ?>"  name="<?php echo 'form' . $i ?>"    class="progress-form">

  <div class="progress-user" id="<?php 'progress-user' . $i; ?>" data-numer="<?php echo $i; ?>"  >
       <div class="progress-bar-user progress-bar-danger-user"></div>
       <div class="progress-bar-user progress-bar-warning-user"></div>
       <div class="progress-bar-user progress-bar-success-user"><span class="rating">0%</span></div>
 </div>

  <input class="mi-input" name="intEvaluacion" type="hidden" value="" />
  <input type="hidden" name="MM_insert" value="form3" />                       
  <input type="hidden" name="intActivo" value="1" />
  <input type="hidden" name="idPost" value="<?php echo $row_Datos_polls['idPost']; ?>" />
  <input type="hidden" name="idUser" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
  </form>
  $i++; //dont forget this :-)
} while ($row_Datos_polls = mysql_fetch_assoc($Datos_polls));

Now you have several forms with its own unique id and several progress bars with its unique id and a data-number attribute. Also, the dinamically generated form have that 'progress-form' class.

So now you can listen to clicks on progress bars like before, then caching the data-number of that element: $('.progress-user').click(function() { var formNumber = $(this).attr('data-number'); $("#form" + fromNumber).submit(); }); This way, you can be sure the form being submitted is the one whose progress-bar was clicked. Now you should also modify your submit listener:

$('.progress-form').submit(function(e){
    var url = "<?php echo $editFormAction; ?>"; 
    var data = $(this).serialize(); 

    $.ajax({
       type: "POST",
       url: url,
       data: data,
       success: function(data)
       {
           alert(data); // show response from the php script.
       }
     });
   e.preventDefault();
});

So now you're serializing and sending only the form whose progress bar was clicked, and not the first '#form3' in the document.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM