0

I want to parse json array with jquery and success ajax response. the json look like this :

{
"data": {
    "list_app_banner_and_schedule": [
        {
            "due_date": "2022-02-19T00:00:00",
            "start_showing_on": "2022-02-18",
            "removed_on": "2022-02-22T00:00:00"
        },
        {
            "due_date": "2022-02-20T00:00:00",
            "start_showing_on": "2022-02-18",
            "removed_on": "2022-02-23T00:00:00"
        }
    ],
    "list_email_banner_schedule": [
        {
            "due_date": "2022-02-19T00:00:00",
            "sent_on": "2022-02-22T00:00:00"
        },
        {
            "due_date": "2022-02-20T00:00:00",
            "sent_on": "2022-02-23T00:00:00"
        }
    ],
    "list_pn_banner_schedule": [
        {
            "due_date": "2022-02-19T00:00:00",
            "sent_on": "2022-02-22T00:00:00"
        },
        {
            "due_date": "2022-02-20T00:00:00",
            "sent_on": "2022-02-23T00:00:00"
        }
    ]
  } 
}

and i want to create something like this : enter image description here

Here's my code :

$.ajax({
url: "{%url 'url' %}",
type: "POST",
dataType: "json",
headers: {
    "X-CSRFToken": token
},
contentType: "application/json",
data: JSON.stringify(obj, null, 2),
success: function(data, status, xhr) {
    var table = $("<table><tr><th>Schedule Banner</th></tr>");
    table.append("<tr><td>Start Showing On:</td><td>" + data["list_app_banner_and_schedule"]["start_showing_on"] + "</td></tr>");
    table.append("<tr><td>Removed On:</td><td>" + data["list_app_banner_and_schedule"]["removed_on"] + "</td></tr>");

    $("#message").html(table);
},
error: function(xhr, status, error) {
    alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
})

but I got error "Cannot read properties of undefined (reading 'start_showing_on')". What I did wrong?

DIR
  • 57
  • 4
  • I have no idea what `success: $.each(list_app_banner_and_schedule,` is *supposed* to do. – Quentin Feb 23 '22 at 18:28
  • `success` takes a function. You're assigning the result of a function call to it. Check the documentation for how to actually use it. – VLAZ Feb 23 '22 at 18:29
  • sorry, I just updated my code – DIR Feb 23 '22 at 18:31
  • It's `data.data.list_app_banner_and_schedule.forEach(...)` – Barmar Feb 23 '22 at 18:34
  • You didn't notice that `list_app_banner_and_schedule` contains an array, you have to loop over it to get all the times. – Barmar Feb 23 '22 at 18:36
  • Hi guys, thanks a lot for the answer, but I have no Idea how to loop over from my code, can you guys please help. – DIR Feb 23 '22 at 18:37

0 Answers0