Furqan Asghar
Furqan Asghar

Reputation: 3870

rails json format

i'm trying to render a json string in response to a request like following:

def check_progress
  if request.xhr?
    render :json=>"{'bytes_expected': #{session[:size]}, 'bytes_recieved': #{session[:size]}, 'last_seq': 0}".to_json
  end
end

but in my js code :

$.getScript('contacts/check_progress', function(data){
    console.log(data.bytes_recieved)
    console.log(data.bytes_expected)
    d.renderProgress(data);
});

I get undefined in response to data.bytes_recieved and data.bytes_expected.

what's wrong in my rails code?

Upvotes: 0

Views: 1549

Answers (3)

rubyprince
rubyprince

Reputation: 17803

You can simplify your code to:

def check_progress
  if request.xhr?
    render :json => {'bytes_expected' => session[:size], 
                     'bytes_recieved' => session[:size], 
                     'last_seq' => 0}
  end
end

as render :json will do the conversion of hash into JSON object for you. I dont know if this will solve the problem.

Upvotes: 0

KARASZI István
KARASZI István

Reputation: 31477

The $.getScript method of jQuery inserts a <script> node to the <head> of your HTML document.

With that method your browser won't send the X-Requested-With HTTP header to the server. Because it will be a simple HTTP request not an AJAX one. And your browser is waiting a javascript in the response not a JSON data.

In the jQuery documentation of the $.getScript method is somewhat misleading because it says data in the callback function of the method signature, but it won't give you any data in the callback function, because your browser simply executes the javascript there is no actual payload with this request.

There is to possible solutions:

  • If you need to load data from cross-domain, then try to remove the request.xhr? condition an use JSONP method and callback
  • if it's not a cross-domain situation, simply load with a $.getJSON response and don't touch the condition

Update: and I have not seen it but @Barlow pointed it out you need to fix your json generation code in your rails app as he says.

Upvotes: 0

David Barlow
David Barlow

Reputation: 4974

I Think your main problem might be that your returning a string which looks like json and is not actually a json hash.

in your render statement you are hand formatting the json as a string... which is fine until you call to_json on it.

to_json is suspose to be passed a hash not a string.

You could try removing the .to_json at the end of your render statement:

render :json=>"{'bytes_expected': #{session[:size]}, 'bytes_recieved': #{session[:size]}, 'last_seq': 0}"

or create a ruby hash then convert it to json:

@ruby_hash = {
  :bytes_expected => session[:size],
  :bytes_recieved => session[:size],
  :last_seq => 0
}

render :json=> @ruby_hash.to_json

Upvotes: 2

Related Questions