i am trying to show candidate's data but unfortunately getting error using ajax

Viewed 24

I am trying to show candidate's data but unfortunately i am getting error ReferenceError: candidates is not defined please help me how can i resolve that thanks.

Ajax script

<script>
$(document).ready(function(){
$('.election').on('change', function(){
var id = $(this).val();
$('#electionPosition').empty();
    axios
    .post('{{route("election.voting.search")}}', {
    _method: 'post',
    _token: '{{csrf_token()}}',
    election_id: id,
    })
    .then(function (response) {
    response.data.election_postion.forEach(element => {
    element.election_candidate.forEach(elements =>{

       let candidates = `<div class="col-lg-6 col-xl-4">
            <div class="card">
                <img class="rounded-circle userImage" src="{{ url('') }}/assets/images/download.png"  alt="Card image cap">
                <div class="card-body">
                    <h5 class="card-title text-center">${elements.candidate.name}</h5>
                </div>
            </div>
        </div>`

    })
    $('#electionPosition').append(`
        <h3 class="heading">${element.position.name}</h3>
        <div class="row">
            ${candidates}
        </div>
    `);
    });

    })
    .catch(function (error) {
    console.log(error);
    });
});
});
</script>
1 Answers

You should put $('#electionPosition').append(.... }); code in your element.election_candidate.forEach(...) loop, because candidates is defined in this loop and you cannot access it from outside.

Related