简体   繁体   English

ajax调用仅显示每个循环中第一项的输入值。 需要它显示取决于按钮单击的上下文

[英]ajax call only showing input values for the first item in for each loop. Need it to display depending on context of button click

I am trying trying to post data to a controller based on the context of the button click in the for each loop. 我试图基于每个循环中单击按钮的上下文将数据发布到控制器。 The response is only showing the first iteration of the loop. 该响应仅显示循环的第一次迭代。


@foreach($obj['questions'] as $question)
        <form class="col-md-12" id="upvote">
        <input type="hidden" value="{{$question->id}}" id="question_id" data-id="{{$question->id}}" class="form-control question_id">
        <input type="hidden" value="{{$user->id}}" id="user_id" data-id="{{$user->id}}" class="form-control user_id">
        <button class="btn btn-xs fas fa-arrow-up btn-submit" style="{{ in_array($question->id, $upvotes) ? 'color:gray' : 'color:orange' }}" {{ in_array($question->id, $upvotes) ? 'disabled' : null }}></button>
        </form>
@endforeach

And my ajax script looks like this: 我的ajax脚本如下所示:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajaxSetup({
            headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('.btn-submit').click(function(e){
        e.preventDefault(); 
        var question_id = $("input[id=question_id]").val();
        var user_id = $("input[id=user_id]").val();
            $.ajax({
                url: "{{ route('welcome.upvoteAjax') }}",
                type: 'POST',
                data: {question_id:question_id, user_id:user_id},
                dataType: 'json',
                success: function (data) {
                    console.log(data);
                }
            });
        });
    });
</script>

My route: 我的路线:


Route::post('/upvoteAjax', 'WelcomeController@upvoteAjax')->name('welcome.upvoteAjax');

And my controller looks like this: 我的控制器如下所示:

public function upvoteAjax(Request $request){
   if($request->ajax()) {
      return response()->json($request);
   }
}

The response I get in console is (I attached a screenshot of the browser as well): 我在控制台中得到的响应是(我还附加了浏览器的屏幕截图):

(index):593 {question_id: "736", user_id: "1"}
(index):593 {question_id: "736", user_id: "1"}
(index):593 {question_id: "736", user_id: "1"}

This is the output regardless of which item in the loop I click. 无论我单击循环中的哪个项目,这都是输出。 The output that I want is the question and the user associated with the iteration of the loop that is displayed on the front end. 我想要的输出是问题以及与前端显示的循环迭代关联的用户。 Any feedback would be appreciated. 对于任何反馈,我们都表示感谢。

Thanks. 谢谢。

这是Chrome控制台的屏幕截图

When you are clicking the submit button, You're fetching the value from the first field it finds example 当您单击“提交”按钮时,您将从它发现示例的第一个字段中获取值

<input id="question_id"> . <input id="question_id">

A better way to solve this issue would calling the closeset elements input types to get the value: 解决此问题的更好方法是调用closeset元素输入类型以获取值:

    var question_id = $(this).closest('.question_id').val();

This will make sure the form values corresponds the input that button is submitting. 这将确保表单值对应于按钮正在提交的输入。 Also ID is unique for each element. 每个元素的ID也是唯一的。

here try this: 在这里试试这个:

let btns = document.querySelectorAll('.btn')
btns.forEach((btn) => {
    btn.addEventListener('click', function(event){
        event.preventDefault();
        let question_id =  btn.parentNode.children[0].value
        let user_id = btn.parentNode.children[1].value

        $.ajax({
                url: "{{ route('welcome.upvoteAjax') }}",
                type: 'POST',
                data: {question_id: question_id, user_id: user_id},
                dataType: 'json',
                success: function (data) {
                    console.log(data);
                }
        })

    })
  })
}

After referencing Aditya's answer and understanding how the references work I did some more searching and now this works for me 在参考了Aditya的答案并理解了参考如何工作之后,我进行了更多搜索,现在对我有用

$('.btn-upvote').click(function(e){
   e.preventDefault(); 
   var question_id = $(this).parent().find('.question_id').val();
   var user_id = $(this).parent().find('.user_id').val();
       $.ajax({
           url: "{{ route('welcome.upvoteAjax') }}",
           type: 'POST',
           data: {question_id:question_id, user_id:user_id},
           dataType: 'json',
           success: function (data) {
               console.log(data);
           }
       });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WordPress:在每个循环中遍历多个api获取。 仅返回第一个数组项的响应 - Wordpress: Iterate through multiple api fetches within for each loop. Only returns response for first array item 无法遍历类别循环内的帖子。 仅获得第一项 - Can't loop through posts inside a category loop. Only get the first item $ .each仅显示json的第一个值,而其他值在ajax成功中显示为未定义。 - $.each showing only first value of json and other values are shown as undefined in ajax success.? 当我单击按钮时,它仅在第一个显示输出div&#39;mouse_move&#39;时在jQuery ajax上显示图像,而在另一次单击上不显示相同图像 - When I click button it display image with jQuery ajax on output div 'mouse_move' only for first one but not display same on another click 单击按钮时仅显示输入框 - only display input boxes when button is click 循环显示每个项目 - Display each item in loop Ajax只在while循环中获取数据的第一项 - Ajax get data only first item in while loop Ajax成功功能仅更新首次点击的值 - Ajax success function only updating values for first click php中的jQuery ajax调用while循环仅返回第一个id - jQuery ajax call in php while loop only returns first id 如何仅显示3条评论,然后每个按钮单击再显示10条评论 - How to display only 3 comments and then 10 more comments on each button click
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM