I am currently creating a feature on a webpage that aims to create an HTTP request to a server with js when a certain dropdown menu value is changed and the change the webpage based on the request response. To accomplish this, I am using a Laravel @include to include the view that will build the page based on the json response.
The problem lies on this line allNews.innerHTML+=(`@include('partials.news.post',['news'=>`+news.data[i]+`])`)
The problem here is that an error (in the view caused by the argument news.data[i] being null) is immediately thrown by js when the page is loaded, it doesn't even wait for the EventListener to be triggered or for the request to be answered. If I delete this line of code it does not throw any error and works as expected, but if I comment it, the same error happens, which seems odd to say the least. What seems to be the problem here?
I used this stackoverflow question to base my development on.
I know the view is well built and does not throw errors because I use it in other instances.
<script defer>
let select = document.getElementById("sort-select");
let allNews = document.getElementById("posts-result");
let xhttp = new XMLHttpRequest();
console.log(js_query)
select.addEventListener("change",function(){
xhttp.open("GET", "/api/load-posts-search?sortBy="+ select.value +"&search=" + js_query, false);
xhttp.send();
let news = JSON.parse(xhttp.responseText);
console.log(news);
allNews.innerHTML=""
for(i=0;i<news.total;i++)
{
console.log(news.data[i]);
allNews.innerHTML+=(`@include('partials.news.post',['news'=>`+news.data[i]`])`)
}
})
</script>