The user selects one of the options and submits the form.
Then without submitting the form, I need to display data from json file.
I am storing ajax call in a global variable display_this
and calling that variable as a function after form is submitted.
When I select option and press submit I get this error:
TypeError: display_this is not a function
When I refresh the page, it displays the data.
My code:
<form id="form">
<select name="op" id="op">
<option value="A">A</option>
<option value="B">B</option>
</select>
<input value="Submit" type="submit" id="submit">
</form>
My JSON data:
[
{"key":"A","val":"apple"},
{"key":"A","val":"orange"},
{"key":"B","val":"carrot"},
{"key":"B","val":"onion"}
]
My jQuery code:
$(document).ready(function () {
var output;
var display_this = function () {
var val = $("#op").val();
$.ajax({
async: 'false',
type: 'post',
url: 'abc.php',
data: {
"val": val
},
dataType: 'json',
success: function (response) {
var data = JSON.stringify(response);
var resp = JSON.parse(data);
$.each(resp, function (i, item) {
if (val == "A" && resp[i].key == "A") {
output += resp[i].val + "</br>";
} else if (val == "B" && resp[i].key == "B") {
output += resp[i].val + "</br>";
}
});
return results.html(output);
}
});
}();
$('#form').submit(function (e) {
e.preventDefault();
display_this();
});
});