rubyist
rubyist

Reputation: 3132

passing ruby parameters as query string in Jquery ajax

I am using jquery draggable and droppable functions. SO when an element is dropped an ajax call would be initiated passing parameters as query string. I know how to pass query string. But i need to do some conditional checking in query string parameters. I am not sure how it can be done. Please find my code below.

jQuery('#<%= qtr %>').droppable({
    hoverclass: 'e_high',
    accept: function(elm) {
        if (jQuery(this).hasClass('<%=name%>_edit'))
            return true;
        },
        drop: function() {
            jQuery.ajax({
                type: "POST",
                url: '/sections/reorder?site_id=<%[email protected]%>&page=<%=@page%>?<%[email protected]%>:nil&ref_id=<%=section.id%>&name=<%=name%>'

Is the above method of passing query string correct. I am getting a No method error. Nil object. When i checked the terminal the params are Parameters: {"page"=>"", "site_id"=>"11650ecf55668fed9e7a624c93adcba2"}

Upvotes: 0

Views: 1540

Answers (1)

mu is too short
mu is too short

Reputation: 434975

For one thing, your ternary question mark and colon are in the wrong place, they should be inside the ERB delimiters. You'd be better off use the data option for $.ajax here; this will not only be cleaner but it will keep you from using GET parameters in a POST request. And you should be escaping your values for using in JavaScript with escape_javascript. Try it like this:

jQuery.ajax({
    type: "POST",
    url: '/sections/reorder',
    data: {
        site_id: '<%= j(@site.id) %>',
        page: '<%= j(@page ? @page.id : '') %>',
        ref_id: '%<= j(section.id) %>',
        name: '%<= j(name) %>'
    },
    //...

This assumes of course that section and name are available in ERB as Ruby variables rather than client-side JavaScript variables.

And if for some reason you must use a GET query string with a POST request, then you'd want something like this:

url: '/sections/reorder?site_id=<%= j(@site.id) %>&page=<%= j(@page ? @page.id : '') %>&ref_id=<%= j(section.id) %>&name=<%= j(name) %>'

Upvotes: 1

Related Questions