0

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.

4
  • 5
    It should be noted that JQuery is JS. You aren't trying to convert between the two, you're trying to use JQuery. Commented Jan 30, 2018 at 15:20
  • 1
    And if you're getting errors, post them along with your debugging attempts. This question is quite broad and vague right now. Commented Jan 30, 2018 at 15:21
  • alright so im basically modifying the code then. at the moment the code works so im trying to identify the jquery version of it. Commented Jan 30, 2018 at 15:31
  • 1
    It could be helpful youmightnotneedjquery.com Commented Jan 30, 2018 at 15:51

1 Answer 1

2

If you already have a working javaScript only function, you should really consider keeping it as is. jQuery will make a lot of tasks easier, but also requires loading the library. Especially if you don't use it a lot, it's unnecessary overhead. In jQuery you do something like the following:

$(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...');
        }
    });
});

Of course I couldn't test it without the functions displayOutput and the source for the data. But I think this should work. If not, please let me know and provide the errors, and I'll adjust my answer.

Sign up to request clarification or add additional context in comments.

10 Comments

this might be what im aiming for, thank you! ill post the rest of the code if this doesnt work. it seems your missing a bracket for the ajax(
Whoops made an error indeed. I've updated my answer, thanks for the hint.
alright so i gave your solution a go, it seemed to give me errors even though it does look like it should work. ive updated the code you provided and what im using the code with.
there seems to be something wrong with displayout function, nothing is linking but the data is there
Ohh wow, I totally thought that responseText was an entry in your response. But it's plain javascript response from a plain javascript ajax response. I'm sorry, I didn't know that. You probably should remove the .responseText after response in let data = response.responseText; -> let data = response;. Or just set success: function(response){to success: function(data){ and remove the line let data = response.responseText;. That was a really noobish mistake from my side, I'm sorry.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.