javascriptajaxgrailscontrollergsp

Send data from .gsp to controller


I need send data from text input in .gsp page to a controller using js or ajax. My code in gsp page is

 <input placeholder="<g:message code="form.search.label"/>" id="q" name="q" type="text" onkeypress=validar(event);>
 <button class="button"><span class="mif-search"></span></button>

The js function is:

 <script type="text/javascript">
function validar(event){
    var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    var message = $('#q').val();
    if (theCode == 13){           
        
        <g:remoteFunction controller="search" action="search" params="message" update="pageid"/>          
}
}

This code work fine is I wish to refresh my page, but I need to send the data in the input text to my controller. I surf in web but I can't resolve this problem. What I need to do for this?


Solution

  • I strongly recommend use jQuery.ajax(); instead of g:remoteFunction because at the end of the day. The g:remoteFuncion it would be rendered to jQuery.ajax();. For example, you have this:

    <g:remoteFunction controller="search" action="search" params="message" update="pageid"/>
    

    This will be:

    jQuery.ajax({type:'POST', url:'/YOURGRAILSAPPNAME/search/search',success:function(data,textStatus){jQuery('#pageid').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});
    

    You can test looking the HTML in your webpage.

    But if you really want to use the g:remoteFunction. You can use this

    var message = $('#q').val();
    if (theCode == 13)
        <g:remoteFunction controller="search" action="search" params="'message='+message" update="pageid"/>