john Smith
john Smith

Reputation: 17926

Passing Parameters of AJAX POST to Grails Controller

I´m building a social network with Grails and got stucked on giving users inner their editprofile page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video

the html looks like :

                    <g:textField name="videoinput" class="videoinput reLef" value="" />
                    <span class="daten_videouploadbtn reLef" ></span>

        <g:render template="/forms/storedVideos" />

the JS looks like :

    $('.daten_videouploadbtn').click(function() {

        var string = document.editProfileForm.videoinput.value;
        var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1'); 
        var id = RegExp.$1;

        jQuery.ajax({
        type:'POST',
        data:RegExp.$1, 
        url:'${createLink(action: 'addVideo')}',
        success:function(data,textStatus){jQuery('#storedvideos').html(data);},
        error:function(XMLHttpRequest,textStatus,errorThrown){}
        });
});

the controller looks like :

def addVideo() {
    def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
    render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}

and stored videos looks :

    <div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>

i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,

can someone give a hint ? it is killing me

Upvotes: 5

Views: 11632

Answers (2)

raffian
raffian

Reputation: 32086

I got this working on Grails 2.0.4:

Javascript/Ajax

var data = 
   {requestId: 12456,
    node: "node1",
    host: "mynode.com"};


    $.ajax({            
      url: '/myurl',
      data: JSON.stringify(data),
      type: 'post',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      success: function() ...
      },
      error: function() ...
      }
});

In Grails....

def service(){   
  def jsonObj = request.JSON
}

I like this approach because request.JSON parses the data and returns a ready to use object.

Upvotes: 3

micha
micha

Reputation: 49612

You should post the data like this:

jQuery.ajax({
  type: 'POST',
  data: { value: RegExp.$1 },
  ...

After that you can access the posted data inside your grails controller with params.value.

Upvotes: 4

Related Questions