views:

50

answers:

1

I have a button on my Ruby on Rails view file.

Firstly when the button is clicked an ajax call is made which in response gives a json string. So far I have accomplished this task. I am stuck here:

The button also redirects me to another action of the same controller. Now I want to send the json string received by javascript as a parameter to that action.

Is there any way around.

Please help.

Thanks in advance.

+3  A: 

Your ajax call should look something like this:

... doing stuff before ...

$.ajax(
  url:'url-to-script',
  success: function(data) {
    var json = JSON.parse(data);
    $('#hidden-field').val(json); // set a hidden field in your form
    $('#from-id').submit();
  }
);

$('#submit-button').attr('disabled', 'true'); // disable the button
// set some spinny animation to notify the user that you are waiting.
// time out after a while if you don't get a response

... doing stuff after ...

Basically we fire off the ajax event, disable the button and notify the user you are waiting. When the call returns, your callback method submits the form to rails. You can also set a time out for the ajax call and let the user resubmit if necessary. You can handle the error case however you like.

shoebox639
Consider a scenario: You are a server 'A'. It gives a script to its client 'B' to run on B's site. B has a client 'C' which visits B's site and tries to access the script that you gave to B. So B will first authenticate C and provide the user credentials back to A in JSON format and then the rails part will be executed and C's data will saved on A's server. That is somewhat I am trying to do. Hope you have a clear idea now.
Rohit
Got it, posted editted. Is this close to what you're looking for?
shoebox639