ajax post list update only first of posts

I have a list of content that users send, such as tweeting, and they post a text, and the following content is also displayed. input I put an ID that updates that ID in Ajax, but because the posts are below and editing is modal, only one of the forms can be edited because the input ID is fixed
Can you please help?

@foreach($consult as $item)
                                <div id="cards" class="card data-id-{{$item->id}}">
                                    <div class="card-header">
                                        <h5 class="card-title">your consult</h5>

                                        <div class="card-tools">
                                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                                <i class="fas fa-minus"></i>
                                            </button>
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-tool " data-toggle="dropdown" aria-expanded="false">
                                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-supported-dps="24x24" fill="currentColor" class="mercado-match" width="24" height="24" focusable="false">
                                                        <path d="M14 12a2 2 0 11-2-2 2 2 0 012 2zM4 10a2 2 0 102 2 2 2 0 00-2-2zm16 0a2 2 0 102 2 2 2 0 00-2-2z"></path>
                                                    </svg>
                                                </button>
                                                <div class="dropdown-menu dropdown-menu-right" role="menu" style="">
                                                    <button data-toggle="modal" data-target="#modal-lg-{{$item->id}}" class="dropdown-item "><i class="fas fa-edit"></i> Edit</button>
                                                    <button  class="dropdown-item deleteskill" data-id="{{$item->id}}" data-token="{{ csrf_token() }}" ><i class="fas fa-trash"></i> Delete</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body" >
                                        <div class="post">
                                            <div class="user-block all-posts-body">
                                                @if(Auth::user()->photo)
                                                    <img alt="On Demand Consults" class="img-circle img-bordered-sm" src="/photo/avatar/{{Auth::user()->photo}}">
                                                @else
                                                    <img alt="On Demand Consults" class="img-circle img-bordered-sm" src="/img/avatar.png" >
                                                @endif
                                                <span class="username">
                                                      <a href="#">{{Auth::user()->name}}{{Auth::user()->family}}</a>
                                                   </span>
                                                <span class="description">Shared publicly - {{ CarbonCarbon::parse($item->created_at)->diffForhumans()}}</span>
                                                <p>
                                                    {{$item->description}}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            @endforeach

my modal
    @foreach($consult as $item)
                                <div class="modal fade" id="modal-lg-{{$item->id}}">
                                    <div class="modal-dialog modal-lg">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h4 class="modal-title">update your consult</h4>
                                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                    <span aria-hidden="true">&times;</span>
                                                </button>
                                            </div>
                                            <form data-id="{{$item->id}}" method="post" action="{{ route("Consult.update", $item->id) }}" enctype="multipart/form-data">
                                                @csrf
                                                @method('PUT')
                                                <div class="modal-body">
                                                    <textarea   id="description" name="description" class="form-control form-control-sm" type="text" placeholder="What do you want to talk about?" >{{$item->description}}</textarea>
                                                    <div class="alert-message" id="descriptiError"></div>
                                                </div>
                                                <div class="modal-footer justify-content-between">
                                                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                                    <button type="button" class="btn btn-primary updateInfo" data-id="{{$item->id}}" data-token="{{ csrf_token() }}">Save changes</button>
                                                </div>
                                            </form>
                                        </div>
                                        <!-- /.modal-content -->
                                    </div>

                                    <!-- /.modal-dialog -->
                                </div>

                            @endforeach

my ajax code
 $(".updateInfo").on('click',function(e) {
        e.preventDefault();
        let description = $('#description').val();
        const ConsultId = $(this).attr('data-id');
        var confirmation = confirm("Are you sure you want to update this Consult ?");
        if (confirmation) {
            $.ajax({
                type:"PUT",
                data:{
                    "_token": "{{ csrf_token() }}",
                    description:description,
                },
                url:'/ConsultantsCp/Consult/' + ConsultId,

                success: function(data){
                    swal({title: "Good job", text: "Consult is successfully updated!", type:
                            "success", timer: 1500, buttons: false,}).then(function(){
                            location.reload();
                        }

                    );

                },
                error: function(response) {
                    $('#descriptiError').text(response.responseJSON.errors.description);
                }
            });
        }

    });

enter image description here

enter image description here

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Similar as Rateb’s answer, however a bit different

First we have to declare a javascript function to initialize whatever we need to show in the modal form

Second we must call the function with the necessary content. In your case when we click the Edit button, it must cal the js function

Third is the logic you use to post the data.

Notice how i have encoded the description to preserve the format and i have deleted the other parameters in the modal form and declared a hidden field to contain the item-id.

