Matheus Leão
Matheus Leão

Reputation: 437

Read JSON file on HTML form submit

I have an array of objects in a JSON file. I'd like to input an ID and have N elements populated by one of the N properties of the corresponding object, in order.

(example.json)

{
  "objects": [
    {
      "key1": "obj1 val1",
      "key2": "obj1 val2"
    },
    {
      "key1": "obj2 val1",
      "key2": "obj2 val2"
    }
  ]
}

I first set the ID and worked on populating the dynamic elements:

(populate.js)

$(document).ready(function () {
  var id = 1;
  $.getJSON('example.json', function(example) {
    let data = Object.values(example.objects[id]);
    let elements = document.querySelectorAll('.dynamic-elements');
    elements.forEach((e, i) => {
      e.innerHTML = data[i];
    });
  });
});

(HTML)

<!DOCTYPE html>
<html>
<script src='https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js'></script>

<body>
  <div class='dynamic-element'></div>
  <div class='dynamic-element'></div>
  <script src='populate.js'></script>
</body>

This would write "obj2 val1" on the first element and "obj2 val2" on the second, which is what I want. The problem comes when I tried to do the same thing on form submit. I add a form to .html:

<form>
  <input type='text' name='ID'>
  <input type='submit' value='Submit'>
</form>

And change the first line of populate.js to:

$('form').submit(function () {

I expected the page to be filled by objects[1] whenever I click "Submit", but nothing happens. If I replace the whole script with a simple console.log("debug"), nothing gets printed either. The funny thing is, if I also add alert("debug"), then both the console message and the alert will work. Also, it only seems to work if I place the script call below the form.

I'm a complete newbie to html/javascript. Can someone explain why these happen, and also help me obtain the desired behavior?

Edit: Full code of changed populate.js:

//$(document).ready(function () {
$('form').submit(function () {
    // This section runs, but not without the alert
    console.log("debug");
    alert("debug");

    // This section no longer seems to run
    var id = 1;
    $.getJSON('member-db.json', function(db) {
        let data = Object.values(db.members[id]);
        let elements = document.querySelectorAll('.db-info');
        elements.forEach((e, i) => {
                e.innerHTML = data[i+1];
        });
    });
});

Upvotes: 0

Views: 613

Answers (1)

Ryan Nghiem
Ryan Nghiem

Reputation: 2448

Because when u submit form, this page redirect with method POST. if u want console.log("debug"), u must add e.preventDefault();

$('form').submit(function (e) {
     e.preventDefault();
     console.log("debug");
     ...
});

Upvotes: 2

Related Questions