I'm attempting to send a JSON string from PhoneGap to my Ruby application. In PhoneGap, the following code is sending the JSON string:
var location = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
$.ajax({
type: "post",
dataType: 'json',
data: location,
url: 'http://localhost:3000/location/new'
});
In my Ruby app, I have a controller trying to process the response:
def addlocation
require 'json'
json_string = params[:data]
parsed_json = JSON.parse(json_string.to_json)
if parsed_json["app"] == "Inrix PhoneGap"
new_obj = Location.new
new_obj.lat = parsed_json["lat"].to_f
new_obj.lng = parsed_json["lng"].to_f
new_obj.save
end
end
I know I'm getting the data from PhoneGap, because the parameters show up in the server log. I tried converting the response to a string, and then to json, because it doesn't appear to be in the proper json format. I've also tried passing the JSON.parse function response.body and params[:data]. Here is the error I receive in the server log:
Started POST "/location/new" for 127.0.0.1 at 2013-07-23 01:14:37 -0700
Processing by LocationsController#addlocation as HTML
Parameters: {"lat"=>"37.785834", "lng"=>"-122.406417"}
Completed 500 Internal Server Error in 0ms
JSON::ParserError (757: unexpected token at 'null'):
app/controllers/locations_controller.rb:12:in `addlocation'
Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.9ms)
Rendered /usr/local/rvm/gems/ruby-1.9.3-p392/gems/actionpack-3.2.13/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (7.5ms)
Thanks in advance. Let me know if you need more information. Cheers!
data
in $.ajax
is not the name of the POST parameter. You need to give data: { data: location }
in order to have a parameter named data
(which would translate to POST data={"lat"=>"37.785834", "lng"=>"-122.406417"}
)
However, I would suggest you name it something like location
instead :P
$.ajax({
type: "post",
dataType: 'json',
data: { location: location },
url: 'http://localhost:3000/location/new'
});
and
location_json = params[:location]
just so you understand what you wrote six months from now :D
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.