简体   繁体   中英

how to access javascript variable in ruby on rails view

We have a javascript code in which url of selected image is obtained in javascript variable (src). We want to access src var in rails view to obtain the id of the selected image.Tried this by using Ajax where we tried passing the url to var created in controller but somehow the ajax call isn't working,therefore controller var always show nil value. we have tried ajax by 2 method:

1:

$('#submit').click(function(){
$.ajax({

    type: "POST",

    url: "index",

    cache: false,

    data: "src="+src1,

    success: function(){ 

           alert("DATA SAVED");

     }
});

2:

<%= link_to_remote "submit" , :url=>{:controller=>'album',:action =>'index' ,:var=>'src1'}%>

i would suggest you to modify your Ajax to something like this.

var MyTestData = '';
function ajax() {
    return $.ajax({
        url: 'index',
        type: 'POST',
        // make sure you use params[:src] in your controller method to access src1
        data: { src: src1 },
        // You should return your response in JSON format
        success: function(data){ MyTestData = data }
    });
}

So now the response which you get from your POST call will be saved in MyTestData variable.
Example on how to send json response from a controller method

def index
    # Use the data you passed in the Ajax call
    data = params[:src]
    # Do some processing
    result = something
    # Return the response in json
    render :json => result
end

Here is how you can use the ajax() function on submit event

$('#submit').click(function(){
    ajax().done(function() {
        // Your MyTestData variable will have whatever details your returned
        // on your POST call. you can test it by logging it in console
        console.log(MyTestData)
      }).fail(function(){
          alert('Ajax call Failed')
    });
});

Make sure your src1 variable is in scope. The easiest way—though not the best—would be to just make src global, defined right inside your script tag.

Of course global variables are frowned upon, for good reason, so once this works look at tidying up the code and getting src declared more locally, or at least namespaced.

Also, is the variable named src , or src1 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM