this is my controller method
def purchase
if #item_point > current_user.points
flash.keep[:notice] = "You dont have enough points to buy this item"
else
flash.keep[:notice] = "You have successfully redeemed this items, Thanks for the purchase."
end
render :json => flash
p flash[:notice]
end
and in my javascript ajax function's success i have written
$(".purchaseBtm button").click(function() {
var button_id = this.id.split("-")[1];
$.ajax({
url: '/hhr/purchase',
data : {
button_id : button_id
},
success: function(response) {
console.log('message: <%= flash[:notice]%>');
$('.flash-msg').html('');
$('.flash-'+button_id).text('<%= flash[:notice]%>')
}
});
});
This ajax call goes on a button click which passes some values, with which #item_point is calculated.
Problem is in my terminal i'm getting the correct Flash message every time.
but in my Browser console sometimes i get the first flash message as correct and then the same flash message persists. I wont get the second flash message. But the terminal shows corectly(the p message.)
If this action is to only to render feedback message from server, then I would just render the hash containing the message, as there is no point to store it in special flash container.
if #item_point > current_user.points
message = "You dont have enough points to buy this item"
else
message = "You have successfully redeemed this items, Thanks for the purchase." }
end
render json: { notice: message }
Edit:
Then in your json use
success: function(response) {
console.log('message: ' + response.notice);
$('.flash-msg').html('');
$('.flash-'+button_id).text(response.notice)
}
Also remember to set type of ajax request to dataType: 'json'
Related
I had earlier been provided permission for the feature Manage_pages. However, Facebook has changed it policies and this feature has been depreciated, moreover, my application wasn't using much of the Facebook feature. For these 2 reasons, my app has been disabled.
SO, i submitted a review for the same. The feedback is as such:
The main purpose of my app is to take payments through the client's Facebook page , for which earlier used Manage_pages feature. Now, even if i hit the connect button, it says "The app is in dev mode" . Am stuck here, how can i get the button to work and display a screen cast if I keep getting the same error. this seems like an endless while loop :(
Now, when i am trying to re-submit an app review, it seems to be getting auto rejected.
Any insight would be appreciated!
Here is my Facebook controller code
class FacebookController < ApplicationController
skip_before_action :verify_authenticity_token
skip_before_action :authorize
def connect
# get array of facebook pages added
page_ids = params[:tabs_added].keys
# create or update connection for each facebook page added
page_ids.each do |page_id|
page = FacebookPage.where(page_id: page_id).first_or_initialize
page.update!(slug_id: params[:slug_id], form_type: params[:form_type])
end
head :created
end
def show
request = parse_signed_request(params[:signed_request]).try(:[], 'page')
facebook_page = FacebookPage.find_by(page_id: request.try(:[], 'id'))
facebook_admin = request.try(:[], 'admin')
if facebook_page
redirect_to contribution_form_url(
subdomain: facebook_page.account_type,
id: facebook_page.slug.name,
form_type: facebook_page.form_type,
iframe: true,
facebook: true,
facebook_admin: facebook_admin,
facebook_page: facebook_page
)
else
render nothing: true
end
end
def update
facebook_page = FacebookPage.find(params[:id])
slug = Slug.find_by!(name: page_params[:form_slug], account_type: facebook_page.account_type)
if facebook_page.update!(slug: slug, form_type: page_params[:form_type])
redirect_to contribution_form_url(
subdomain: facebook_page.account_type,
id: facebook_page.slug.name,
form_type: facebook_page.form_type,
iframe: true,
facebook: true,
facebook_admin: true,
facebook_page: facebook_page
)
end
end
private
def parse_signed_request(signed_request)
# We only care about the data after the '.'
payload = signed_request.split('.')[1]
# Facebook gives us a base64URL encoded string.
# Ruby only supports base64 out of the box, so we have to add padding to make it work
payload += '=' * (4 - payload.length.modulo(4))
decoded_json = Base64.decode64(payload)
JSON.parse(decoded_json)
end
def page_params
params.require(:facebook_page).permit(:form_type, :form_slug)
end
end
and i am also attaching the the script which opens the facebook tab
<script>
function move_to_top( value )
{
$(".fb_dialog").each(function(index) {
if($(this).css("top")!='-10000px') {
$(this).css("top", value + 'px' );
}
});
setTimeout( ('move_to_top("'+value+'");'), 1250);
}
window.addToFacebook = function() {
// make sure logged in as user; not page
FB.login(function(loginResponse) {
// if they are correctly logged in as user
if (loginResponse.authResponse) {
// popup modal to add form to page
FB.ui({
method: 'pagetab',
display: 'popup'
}, function(response) {
// if tabs were added, make the connection
if (Object.keys(response.tabs_added).length > 0) {
console.log("inside")
response.form_type = $('[name=form_type]:checked').val().slice(0,1);
response.slug_id = '<%= Slug.find_by(name: slug, account_type: candidate.account_type).try(:id) || candidate.account_slug.id %>';
$.post('/facebook/connect', response);
$.magnificPopup.open({
items: {
src: '<%=j render "form_settings/facebook_success" %>',
type: 'inline'
}
});
}
});
$(".fbProfileBrowserResult").ready( function(){
t = setTimeout ( ('move_to_top("'+50+'")'), 1250 );
});
}
});
};
</script>
<p><%= link_to 'Connect with Facebook', '#', onclick: 'addToFacebook()', class: 'button' %></p>
Users can subscribe to my Rails app through Stripe:
class Subscription::CreditCardController < Subscription::PaymentController
def new
stripe_customer = Customers::FindOrCreate.call(current_account)
if stripe_customer
#stripe_subscription = Subscriptions::Create.call(current_account, #price, :payment_behavior => "default_incomplete")
#client_secret = #stripe_subscription.latest_invoice.payment_intent.client_secret
else
flash[:notice] = "An error occurred."
redirect_to plans_path
end
end
def create
flash[:success] = "Subscription created."
redirect_to plans_path
end
end
I am relying on Stripe.js to catch any errors that may occur:
form.addEventListener('submit', function(e) {
e.preventDefault();
handlePayment();
});
function handlePayment() {
stripe.confirmCardPayment(clientSecret.value, {
payment_method: {
card: card,
billing_details: {
name: name.value,
email: email.value
}
}
}).then(function(result) {
if (result.error) {
displayError(result.error);
} else {
form.submit();
}
});
}
This works in 99 % of all test cases so far. Stripe.js catches pretty much every error that can possibly occur. But on some rare occasions it does NOT, so that the error occurs on the server when Stripe is trying to create the Subscription, leaving it in an incomplete state.
This is a major problem because I am not handling these type of errors in my create controller action right now.
So why is it that Stripe catches most of these errors but not all? As a developer, am I supposed to validate user input with Stripe.js AND on the server? Or will one of the two suffice? Reading through Stripe's documentation I was under the impression that Stripe.js will handle everything for me and that I won't have to add additional checks on the server level.
Is this not correct?
In my customer index view if I click on delete customer button, the following actions take place in my Customers controller delete method.
Customers_controller.rb
class CustomersController < ApplicationController
.
.
def destroy
if Customerarticle.where(author_id: params[:id]).count > 0
#####I need the logic here to display a modal window on my index page of customers here#####
else
Customer.find(params[:id]).destroy
flash[:success] = "Customer deleted"
# debugger
redirect_to customers_path
end
So based on my condition if it's true means customer can't be deleted, and that message to be displayed in a modal pop up window on Customers index page itself, how to achieve it ?
I suggest you issue an ajax request when the button was clicked and make it redirect to your destroy action. Then, within the controller do your logic and simply return a true/false (or whatever else you need) and use it in your JS callback.
For example:
In your view.js
$(document).ready(function(){
$("#delete_button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/URL/TO/CONTROLLER",
data: { id: someID},
success: function(result){
if(result == true) {
// Do something
} else {
window.location.replace(result);
}
}});
});
});
In your controller:
def destroy
if Customerarticle.where(author_id: params[:id]).count > 0
return true
else
Customer.find(params[:id]).destroy
flash[:success] = "Customer deleted"
return customers_path
end
end
This should work just fine. Remember, it definitely needs some re-work and adjustments :)
I am trying to update a model through JSON. Right now I am able to get the put method to execute.
From my browser console, I see this so I believed that my request did go through.
PUT http://localhost:3000/slot_allocations/1 [HTTP/1.1 200 OK 7ms]
However, I am not too sure how I could get Rails to accept the data I want to update and would appreciate it if someone could help me out.
This is my Jquery codes for Ajax request. dataToServer is the data I want to send to update the model.
var url = 'slot_allocations/'+alloc_id;
var dataToServer = {slot_allocation:{timeslot:timeslot, subject:subject,slot_allocation_id:alloc_id-1, group_id:"Group 2", lesson_type:"Tutorial"}}
$.ajax({
type: "PUT",
url: url,
dataType: "json",
data: JSON.stringify(dataToServer) , // message to send goes here
success: function (data)
{
}
});
In my update method in the controller I have the following codes.
def update
#slot_allocation = SlotAllocation.find(params[:id])
respond_to do |format|
if #slot_allocation.update_attributes(params[:slot_allocation])
format.html { redirect_to #slot_allocation, notice: 'Slot allocation was successfully updated.' }
format.json { render :json=>#slot_allocation.as_json }
else
format.html { render action: "edit" }
format.json { render json: #slot_allocation.errors, status: :unprocessable_entity }
format.js { render :js => #slot_allocation.errors, :status => :unprocessable_entity }
end
end
end
And this is my as_json method. I am using it for my send request from the server to the client side but I am not too sure if I could use the same method to send information from the client to the server side.
def as_json(options={})
{
:group_id =>self.group_index,
:lesson_type =>self.lesson_type,
:timeslot =>self.timeslot_id,
:subject =>self.subject_id,
:slot_allocation_id => self.slot_allocation_id
}
end
I would appreciate it if someone could guide me along as I am not too familiar with how I should get Rails to accept the parameters to update the model.
I believe you need to parse the JSON parameters first:
attributes = ActiveSupport::JSON.decode(params[:slot_allocation])
if #slot_allocation.update_attributes(attributes)
...
end
How do I parse JSON with Ruby on Rails?
None of the tutorials I seem do what I'm trying to do. Very simply, I want a user to be able to submit a POST request to a controller (to "LIKE" a video) and have the controller respond back with a JSON object. Any help would be appreciated.
Thanks
EDIT Because SO is messing the formatting up, here is a gist of my code too:
https://gist.github.com/813503
Here is my controller:
class LikesController < ApplicationController
before_filter :get_ids
respond_to :json, :js
def videolink
results = {}
# check to see if the user has liked this videolink before
if current_user
liked = Like.video?(current_user, #vid_id)
results["status"] = "OK"
results["liked"] = liked
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
def update
results = {}
if current_user
results["status"] = "OK"
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
private
def get_ids
#vid_id = params[:videolink_id]
end
end
Here is my JS file:
$("#likeVideo").click(function() {
$.ajax({
contentType: "application/json",
data: { game_id: game_id, videolink_id: current_video["videolink"]["id"] },
dataType: "json",
type: "POST",
url: "/likes/" + game_id,
success: function(data) {
console.log("Success", data);
}
});
return false;
});
My routes:
resources :likes do
collection do
get "videolink"
end
member do
post :update
end
end
And here is the error I get:
NoMethodError
in LikesController#update
undefined method `{"status":"OK"}_url' for #<LikesController:0x0000010178be58>
If you want to send back custom JSON, Instead of respond_with(results.to_json)... just render the text
render :text=>results.to_json
The responds_with is a way for you to easily send back objects, with their location (url). So that's why your error is telling you that that '_url' is invalid.
More info on responds_with, courtesy of http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering
If another format was requested, (i.e.
:xml or :json)
If it was a GET request, invoke the :to_format method on the resource and
send that back
If the resource has validation errors, send back the errors in the
requested format with the
:unprocessable_entity status code
If it was a POST request, invoke the :to_format method on the resource
and send that back with the :created
status and the :location of the new
created resource
Else, send back the :ok response with no body