Search code examples
ajaxfunctiongrailssubmitgsp

Call remoteForm to update only one div with onChange event


I want to update div contents upon entering data in a textField dynamically. I have tried the following:

<g:formRemote name="changeText" on404="alert('not found!')" update="resultDiv"
    url="[ controller: 'results', action:'results' ]">
        <g:textField onChange="submit();" name="text"/>
</g:formRemote>

Everything work except a new page is render and the div is not updated...

def results = {
   render "new content"
}

Solution

  • The following GSP code:

    <g:formRemote name="changeText" on404="alert('not found!')" update="resultDiv"
              url="[ controller: 'results', action:'results' ]">
    

    Will generate a new HTML form with an onSubmit method like that:

    <form id="form_id" action="/action" method="post" onsubmit="jQuery.ajax({type:'POST',data:jQuery(this).serialize(), url:'/action',success:function(data,textStatus){jQuery('#resultDiv').html(data);},error:function(XMLHttpRequest,textStatus,errorThrown){}});return false">
    

    So the Javascript code that will trigger the AJAX call is on the onSubmit() method.

    The problem here is that you are calling submit() action using Javascript and this doesn't trigger the onSubmit() method.

    A solution would be to call the onSubmit() method directly in the onChange event:

    <g:textField onChange="this.form_id.onsubmit();" name="text"/>