KrakenNeedsHelp KrakenNeedsHelp - 5 months ago 30
Javascript Question

jQuery AJAX - Returning and displaying multiple results


<!DOCTYPE html>
<script type="text/javascript" src="scripts.js"></script>
<h1>Order Request Form</h1>
<form id="create-form">
<td><input type="text" id="txtID"></td>
<td><button id="getid-button">GET Order by ID</button></td>
<td><input type="text" id="txtName"></td>
<td><button id="getname-button">GET Order by Name</button></td>
<div id="resultDiv"></div>


$(document).ready(function() {
var resultElement = $('resultDiv');
$('#getname-button').on('click',function(e) {
var searchName = $('#txtName').val();
$.ajax ({
url: 'https://localhost:8080',
contentType: 'application/json',
}).then(function(response) {
for (var i = 0; i < response.length, i++) {
if (response[i].names.indexOf(searchName) > -1) {
resultElement.html('ID: ' + response[i].id + '</br>
+ 'Name: ' + response[i].name + '</br>');

So what I want to do is that whenever I press the "GET Order by Name" button, I want to return and display ALL the results with the name in it. Right now though, it is simply going through my JSON array and printing out the latest result found. Any idea how I might go about solving my problem? Thanks in advance.


You are using .html() witch will override all previous results use .append() instead.

var resultElement = $('#resultDiv'); //use # for ids

resultElement.append('ID: ' + response[i].id + '</br>
                         + 'Name: ' + response[i].name + '</br>')
//use append or else you will only see 1 result