so currently, I have this ajax statement combined with javascript to run an external file and grab its data like so:
const ajaxRequest = new XMLHttpRequest();
const handleResponse = function() {
//have we got a response from the server
if (ajaxRequest.readyState === 4) {
//did we find the requested resource?
if (ajaxRequest.status === 200) {
// console.log(ajaxRequest.responseText); //testing file
let data = JSON.parse(ajaxRequest.responseText)
let ul1 = document.querySelectorAll('.ajax')[0];
let ul2 = document.querySelectorAll('.ajaxCheck')[0];
let ul3 = document.querySelectorAll('.ajaxCheck')[1];
if (ul1) {
ul1.innerHTML = displayOutput(data, false);
} else {
ul2.innerHTML = displayOutput(data, true);
ul3.innerHTML = displayOutput(data, true);
}
}
}
}
ajaxRequest.open('GET', 'data/games.json', true);
ajaxRequest.onreadystatechange = handleResponse;
ajaxRequest.send(null);
what im trying to do is simply convert it into a jquery like substance. made an earlier attempt and simply replaced some of the code but it kept running into various errors
$(document).ready(function() { //Make sure the document is done loading
$.ajax({ //Initialize the ajax object
url: "data/games.json", //set the target url`
dataType: 'JSON', //set the expected response type
success: function(response){ //On success we do something
let data = response.responseText;
let ul1 = $('.ajax')[0];
let ul2 = $('.ajaxCheck')[0];
let ul3 = $('.ajaxCheck')[1];
if (ul1) {
ul1.html(displayOutput(data, false));
} else {
ul2.html(displayOutput(data, true));
ul3.html(displayOutput(data, true));
}
},
error: function() {
console.error('Whoops something went wrong...');
}
});
});
console.log(data);
const displayOutput = (games, hasCheckbox) => {
var newReleases = games.filter(function(game){
if(game.Type==="New Release"){
return true;
}
return false;
})
var comingSoon = games.filter(function(game){
if(game.Type==="Coming Soon"){
return true;
}
return false;
})
console.log(games[1]["Genres"]);
//let ul = document.getElementById('ajax');
let output = "";
var x = 0;
games.forEach(game => {
x++;
output +=`
<li>
<div class=""><input id="togg`+x+`" type="checkbox"><label for="togg`+x+`" class="${hasCheckbox ? 'visible' : 'invisible'}">Compare</label></div></li>
<li><a href=#><img class="frontGames" src="${game.image}">
<p><b>Name:</b>${game.Name}<br>
<b>Release Date:</b>${game.ReleaseDate}</br>
<b>Genres:</b>${game.Genres}</br>
<b>Retail Price:</b>${game.RetailPrice}</br>
<b>Rating:</b>${game.Rating}</br></p></a>
</li>`;
})
return output;
}
this gives errors, the data bit no longer makes sense.
Surely given that jquery is a shorter form of Js, it would be a simple matter of replacing some of the lines and removing some bits out. im unsure of how to go about it so any help would be greatly appreciated.
given it a few test and getting a bunch of errors:
1.displayout not defined 2.cannot read property of foreach.
everytime i make a correction, a new error pops up.