I have rails controller:
class TrafficVolumeController < ApplicationController
def test
render json: Traffic.all
end
end
I can see it returns json:
On this AJAX request:
$.ajax '/traffic_volume/test',
type: 'GET'
dataType: 'json'
json: true
success: (data, textStatus, jqXHR) ->
$('body').append "Successful AJAX call: #{data}"
But data is of Anything type and in browser I can see:
So the question is how to work with this data parameter. Do I have to cast it to other type or I need to change HTTP headers in request or something in rails controller. Really need your help as I've spent so many time on this already. Thanks!
What you observe on the page, is the default string representation of object, which is not very helpful.
Try this one, should be much better:
console.log "Successful AJAX call: ", data
That data of yours, it's an array, right? If so, this should work as well
$('body').append(data[0].year) # or whatever you were going to do
# in the first place
Related
I have a problem, I want to send a json that I have to a URL and this is an action in my controller, I want to get this json in my js by means of an http get, the problem is that I do not understand very well how to do it.
All_events is a method in my helper that returns a json
The action of my controller with the data I want to send
def events_calendar
render json: {events: all_events}
end
In my routes.rb:
resources :tools do
collection do
get 'events_calendar' => 'tools#events_calendar'
end
end
My js:
$http({
method: 'GET',
url: "/admin/tools/events_calendar"
}).then(function (response) {
console.log(response);
}, function (response) {
});
When I execute this, this is the result:
Any suggestions on how to solve this error?
You need an AJAX call:
$.getJSON('/admin/tools/events_calendar', function(response) {
console.log(response)
});
Please, check the Working with JavaScript in Rails guide.
I'm working on a tournament bracket based on the GOjs library, The bracket has score input.
Once my user is done editing the bracket I save the bracket into a JSON variable :
function save() {
var tojs = myDiagram.model.toJSON();
var payload = JSON.parse(tojs);
stringify_tojs = JSON.stringify(payload);
myDiagram.isModified = false;
I use XMLHttpRequest to able to post the payload into my rails model that handles 'payload' :
var request = new XMLHttpRequest();
request.onload = callback;
request.open("post", "http://localhost:3000/malesingles");
request.setRequestHeader("Content-Type", "application/json");
request.send(payload);
I don't know where I went wrong but I'm certain it's around my
controller params but I can't find my mistake already been a week, the
controller looks something like this :
#tournoi = Tournoi.new(bracket_params)
if #tournoi.save
redirect_to root_url
flash[:success] = "Your tournament bracket has been validated!"
# redirect_to #tournoi
else
render 'new'
end
end
I have included the bracket_params in private settings
def bracket_params
params.require(:tournoi).permit(:payload)
end
Tried different method to post the payload none really work, would appreciate some help to understand where I went wrong, I get a param is missing or empty :/.
#DezzH check out my latest commits from my repo https://github.com/fabriziobertoglio1987/sprachspiel/tree/feature/purchase-system I just built something like that using coffescript.. the commits include description of my work
basically what I figured out is, post request do not pass the parameters in the url so it is not easy to find them in the request, but you can check in your network tab
as you can see from the image I am passing
createPurchase: ->
$.ajax
url: "/products"
method: "POST"
dataType: "json"
data: { items: {product_id: '1', name: 'test' }}
error: (jqXHR, textStatus, errorThrown) ->
console.log "AJAX Error: #{textStatus}"
success: (data, textStatus, jqXHR) ->
console.log "Successful AJAX call: #{data}"
console.log data
then I set just a binding.pry in the controller and I can see my params there
In my Rails app, stringified JSON form input is passed to a controller via AJAX - on success, the user is to be redirected to a summary page, but the AJAX redirect doesn't seem to be working...
$.ajax({
url: "report/submission",
type: "POST",
beforeSend: function(xhr) {xhr.setRequestHeader("X-CSRF-Token", $("meta[name='csrf-token']").attr("content"))},
data: {"report" : reportParameter},
success: function(response) {
window.location.href = "/report/summary";
}
});
and the associated controller
def submission
#incomingReport = ActiveSupport::JSON.decode(params[:report])
#newReportIDArray = Array.new
#incomingReport.each do |x|
hash = ActionController::Parameters.new(x)
#new_report = Report.new(report_params(hash))
#new_report.save
end
end
Everything else seems to work just fine - the data is entered, but the redirect does not trigger. I've searched all around and it looks like this is the syntax that everyone says to use, but it doesn't seem to work for me. I'm sure that I am doing something wrong, but I'm not sure what.
Editing to clarify problem/solution
During a chat with #Jonathan and #Kumar, I noted that window.open("/report/summary") did work correctly - #Jonathan suggested that I just try console.log(window.location) before the ajax call, and to my surprise, the script from a function from elsewhere in my app was logged. Big shocker now - THE FUNCTION WAS CALLED location()!!! Renaming the function and then restarting the app in a new window solved the problem. Learn from my mistake, kids - don't name a function location().
Ruby isn't my first language but it doesn't look like you're sending a response back. Try returning something or putsing. Look up how to do that with rails, a proper response. Maybe render json: [success: 200] or something like that. Maybe it's irrelevant. In any case, if it's not working try changing success for complete and log out the response to debug. The complete will always fire, but success won't always.
Try this:
respond_to do |format|
format.json do
render json: {
success: 200
}.to_json
end
end
In your AJAX setup, add "datatype": "json".
You could improve the response to conditionally send a failure like success: 500 if something went wrong.
You don't really need respond_to block here because you're always expecting JSON, but that's the kind of format that's often used in Rails if not mistaken.
If that doesn't work just use the render json: part as that is definitely a return.
Update
Further from our discussion it turns out that after making a robust Ajax call and tweaking the action, the final hurdle was a window.location that was not working. The cause of the problem was that location had been rebound to another function. All that needed to be done in the end is to rename that custom function and Bob's your uncle.
Add a datatype
$.ajax({
url: "report/submission",
type: "POST",
dataType: 'json', #Add json data type, as we'll render json from controller
beforeSend: function(xhr) {xhr.setRequestHeader("X-CSRF-Token", $("meta[name='csrf-token']").attr("content"))},
data: {"report" : reportParameter},
success: function(response) {
console.log("Response is ", response);
//When we get 200, this function should execute
window.location.href = "/report/summary";
},
error: function(error){
console.log("Error is ", error);
}
});
And in the controller
def submission
#incomingReport = ActiveSupport::JSON.decode(params[:report])
#newReportIDArray = Array.new
#incomingReport.each do |x|
hash = ActionController::Parameters.new(x)
#new_report = Report.new(report_params(hash))
#new_report.save
end
respond_to do |format|
format.json { head :ok } #This will return 200 status back to ajax call
end
end
I posted question recentry as same
how to use local or instance variable inruby codein coffeescript in haml templ
Getting helpful comment, I'm trying to pass param to controller in ajax but it always returns error callback I can't not find the reason.
Here is my code.
.html.haml
:coffee
$('input#field').change ->
$.ajax
url: '/posts/gaga'
type: "GET"
dataType: "json"
data: { code: $('input#field').val() }
error: (jqXHR, textStatus, errorThrown) ->
alert "error"
success: (data, textStatus, jqXHR) ->
alert "success"
routes.rb
get 'posts/gaga'
posts_controller.rb
def gaga
#model = Model.new
render nothing: true
end
Does anyone know what's wrong my code?
Thanks in advance.
I think your route is incorrect. It should be formatted like this at least:
get "posts/gaga", to: "posts#gaga"
However this might be more what you want if you already have a resources :posts in your routes.rb:
resource :posts do
collection do
get :gaga
end
end
Because then you can avoid repeating get "posts/..." if you plan on adding more custom actions.
I have a RESTful controller:
class Api::V1::DevicesController < ApplicationController
before_filter :require_user
respond_to :json
# PUT /api/v1/devices/1
def update
#device = Device.find(params[:id])
authorize! :update, #device
#device.update_attributes(params[:device])
respond_with #device
end
end
And some JS on the client side:
$("#click-me").on('click', function() {
$.ajax({
type: "PUT",
url: '/api/v1/devices/' + $(this).data('device-id'),
dataType: 'json',
accept: 'application/json',
data: {device: {user_id: null}, format: 'json'},
success: function () {
alert("Booya!");
}
})
});
When the AJAX gets fired, by default, jQuery sends a JS object as a URL encoded string.
And a Content-Type:application/x-www-form-urlencoded which is fine. And because I set dataType to 'json', it sets Accept:application/json, text/javascript, */*; q=0.01, which also seems fine.
However when Rails gets the request, it treats the post body as JSON, even tho content-type is URL Encoded. Is this a bug?
My solution so far is to cast the JS object as JSON (JSON.stringify({device: {user_id: null}, format: 'json'})) and just submit it.
But that doesn't feel very good, surely Rails should handle Content-Type and Accept separately. This app is in 3.0.17. Perhaps it's an issue with earlier versions?
UPDATE:
Turns out the 422 I was receiving was a validation failure, and Rack is smart enough to deal with varying Content-Type and Accept headers. Duh.
This is maybe due to the
dataType: 'json',
line, which informs the server that the content of your request is JSON.