简体   繁体   中英

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:

<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"> .

A better way to solve this issue would calling the closeset elements input types to get the value:

    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.

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

$('.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);
           }
       });
});

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