I am making a page that loads a JSON file when a form is submitted. The form calls a javascript function on submit, search(this)
, which loads the JSON file and does some other stuff. To test things out, I used the example for $.getJSON()
from the jQuery documentation.
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
When I use this code outside a function in my javascript file, it works, but if I put it inside my search
function, it doesn't do anything.
What is going on?
MCVE
Enter a string in the text field and push the search button. This will call the search
function. A breakpoint in the search function will show that it gets called, but the new elements are not added to the page.
demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Demo </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="LoadDemo.js"></script>
</head>
<body>
<h1> Demo </h1>
<form onsubmit="return search(this);">
<input type="text" name="query" id="query"> <input type="submit" value="Search">
</form>
<br>
<div id="results">
</div>
</body>
</html>
LoadDemo.js
function search(form){
//Clear any existing elements from results
//$('#results').empty();
//Retrieve new results
queryStr = $("#query").val();
//If I put a breakpoint after this line, I can see the query string printed on the console
console.log(queryStr);
//This doesn't work
$.getJSON( "test.json", function( data ) {
console.log("success");
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
//This works
/*
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
}); /**/
Test.json
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}