jQuery each loop on json response after ajax in laravel

You can loop through the json data in jQuery using $.each method in jQuery. The jQuery method has two values (index and value) and you can get the value of each record using the value.keyname.

Answers 1
  • Append data to div using foreach loop in jQuery on json response after ajax call in laravel

    //code inside controller's method
    $users = User::select('name', 'id')->where('name',  'like', '%' . $request->name . '%')->get();
    return response()->json(['data' => $users]);
    //script 
    $('#eventSpeaker').keyup(function(){
        var input = $(this).val();
        
        $.ajax({
            url: "/get-users",
            method: "POST",
            data:{
                name: input,
            },
            success:function(response){
                html = "";
                html += '<ul class="list-unstyled">';
                $.each(response.data, function( index, value ) {
                    html += '<li class="my-2 text-capitalize" style="cursor:pointer" data-id="'+ value.id +'">' + value.name +'</li>';
                });
                html += '</ul>';
                $('#speakerResponse').empty('').append(html);
                console.log(html);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr.status);
                console.log(thrownError);
            }
        });
    });
    
    0

    You can easily append data to div after each method in jQuery. This code snippet helps you to get the record with name using search input and after that you can use jQuery each method to get the value and append data to the html element.

  • Back to code snippet queries related laravel

Related queries helps you to understand and may also used for implementation of current code snippet