如何为表单动态生成唯一的ID,该ID是弹出式表单以评论每个帖子,但它会获取最后的帖子ID

时间:2019-08-22 16:27:30

标签: javascript php jquery ajax laravel

我想用包含4-5个字段的弹出表单对帖子发表评论。我想在弹出表单中提供要评论的帖子的帖子ID,但是当通过隐藏字段发布此ID时,它总是导致最后一个帖子ID。如何生成动态不同的ID,该ID可为我提供确切的帖子ID?

<form id="forms">
  <label for="email">Facility :</label>
  <input type="text" class="form-control" id="facility" name="facility" maxlength="50">  
  //printing{{$customerpost->id}} this value gives correct post id
  <input type="hidden" name="hidden" value="{{$customerpost->id}}" id="hidden">
  <button type="submit" class="btn btn-lg btn-primary btn-block"  id ="submit">Post It! </button>
</form>

$( 'form' ).submit(function ( e ) {
    var data;
    data = new FormData();

    $.ajax({
        headers: {
            'X-CSRF-TOKEN':  $('meta[name="csrf-token"]').attr('content'),
            authorization:  $('meta[name="csrf-token"]').attr('content'),
        }
    });

    data.append('facility', $("#facility").val());
    data.append('hidden', $("#hidden").val());

    console.log(data);
    alert(data);

    $.ajax({
        url: 'api/bidon/',
        data: data,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function ( data ) {
            alert("sucess");
            alert( data );
        }
    });

    e.preventDefault();
});

当我登录到控制台时,它总是为我提供最后的帖子ID。如何使用Laravel框架解决此问题?

1 个答案:

答案 0 :(得分:0)

点击即可简单执行

<!-- Add post id in attribute -->
<div data-id="12345" class="btn"> add comment </a>

<script type="text/javascript">
$('body').on('click','.btn',function(){
    // get id from         
    var id = $(this).attr('data-id');
    // set id to hidden attribute
    // $('#hidden').attr('data-id', id);
    // or set id to hidden input
    $('#hidden').val(id);
    // Show form
    $('#forms').slideUp();
});
</script>