Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax request to controller

I'm new to Play and try some very simple things with AJAX. Right now I only want to send some data to my controller and send something back. I don't get how I can realize this in Play.

I used to send data with

$.get(url, {data:'input'), function() { do something });

to a standard servlet found at /url. In the servlet I have a simple

out.println("html output")

if I want to print something in my html file. I hope you get the point.

In Play I have a function in my controller (it's nonsense, just a test...)

public static void doIt(String input) {
    String out = input+"_foo";
    render(out);
}

I try to call this function with JQuery/AJAX like this:

$(document).ready(function() {
      // when I click a button ...
      $("#send").click(function(){
            var url = #{jsAction @doIt(':input') /}     
            $.get(url({input: 'x'}), function() {
                ...
            });
      });
});

This is taken from the tutorial and doesn't work. Can somebody give me an idea how to write the controller and the JS to send some random string to my controller and return something.

Cheers

like image 205
Martin Preusse Avatar asked Apr 19 '26 03:04

Martin Preusse


1 Answers

Try renderText() instead of render():

public static void doIt(String input) {
    String out = input + "_foo";
    renderText(out);
}

And try to explicitly define the controller you use if your view (where you write the script) does not belong to YourController:

$(document).ready(function() {
  // when I click a button ...
  $("#send").click(function(){
        var url = #{jsAction @YourController.doIt(':input') /}     
        $.get(url({input: 'x'}), function() {
            ...
        });
  });

});

It works for me. And important thing: This will only work at view file not separate js

like image 173
wassertim Avatar answered Apr 20 '26 16:04

wassertim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!