I need your help concerning AJAX Responses with Symfony. On my page I have select options and want only refresh them, if anything in DB has changed. Now I'm loading every five seconds and checking if data count is different. But on the other hand users could also edit/rename old options. If I only check the count it's not possible to refresh the list. So how can I check if old response different than the new one?
Thanks in advance!! (My code in JS as follows)
let Routing = require('../../vendor/friendsofsymfony/jsrouting-bundle/Resources/public/js/router')
let Routes = require('./js_routes')
Routing.setRoutingData(Routes)
let select_options = document.getElementById("person_names")
document.addEventListener('DOMContentLoaded', function (event) {
if(window.location.href.indexOf("entity=Person&action=new") > -1 || window.location.href.indexOf("entity=Person&action=edit") > -1){
let firstRequest = true;
let responseOld
window.setInterval(function () {
new Promise( function (resolve, reject) {
let url = Routing.generate('getNewPersonList')
let xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
xhr.addEventListener('load', function (event) {
if (this.status === 200 && this.statusText === "OK"){
resolve(JSON.parse(this.responseText))
} else {
reject(JSON.parse(this.responseText))
}
})
xhr.send()
})
.then((response) => {
debugger;
if (firstRequest){
responseOld = response
firstRequest = false
// document.cookie = "Names=" + response + "; expires=Thu, 18 Dec 2019 12:00:00 UTC; path=/refreshNames";
console.log("first")
}
if (select_options.length !== response.length) {
console.log(select_options)
console.log(response)
// Drop old options
select_options.length = 0
// Fill it with new names
for (let index = 0; index < response.length; index++) {
let $option_element = document.createElement('option')
$option_element.value = response[index].id
$option_element.text = response[index].name
select_options.appendChild($option_element)
}
}
})
.catch((error) => {
console.log(error)
})
}, 5000)
}
})