3

I am able to get my url response in the console tag in google chrome. I need your help in displaying those values in my interface. The provided below code only enables me to display the first value in the url response.

main.js:

 try{
         var getNameOfEmployee = document.getElementById('getNameOfEmployeeID');

       function displayEmployee(){

            if (getNameOfEmployee.value != "") {
                 $("#someform").submit(function (event) {
                 event.preventDefault();
                 });
                 AjaxGet();
            }
            else{
                alert("Please enter any name of employee that you wish to know the extension code of!");
            }
       }

       AjaxGet = function (url, storageLocation, mySuccessCallback) {
             var result = $.ajax({
                 type: "GET",
                 url: 'http://localhost:8080/employee/' +$("#getNameOfEmployeeID").val(),
                 param: '{}',
                 contentType: "application/json",
                 dataType: "json",
                 success: function (data) {
                        storageLocation = data;
                        globalVariable = data;
                       console.log(storageLocation);
                       console.log(storageLocation.empName0.extCode);

                      var length = Object.keys(storageLocation).length;

                    var empArray = new Array(length);                   
                 }
             }).responseText ;
             return result;
             return  storageLocation;
             //console.log(result);
       } ; }

 catch(e){          document.getElementById("demo").innerHTML = e.message; }

My console is as:

empName0
:
{empName: "Aran", extCode: 5500}
empName1
:
{empName: "Bran", extCode: 5900}
empName2
:
{empName: "Cran", extCode: 5750}

Please somebody help me how to get all these results get printed in my index page once the submit button is clicked. Just now I tried JSON.stringify(storageLocation) and print the results on an alert message. Please provide me an answer to display the results which are now duplicated. If you need my java file which retrieves the data, it follows:

employeeDAO.java :

@Repository public class EmployeeDAO { private static final Map empMap = new HashMap();

static {
    initEmps();
}

private static void initEmps() {

}

public JSONObject getEmployee(String empName){
    Map<String ,Employee> empMap2 = new HashMap<String ,Employee>();
    String filePath="D:\dummy.xls";
    ReadExcelFileAndStore details = new ReadExcelFileAndStore();

    List<Employee> myList= details.getTheFileAsObject(filePath);
    JSONObject emp1 = new JSONObject();
    boolean check=false;

    int j=0;
    for (int i=0; i<myList.size(); i++) {
        if (myList.get(i).getEmpName().toLowerCase().contains(empName.toLowerCase()))

{ emp1.put("empName"+j,myList.get(i)); j++; check = true; }

    }

    if(check == true)
    {
        //System.out.println("yes");
        return emp1;
    }
    else
    {
        return null;
    }
}

public Employee addEmployee(Employee emp) {
    empMap.put(emp.getEmpName(), emp);
    return emp;
}

public Employee updateEmployee(Employee emp) {
    empMap.put(emp.getEmpName(), emp);
    return emp;
}

public void deleteEmployee(String empName) {
    empMap.remove(empName);
}

public List<Employee> getAllEmployees() {
    String filePath="D:/dummy.xls";
    ReadExcelFileAndStore details = new ReadExcelFileAndStore();
    return  details.getTheFileAsObject(filePath);
}

public List<Employee> getAllImportantEmployees() {
    String filePath="D:/dummy.xls";
    ReadImportantExtensionSheet impDetails = new ReadImportantExtensionSheet();
    return  impDetails.getTheFileAsObject(filePath);
} }
Parkavi
  • 137
  • 1
  • 2
  • 16
  • 1
    user document.write – Harsh Patel Jan 02 '18 at 05:57
  • shouldn't the AjaxGet() call be inside the submit handler? Strongly suggest you also read [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – charlietfl Jan 02 '18 at 05:58
  • I do not understand why are you not calling element.innerHTML = response in success handler – Akshay Vijay Jain Jan 02 '18 at 06:07

2 Answers2

0

You could add some DOM manipulation inside you AJAX success method:

success: function (data) {
    storageLocation = data;
    console.log(storageLocation.empName0.extCode);
    $("#someform #someLabel").val(storageLocation.empName0.extCode);
    $("#someform #someOtherLabel").val(storageLocation.empName0.empName);
}

This will wait for the AJAX to complete and then update your page with the results.

You can use a jQuery each function to loop over each element in the results and update their corresponding elements on the page.

success: function (data) {
    storageLocation = data;
    $.each(storageLocation, function (index, value) {
        console.log(value.extCode);
        $("#someform #someLabel" + index).val(value.extCode);
        $("#someform #someOtherLabel" + index).val(value.empName);
    });
}
fjoe
  • 1,160
  • 6
  • 15
  • No it won't. Ajax is asynchronous. Can't return what hasn't been received yet. It's like trying to eat a pizza before it gets delivered – charlietfl Jan 02 '18 at 06:00
  • @fjoe The problem that I have is I am able to display the results one by one by having console.log(storageLocation.empName0.empName). But I need that empName0 to be looped over the length of storageLocation so that I can have empName1, empName1 and so on – Parkavi Jan 02 '18 at 06:15
  • @charlietfl I modified the answer should work with Asynchronous JavaScript. – fjoe Jan 02 '18 at 06:16
  • @TEchLearn I have already added a jQuery each loop to the answer which should solve that issue. – fjoe Jan 02 '18 at 06:17
  • @fjoe That worked! But it only displays the empName. Can you please tell me how to display the extCode along with empName. – Parkavi Jan 02 '18 at 06:38
  • @TEchLearn Updated answer as requested. – fjoe Jan 02 '18 at 07:06
  • @fjoe. that was a silly question I asked. Really sorry. Can you provide me a solution for the duplicate values in my url response. I get all the values doubled. – Parkavi Jan 02 '18 at 08:00
0
  1. Have a table in your html
  2. Upon receiving the response populate in UI

This is a sample code, change as per the json structure

  function load() {
   var resp = '[{"empName":"Aran","extCode":5500},{"empName":"Bran","extCode":5900},{"empName":"Cran","extCode":5750}]';

   var emps = JSON.parse( resp );
   var i;
   for(i=0; i<emps.length; i++) {
    $('#empdata').append('<tr><td>'+emps[i]['empName']+'</td><td>'+emps[i]['extCode']+'</td>...</tr>');
   }
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
 <table id="empdata" style="border: 1px solid;background-color: #eedaff;">
  <th>Name</th><th>Ext</th>
 </table>
 <button onclick="load();">Load</button>
</body>
SoSen
  • 101
  • 7
  • As per your answer the variable resp is assigned manually. But in my case it is the result according to the request from the user. – Parkavi Jan 02 '18 at 07:42
  • This is just a sample answer, in your case it will be **var resp = data;** And JSON parsing and iteration will be as per the json structure you have. Can you paste the JSON you have? – SoSen Jan 02 '18 at 11:22