Skip to content
Advertisement

Ajax JSON.parse JSONarray

I am trying populate a form from a mysqli database when an option is selected from a drop down. I am trying to do this with an ajax ‘get’ call to a PHP page. The PHP page does the SQL query and returns the results, then I do a json_encode of the data. This puts the JSON into an array. Then the ajax function attempts to parse the JSON. However this is where the problem lies. The JSON data comes in as an array and the JSON.parse(xhr.response) fails to parse.

[{"id":"12","accountnum":"2148","name":"Blah","address":"123 Dan Hwy","city":"ANY Town","state":"IA","zip":"11111","phonenumber":"555-555-5555","brand":"Dan","create_date":"2021-06-14 15:47:36"}]

//////////////////////////////////////////////////

<script>
  const selectElement = document.querySelector('.accountnum');
  selectElement.addEventListener('change', (event) =>{
    const result = document.querySelector('.result');
    var eventResponse = `${event.target.value}`;
    result.textContent = 'the account num is ' +eventResponse;
    loadAccounts(eventResponse);
  });
</script>

///////////////////////////////////////

  function loadAccounts(eventResponse){
    var xhr = new XMLHttpRequest();
    var url = "users.php";
    var geturl = xhr.open('GET', url+"?accountnum="+eventResponse, true);
    xhr.onreadystatechange = function(){
      if(xhr.readyState === XMLHttpRequest.DONE) {
        if(this.status == 200){
          console.log(xhr.response);
          var accounts = JSON.parse(xhr.response);
          console.log(accounts.id);
          console.log(accounts.name);
          var output = '';

        for(var i in accounts){
          output += '<div class="form-group">' +
            '<label for="accountname">AccountNum*</label>' +
            '<input type="text" class="form-control" id="accountnum" name="accountnum" value= '+accounts[i].accountnum+ '>' +
            '</div>'
          
        }
        document.getElementById('accounts').innerHTML = output;
      }
    }
    }
    xhr.send()
  }
</script>

////////////////////////////////////////////////

<?php
      
      $accountnum = $_GET['accountnum'];
      $query = "SELECT * FROM accounts WHERE accountnum = $accountnum";
      $result = mysqli_query($conn, $query);
      $accounts = mysqli_fetch_all($result, MYSQLI_ASSOC);
      echo json_encode($accounts);

   ?>

Advertisement

Answer

Your response is an array, not an object. Try reassigning the accounts variable like accounts = accounts[0];. Or make your php script extract the first element from the result set and json encode it loke echo $accounts[0] ?? null;

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement