0

Using Rails 4 and native Javascript (vanilla).

I have the following Ajax call, which returns the place object:

// place.js
function addPlace(place) {
  console.log(JSON.stringify(place));
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "<%= Rails.application.routes.url_helpers.places_path %>", true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  xhr.setRequestHeader("X-CSRF-Token", CSRF.token());
  xhr.send("place=" + JSON.stringify(place));
}

In the console.log(JSON.stringify(place)), I get the following JSON:

{"name":"San Francisco","url":"https://maps.google.com/?q=San+Francisco,+CA,+USA&ftid=0x80859a6d00690021:0x4a501367f076adff","utc_offset":-480,"vicinity":"San Francisco","html_attributions":[]}

This params is sent to a Rails controller:

# places_controller.rb
class PlacesController < ApplicationController
  def create
    abort params[:place].inspect
    @place = Place.find_or_create_by(source_id: params[:source_id])
    @place.save
    head :ok
  end
end

In the line abort params[:place].inspect, instead of showing the whole load, it only shows:

"{"name":"San Francisco","url":"https://maps.google.com/?q=San+Francisco,+CA,+USA"

The url gets stripped off because of the & in &ftid=0x80859a6d00690021:0x4a501367f076adff.

Questions

How should I properly pass a Javascript object (preferably Hash) to Rails controller so that I can properly save it in the DB?

1 Answer 1

1

Try:

encodeURIComponent(JSON.stringify(place))
Sign up to request clarification or add additional context in comments.

Comments

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.