Home > database >  Undefined variable JS AJAX
Undefined variable JS AJAX

Time:01-26

I'm trying to display Objects received through JSON arrays, communicating in AJAX with my backend server (Django). All the AJAX/Communication part works well. I want to display the received objects in a chatbox.

This is my arrays

However, my code gets undefined variables when displaying the Arrays. HTML:

    <div id="display"></div>

JS:

<script>
    $(document).ready(function(){
    
    setInterval(function(){
        $.ajax({
            type: 'GET',
            url : "/checkview",
            success: function go(response){
                console.log(response);
                $("#display").empty();
                for (var model in response.models_to_return)
                {
                    var temp="<div class='container darker'><b>"  model.user_id  "</b><p>"  model.room  "</p><span class='time-left'>"  model.datetime  "</span></div>";
                    $("#display").append(temp);
                }
            },
            error: function(response){
                //alert('An error occured')
            }
        });
    },1000);
    })
</script>

Front-end ouput

CodePudding user response:

You can use forEach for json array loop.

Here is code.

response.models_to_return.forEach(function(model, index) {
    console.log(model);
});

Full exmaple:

const models = [
{fname:"John", lname:"Doe", age:25},
{fname:"John2", lname:"Doe2", age:26},
{fname:"John3", lname:"Doe3", age:27}
];

models.forEach(function(model) {
    console.log(model.fname);
});

CodePudding user response:

Use for...of to loop over the elements of an array. for...in should instead be used for iterating over properties.

for (const model of response.models_to_return)
  • Related