0

Play framework version is 2.2.6

jQuery

$('#fridgeSearchInputField').keyup(function () {

var $text = $(this).val();

    $.ajax({
        type: 'GET',
        url: '@routes.controllers.Application.ajaxAutocomplete()',
        data: $text,
        success: function (data) {
            // success result
        }

    });   
});

Routes file

GET     /:ingredientName            controllers.Application.ajaxAutocomplete(ingredientName: String)

Method in Application controller

public static Result ajaxAutocomplete(String ingredientName){
    String s = request().body().asText(); //I guess something here is wrong
    System.out.println(s); 
    return ok("");
}

The problem is that when I print s variable in play console it prints out null. What is wrong in my code? And how can I get the text from input field through the request in order to use it later? Thanks

Kyle Luke
  • 348
  • 5
  • 16
  • In your Javascript, your generating the URL `@routes.controllers.Application.ajaxAutocomplete()`, that is without any ingredientName. I haven't done any Play framework recently but shouldn't you provide an argument ? Moreover, have you tried debbuging and looking into `request().body()` what it looks like ? – Gaël J Jan 04 '16 at 15:20
  • @Gaël when I write request().toString() it returns what I want but like this `GET /@routes.controllers.Application.ajaxAutocomplete()?d GET /@routes.controllers.Application.ajaxAutocomplete()?di ` and so on – Kyle Luke Jan 04 '16 at 15:36
  • 1
    You're sending a get request; does it even *have* a body? Send a parameter like normal. Unrelated, but IMO `$` prefixes should be reserved for stuff that's actually jQuery-related, not text strings. – Dave Newton Jan 04 '16 at 16:19
  • 1
    As @DaveNewton said, `GET` requests don't have bodies. When you hand the data parameter to `jQuery.ajax`, it attaches it as a query string. Play, however, does not see the query string as body text. So what you're seeing is the expected output. – gpgekko Jan 05 '16 at 09:35
  • Have a look at this [post](http://stackoverflow.com/questions/11133059/play-2-x-how-to-make-an-ajax-request-with-a-common-button). – Sivakumar Jan 05 '16 at 10:39
  • Like gpgekko and Dave Newton suggested: Try exchanging your ajax type GET to POST and it should work. – Kris Jan 05 '16 at 13:33

1 Answers1

0

I found the solution!

so I changed my files a bit and everything worked just as want. Probably this is not the best algorithm but it works!

    final String request;
    String[] requestArray;
    try {

        request = request().toString();
        requestArray = request.split("\\?", 2);
        String userRequest = requestArray[1];
        System.out.println(userRequest);


        return ok();


    } catch (IndexOutOfBoundsException e) {
        e.printStackTrace(); 
    }


    return ok();
Kyle Luke
  • 348
  • 5
  • 16