1

I am learning Ajax and trying to get it work on my project. Basically i am trying to implement google like suggestion on the project.
i have a UI that sends ajax request to the server asynchronously and gets relevant suggestion

function showHint(str) {
    if (str.length == 0) { 
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
     console.log(str);
       
     var xmlhttp = new XMLHttpRequest();
      console.log(xmlhttp.readyState);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET", "/hint?word=" + str, true);
        xmlhttp.send();
    }
}
<label>Name <input id="peak" type="text" name="peak_name" onkeyup="showHint(this.value)">
       <p id="peak"></p>
      <p>Suggestions: <span id="txtHint"></span></p>

The Spring MVC controller is

@RequestMapping(value = { "/hint" }, method = RequestMethod.GET,params={"word"})
public @ResponseBody ArrayList<String>  hint(ModelMap model,@RequestParam String word) {
    System.out.println("Inside Hint");
    String[] hints = { "Ram", "Shyam" };

    ArrayList<String> returnhint = new ArrayList<String>();

    // lookup all hints from array if $q is different from ""
    if (word != null) {
        word = word.toLowerCase();
        int length = returnhint.size();
        for (int j = 0; j < length; j++) {
            if (word.contains(hints[j])) {

                returnhint.add(hints[j]);

            }
        }

    }
return returnhint;

}

I am new to Ajax. So is there a specific way xmlhttp object's responseText have to be handled?
My question is since i have passed ArrayList in the response body, how do get ajax to get that response and update the UI accordingly?

Sohil
  • 532
  • 7
  • 26
  • Check if this answer is acceptable for you http://stackoverflow.com/questions/5908466/jquery-spring-mvc-requestbody-and-json-making-it-work-together/5908632#5908632 – Davide Lorenzo MARINO Aug 23 '16 at 08:18
  • My question is since i have passed ArrayList in the response body, how do get ajax to get that response and update the UI accordingly? – Sohil Aug 23 '16 at 08:26

2 Answers2

0

To use @ResponseBody you need two things:

  • <mvc:annotation-driven /> in your context file
  • a library to handle JSon (like Faster Jackson) in your classpath

If you don't configure well the spring part you will have a 406 error because the header of the response is not correctly initialized and the response itself is not in the right format.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • I have those dependency in the pom.xml as well as the configuration file. Do i have to do something in other to construct the responsebody in a particular way such that xhttp.reponse gets the required response? – Sohil Aug 23 '16 at 08:50
  • @Sohil Try to make a curl request and see what it returns. – Davide Lorenzo MARINO Aug 23 '16 at 08:52
  • i just returned a simple hard coded string and the reponse worked just fine. Let me dig into the documentation some more and see if xmlhttprequest object can handle the arraylist as well. Thanks for the suggestion anyway – Sohil Aug 23 '16 at 08:58
  • 1
    Consider also using a library like JQuery to make Ajax calls because different browser handle it differently. Library like JQuery will handle this difference exposing a common interface that is not browser dependent – Davide Lorenzo MARINO Aug 23 '16 at 08:59
0

Going through the documentation, xmlhttprequest object has a set of properties to handle response

XMLHttpRequest.response Read only
Returns an ArrayBuffer, Blob, Document, JavaScript object, or a DOMString, depending on the value of XMLHttpRequest.responseType. that contains the response entity body.

So i basically returned a String instead of a ArrayList and concatenated all of the matched hints in the string using comma ',' separator

And in the javascript file. I simply made a list of the reponse with split(',') function.

function showHint(str) {
    if (str.length == 0) { 
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
     console.log(str);
       
     var xmlhttp = new XMLHttpRequest();
    
        xmlhttp.onreadystatechange = function() {
         
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var list=xmlhttp.responseText.split(',');
            console.log(list);
                document.getElementById("txtHint").innerHTML = list;
            }
        };
        xmlhttp.open("GET", "/hint?word=" + str, true);
        xmlhttp.send();
    }
}
<label>Name <input id="peak" type="text" name="peak_name" onkeyup="showHint(this.value)">
<p id="peak"></p>
<p>Suggestions: <span id="txtHint"></span></p>

Controller Method

    @RequestMapping(value = { "/hint" }, method = RequestMethod.GET,params={"word"})
public @ResponseBody String hint(ModelMap model,@RequestParam String word) {
    System.out.println("Inside Hint");
    String[] hints = { "Ram", "Ra","R","Shyam" };

    String returnedhints="";
    // lookup all hints from array if $q is different from ""
    if (word != null) {
        System.out.println("i am here");
        //word = word.toLowerCase();
        int length = hints.length;
        for (int j = 0; j < length; j++) {
            System.out.println(word+"contains"+hints[j]+"="+word.contains(hints[j]));
            if ((word.regionMatches(0, hints[j], 0, hints[j].length())) {
                returnedhints= returnedhints+","+hints[j];
            }
        }
    }

return returnedhints;

}

Hope this will be helpful to future ajax learner with spring mvc.

Sohil
  • 532
  • 7
  • 26