0

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'}%>

2 Answers 2

1

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')
    });
});
0

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.