@foreach($consult as $item)
    <div id="cards" class="card data-id-{{$item->id}}">
        <div class="card-header">
            <h5 class="card-title">your consult</h5>
            <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                    <i class="fas fa-minus"></i>
                </button>
                <div class="btn-group">
                    <button type="button" class="btn btn-tool " data-toggle="dropdown" aria-expanded="false">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-supported-dps="24x24" fill="currentColor" class="mercado-match" width="24" height="24" focusable="false">
                            <path d="M14 12a2 2 0 11-2-2 2 2 0 012 2zM4 10a2 2 0 102 2 2 2 0 00-2-2zm16 0a2 2 0 102 2 2 2 0 00-2-2z"></path>
                        </svg>
                    </button>
                    <div class="dropdown-menu dropdown-menu-right" role="menu" style="">
                        <button data-toggle="modal" data-target="#edit-modal" onclick="initModal({{$item->id}}, {{json_encode($item->description)}} )"  class="dropdown-item "><i class="fas fa-edit"></i> Edit</button>                       
                        <button  class="dropdown-item deleteskill" data-id="{{$item->id}}" data-token="{{ csrf_token() }}" ><i class="fas fa-trash"></i> Delete</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="card-body" >
            <div class="post">
                <div class="user-block all-posts-body">
                    @if(Auth::user()->photo)
                        <img alt="On Demand Consults" class="img-circle img-bordered-sm" src="/photo/avatar/{{Auth::user()->photo}}">
                    @else
                        <img alt="On Demand Consults" class="img-circle img-bordered-sm" src="/img/avatar.png" >
                    @endif
                    <span class="username">
                          <a href="#">{{Auth::user()->name}}{{Auth::user()->family}}</a>
                       </span>
                    <span class="description">Shared publicly - {{ CarbonCarbon::parse($item->created_at)->diffForhumans()}}</span>
                    <p>
                        {{$item->description}}
                    </p>
                </div>
            </div>
        </div>
    </div>
@endforeach

modal

<div class="modal fade" id="edit-modal">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">update your consult</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="edit-modal-form">                   

                    <div class="modal-body">
                        <textarea   id="description" name="description" class="form-control form-control-sm" type="text" placeholder="What do you want to talk about?" ></textarea>
                        <div class="alert-message" id="descriptiError"></div>

                        <input type="hidden" id="item-id-field">
                    </div>
                    <div class="modal-footer justify-content-between">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary updateInfo" >Save changes</button>
                    </div>
                </form>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>

scripts

function initModal(id, description)
{
      // Inialize the modal hidden field with the id value using Jquery
      $("#item-id-field").val(id);
     
       // decode the json and show it in the desciption field in the modal
      var description_decoded = JSON.parse(JSON.stringify(description));
      $("#description").html(description_decoded);
}


$(".updateInfo").on('click',function(e) {
    e.preventDefault();
    let description = $('#description').val();
    const ConsultId = $("#item-id-field").val();
    var confirmation = confirm("Are you sure you want to update this Consult ?");
    if (confirmation) {
        $.ajax({
            type:"PUT",
            data:{
                "_token": "{{ csrf_token() }}",
                description:description,
            },
            url:'/ConsultantsCp/Consult/' + ConsultId,
            success: function(data){
                swal({title: "Good job", text: "Consult is successfully updated!", type:
                        "success", timer: 1500, buttons: false,}).then(function(){
                        location.reload();
                    }
                );
            },
            error: function(response) {
                $('#descriptiError').text(response.responseJSON.errors.description);
            }
        });
    }
});

Method 2

Try this example, it’s a simple example assuming you have show route that gives the post info and edit route that submitting the edits, in this example we are not submitting form we just sending a request with ajax client called axios,

The blade file:

 <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>

<body>
    @foreach($consult as $item)

    <div id="cards" class="card">
        <div class="card-header">
            <h5 class="card-title">your consult</h5>

            <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                    <i class="fas fa-minus"></i>
                </button>
                <button data-id={{$item['id']}} type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
                    edit
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="post">
                <p>
                    {{$item['description']}}
                </p>
            </div>
        </div>
    </div>
    @endforeach

    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Edit post</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <input type="hidden" name="id">
                        <div class="form-group">
                            <label>Description</label>
                            <input name="description" class="form-control">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button name="save-button" type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
    </script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
    </script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.4/axios.min.js"></script>
</body>

<script>

    const modal = $('#exampleModal')
    const descriptionInput = $('input[name="description"]')
    const idInput = $('input[name="id"]')

    const saveButton = $('button[name="save-button"]')

    modal.on('show.bs.modal', (e) => {

        // getting the id from clicked button
        const postId = e.relatedTarget.getAttribute('data-id')

        // render the required post info 
        axios.get('/posts/' + postId).then(res => {
            descriptionInput.val(res.data.description)
            idInput.val(res.data.id)
        })
    })

    saveButton.on('click', () => {
        // the edit request in your example its /ConsultantsCp/Consult/' + ConsultId
        axios.put('/posts/' + idInput.val(), {
            _token: "{{ csrf_token() }}",
            description: descriptionInput.val(),
        }).then(res => {
            console.log(res)
            modal.modal('toggle')
        })
    })


</script>

</html>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x