0

Using AJAX to read JSON and store in a JS array of objects

I have created a JSON file with sample data. I created a PHP file to read the JSON. The PHP was successfully able to read the JSON and the JSON data has no issues.

I have tried using AJAX to read the PHP file to display the jsonData but it is throwing an "Uncaught ReferenceError: $ is not defined" error.

<p id="test">Paragrah</p>

<script>

  $.ajax({
    url: "assetData.php", // make this url point to the data file
    dataType: "json"
  }).done(function (jsonData) {
    // Create our data table out of JSON data loaded from server.
    document.getElementById("test").innerHTML = jsonData;
  });
</script>

I expect to be able to see the word paragraph be replaced by the data in my JSON file.

Allloush
  • 1,140
  • 8
  • 27
Saachi
  • 33
  • 3

2 Answers2

0

$ is a shortcut for jQuery. In your case, the jquery is simply not included or not loaded yet. Make sure to include it in your HTML:

<script
 src="https://code.jquery.com/jquery-3.3.1.min.js"
 integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
 crossorigin="anonymous"></script>

Also make sure that this is included in your HTML before your code to run ajax.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
0

Try using the complete or success attribute (only one)

   $(document).ready(function() {
        $.ajax({
          url: "assetData.php", 
          dataType: "json"
          success/complete: (function (jsonData) {
            document.getElementById("test").innerHTML = jsonData;
          }
    });
Mbotet
  • 170
  • 2
  • 17