Luke Villanueva
Luke Villanueva

Reputation: 2070

Ajax call on ruby on rails

I have a ajax call using ruby on rails. I'm getting a success but I don't know how to use the data result of the ajax call.

$.ajax({
  url: "/search/get_listing?listing_id" + id,
  dataType: 'JSON',
  success: function(data) {
    var listing = JSON.parse(data);
    $("#modalPrice").html(data.city);
  }
});

Controller:

@listings_data = Listings.find_by(id: params[:id])

render :json => @listings_data.to_json

Using data.city won't work. I'm expecting to get the values retrieve from the model by simply putting . on the variable

var listing = JSON.parse(data);

Still no luck. Help guys. Thanks!

Upvotes: 0

Views: 2109

Answers (3)

Ignasi Vegas
Ignasi Vegas

Reputation: 17

For example, you can render in the controller:

render :json => { :city => @listings_data }

On the JS:

success: function(data) {
    var listing = data.city;
}

Upvotes: 1

Billy Chan
Billy Chan

Reputation: 24815

JSON.parse is Ruby code, API of JSON gem. How can you guys use that in Javascript :)

jQuery can process JSON object data directly. Just use:

  success: function(data) {
    $("#modalPrice").html(data.city);
  }

Upvotes: 1

KappaNossi
KappaNossi

Reputation: 2706

I'm having similar problems everytime I use AJAX in rails since the response seems to differ depending on how you return the value or how you are handling the success in JS. Try this:

success: function(data, status, xhr) {
             var listing = JSON.parse(xhr.responseText);
             $("#modalPrice").html(data.city);
         }

I usually use Firebug (Firefox Plugin) to set a breakpoint in my success handlers to check the arguments where exactly the response is in. Sometimes it's in the first value, sometimes in some other and then it may be xhr.response or even xhr.responseText. It's confusing me every time.

To use Firebug for this, press F12 on your page, select the 'Script' pane and find the code you want to check. Click next to the row number of your code where you want your breakpoint. In this case, you could've chosen the var listing line. When the code is executed (after your click), the browser will stop there and you can check the passed arguments on the right side.

Upvotes: 0

Related Questions