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
Related
I have the following home controller:
class HomeController < ApplicationController
def index
#data = EmergencyFriend.all
#jsonData = JSON.pretty_generate(#data.as_json)
end
def about
end
def alertEmergencyContant
account_sid = "my id"
auth_token = "my token"
#client = Twilio::REST::Client.new(account_sid, auth_token)
#client.messages.create(
to: "+number 1",
from: "+number 2",
body: "hello world !"
)
end
end
Basically, in my home/index.html.erb there is only one button. When the button is pressed it shows an alert message that allows user to select an option to send an SMS to.
What I want to do is to call the alertEmergencyContant method in my home controller so that I can send the message. I also want to pass the phone_number as a parameter with that request. It has been suggested that for this I should use AJAX. I successfully installed jquery and ajax in my rails project and works as expected. What I can't understand is how to create it as a POST request.
My routes list for the home directory are :
root GET / home#index
root GET /home/about(.:format) home#about
But there is nothing on alertEmergencyContant. How to declare that in the routes and make it as a POST request? How to pass attributes from JavaScript to ruby using AJAX?
Here is my ajax request so far (This works):
$.ajax({
url: '/',
type: 'GET',
success: function(event){
alert("sending Message");
}
});
UPDATE:
def about
#thisNumber = params[:phone_number]
puts "helllloooooooooooooo " + #thisNumber
end
function ajaxRequest(){
$.ajax({
url: 'home/about/?phone_number:1244211',
type: 'GET',
success: function(event){
alert("passed");
},
failed: function(){
alert("has failed")
},
done: function(){
alert("after")
}
});
}
You need to add a route to your action
# routes.rb
post 'some_url' => 'home#alert_emergency_contact'
You can now use this in your javascript
$.ajax({
url: '/some_url', // This needs to match what you choose in routes.rb
type: 'POST',
success: function(event){
alert("sending Message");
}
});
PS: Action names are always_snake_case in Ruby, not camelCase
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 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
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 ArtistProduct model. User enters the product details, user can view the entered details in modal window by clicking the preview link before saving the details.
I'm trying to save the data using AJAX by passing all the details like params when it is validated, but it not saving the database.
In view I'm calling AJAX:
var theVal=id+'/'+artist_id+'/'+name+'/'+desc+'/'+price+'/'+story+'/'+artist_name+'/'+dimension+'/'+material+'/'+contact
var theURL = '/add_temp/' + theVal;
$.ajax({
url: theURL
});
In controller I'm handling it like so:
def add_temp
#pro_id=ArtistProduct.where("id=?",params[:id])
if #pro_id.nil?
#artistprod = ArtistProduct.new(:artist_id=>58, :product_name=>params[:name], :description=>params[:desc], :product_price=>params[:price], :product_story=>params[:story],:artist_name=>params[:artist_name], :dimensions=>params[:dimension],:material=>params[:material],:contact_number=>params[:contact])
#artistprod.save
end
end
UPDATE
Thanks for your reply.
Now am getting Routing error.
In my Router I have like:
match 'add_temp/:id/:artist_id/:name/:desc/:price/:story/:artist_name/:dimension/:material/:contact'=> 'artist_products#add_temp'
UPDATE
Routing Error404 Not Found
No route matches [POST] "/add_temp/P58018/58/Prod/swsx/50/sfdf/null/null/0"
UPDATE
Ya i identified it and corrected it but still also values are not saving into the database. Please help me
In Controller i am doing like so:
def add_temp
if !(ArtistProduct.where("id=?",params[:id]).exists?)
#artistprod=ArtistProduct.new(:id=>params[:id],:artist_id=>58, :product_name=>params[:name], :description=>params[:desc], :product_price=>params[:price], :product_story=>params[:story],:artist_name=>params[:artist_name], :dimensions=>params[:dimension],:material=>params[:material],:contact_number=>params[:contact])
#artistprod.save
respond_to do |format|
format.html { redirect_to #artistprod.addproduct }
format.js
end
end
end
Hi dbkooper, Thanks for your answer. I tried answer given by u but am getting Routing error
In view am calling like:
var theURL = '/artist_products/'+id+'/add_temp?artist_id='+artist_id+'product_name='+name+'description='+desc+'product_price='+price+'product_story='+story+'artist_name='+artist_name+'dimensions='+dimension+'material='+material+'contact_number='+contact;
The big problem I see is that your $.ajax call is missing some options. By default, $.ajax defaults to a GET request if no type is specified.
You should change it to:
$.ajax({
type: 'POST',
url: theURL,
success: function (json) {
// handle your success here
},
error: function (response) {
// handle your errors here
}
});
This way, you specify that it will be a POST request and you also have callback methods for handling success and error
I think your routes should be
resources artist_products do
member do
post 'add_temp'
end
end
use rake :routes to get the correct routes
most probab it will be "artist_products/:id/add_temp"
For ajax request it will be you can send the val param's using ? to the url
like
var theURL = '/artist_products/'+id+'/add_temp?artist_id='+artist_id+'so on..';
$.ajax({ url: theURL });
Inside your controller
you can access params as usual