Reazur Rahman Reazur Rahman - 4 months ago 23
JSON Question

JQuery autocomplete with java to use multiple JSON value

I am trying to use jQuery autocomplete with java server side. I have a form called contact info which has two field called first name and last name. When you click save on the contact info it saves the first and last name under sql column c_first_name and c_last_name. Currently the json is returning: [{"c_first_name":"Reur","c_last_name":"Raman"},{"c_first_name":"John","c_last_name":"Joon"}].
Here is my ajax function:

function caseIlete() {

jQuery(document).ready(function() {
jQuery(function() {
jQuery("#Cant, #Caseorney, #CaseInput_employer, #Caney").autocomplete({

// source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]

source : function (request, response) {
jQuery.ajax({
url : "page.request.do?page=page.ajax.autocomplete",
type : "GET",
data : {
term : request.term
},
dataType : "json",
success : function(data) {


data = data[0].c_first_name + " " + data[0].c_last_name;


var dataArray = [data];

response(dataArray);



}
});
}




});
});
});


Here is my java controller file:

public class Controller implements Pler {

public Response execute(Pagxt t) throws ApplicationException {

TextResponse tr = t.createTextResponse();

tr.setContentType("application/json");

try {


String term = t.getPeters().getSingle("term");
String sqlJson = t.ceSQL("Select c_first_name from t_coct").fetchJSON();
tr.put("aadata", sqlJson);


}catch (Exception e ) {

e.printStackTrace();
}


return tr;

}

}


Mind you that the Json list will grow as we enter more people in the contact form. Currently in order for it to work i am pointing the data to:

data = data[0].c_fiame + " " + data[0].c_le;


Which is the first record on the sql data base. I want to be able to auto populate both of the record that's available in sql like Reazur Rahman and John Johnson. Lots of example online did something like response(data) and that didn't work for me at all. I had to return response as dataArray. I also tried:

for (var i = 0; i < data.length; i++) {

data = data[i].c_firme + data[i].c_l_name //Also just returns Reazur Rahman

}

Answer

Inside your ajax success, this is what you need

var dataArray = [];
for(var k = 0; k < data.length; k++) {
    // Add items to array
    dataArray.push(data[k].c_first_name + " " + data[k].c_last_name);
}

response(dataArray);