Home > Software design >  TypeError: Cannot read properties of undefined (reading 'forEach') with ajax method
TypeError: Cannot read properties of undefined (reading 'forEach') with ajax method

Time:11-08

I have ajax funtion:

<div ></div>



...



    const url = window.location.href

    const quizBox = document.getElementById('quiz-box')

    let data

    $.ajax({
        type: 'GET',
        url: `${url}data/`,
        success: function(response){
            // console.log(response)
            data = response.data
            data.forEach(el => {
                for (const [question, answers] of Object.entries(el)){
                    quizBox.innerHTML = `
                        <b>${question}</b>
                    `
                }
            });
        },
        error: function(error){
            console.log(error)
        },
    })

Which gets data from django view.

Now this results in an error in console:

Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') at Object.success at j

at Object.fireWith [as resolveWith]

at x

at XMLHttpRequest.b

Why is this error occuring and how can I prevent this?

CodePudding user response:

use the optional chaining (?.) operator to check if the variable is not null before accessing it.

change :

data.forEach(el => {.....

to :

data?.forEach(el => {.....

and make sure to access div correctly you have to :

change :

   <div ></div>

to :

<div id="quiz-box"></div>
  • Related