Tabledata not refreshed with `on_refresh` callback in `on_load` callback - rubymotion

My tableview won't reload data , it only shows noob but not redreshed data.
Do I missing any steps in my code ?
class ReservoirsScreen < PM::TableScreen
title "I want to refresh"
refreshable
def on_load
#returned_data ||= [{title:'noob'}]
on_refresh
end
def table_data
[{
cells: #returned_data.map do |reservoir|
{
title: reservoir["title"],
action: :select_reservoir,
arguments: { reservoir: reservoir["title"] }
}
end
}]
end
def select_reservoir(reservoir)
PM.logger.info reservoir
end
def on_refresh
start_refreshing
get_reserviors
stop_refreshing
update_table_data
end
def get_reserviors
start_refreshing
url_string = "http://128.199.223.114:10080/"
AFMotion::JSON.get(url_string) do |result|
if result.success?
#returned_data = []
result.object["data"].each do |r|
#returned_data << {
title: [r["reservoirName"], r["immediatePercentage"]].join(":")
}
end
else
#returned_data = ['failed','d']
end
end
stop_refreshing
update_table_data
end
end

AFMotion uses async callbacks, so your code is actually being executed like this:
start refreshing
send a request for the JSON
immediately stop refreshing
update the table data
receive the response with the JSON
Instead, move your stop_refreshing and update_table_data lines into your callbacks (the if result.success? / else blocks), that way they won't be executed until your JSON response is received:
if result.success?
#returned_data = []
result.object["data"].each do |r|
#returned_data << {
title: [r["reservoirName"], r["immediatePercentage"]].join(":")
}
end
update_table_data
stop_refreshing
else
#returned_data = ['failed','d']
update_table_data
stop_refreshing
end

Related

Why is flask jsonify returning unidentified?

I am using fetch on the frontend to send data to my flask backend in order to make a movie seat booking. The whole process works fine until the client awaits the response, which is "undefined" . So , basically the database saves the data , the only problem is the response which is sent to the client. I used jsonify which usually works fine. Can anybody tell me what I am missing? Thanks in advance.
Here is the JS code :
function sendReservationToServer() {
const selectedSeats = sessionStorage.getItem('selectedSeats')
const reservation = { userId, selectedSeats, showTimeId, movieHallId }
fetch('/bookSeats', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(reservation)
}).then(response => {
response.json()
}).then(data => {
theatreHall.innerHTML = `${data} <br> <a href='/home'>Back to main menu</a>`
console.log(`${data}`)
}).catch(err => infoMsg.textContent = err)
sessionStorage.clear()
}
And this is the flask controller which handles the request:
#app.route("/bookSeats", methods=["POST"])
def book_seats():
selected_seats = request.json
user_id = selected_seats.get('userId')
seats = json.loads(selected_seats.get('selectedSeats'))
movie_hall_id = selected_seats.get('movieHallId')
seat_ids = []
showtime_id = selected_seats.get('showTimeId')
for seat in seats:
seat_ids.append(db.session.query(Seat).filter(
Seat.seat_number == seat).filter(Seat.movie_hall_id == movie_hall_id).all()[0].stid)
for seat in seat_ids:
reserved_seat = ReservedSeat(
seat_id=seat, show_time=showtime_id, user=user_id)
db.session.add(reserved_seat)
db.session.commit()
reservation = Reservation(
user=user_id, show_time=showtime_id, number_of_tickets=len(seat_ids))
db.session.add(reservation)
db.session.commit()
message = f'{seats} booked successfully'
return jsonify(message)
data is undefined because the first then does not return anything. Either make it return response.json() or move everything in the second then to the first and replace data with response.json().

Avoid Multiple submits in Django

I am using auto submit in my forms.
Form gets automatically submitted when 10 digits are entered in the number field. This actually comes from USB RFID card reader upon scannig the card (It works as keyboard emulator).
I compare the number with the existing numbers in the database and then identify the user and perform some database transactions.
What happens is that the card reader reads the number multiple times, and due to that before all the database transactions complete for that input, another input is accepted (same number) within 1s and the consistency is lost before the first transaction is fully completed.
Kindly advise.
VIEWS.PY File:
#login_required
def markattdview(request):
# for val in studmst.objects.filter(ccownerid=request.user.id)
# TO DOooo
# select studid from attddetail where studentID= (select student ID from studmst where ccownerid = currentuser.ID)
# lastattd=attddetail.objects.filter()
# Showing last 10 users whose attendance have been marked by the logged in user
#
form_attd = markattdform()
attdsuccess = ""
identified_user = ""
identified_studname=""
loggedin_userid=request.user.id
loggedinuser=request.user.username
print("Logged in User : " + loggedinuser)
if request.method == 'POST':
studmstobj = studentmaster()
attdform = markattdform(request.POST)
unknown_cardno = request.POST.get('cardno')
if attdform.is_valid():
# form_attd.punchtime = datetime.datetime.now()
# attdform.save(commit=True)
obj = attdform.save(commit=False)
obj.punchtime = datetime.datetime.now()
attdsuccess = "Card not assigned. Kindly verify if the card has been registered."
#studlist = studmst.objects.filter(ccownerid = request.user.id)
#print (studlist[0])
# for usr in studlist(cardnumber = obj.cardno):
# Identifying the user who swyped the card
for usr in studentmaster.objects.filter(cardnumber = obj.cardno):
#WORKING FINE AFTER REMOVING WORKER AND REDISTOGO
#saving the details for identified User
identified_studname= usr.studentname
identified_cardno=usr.cardnumber
identified_studid = usr.studentid
punchdatetime=obj.punchtime
obj.studentname=identified_studname
obj.studentid_id=identified_studid
print('User Identified for card number '+ identified_cardno)
print( "Identified user - " + identified_studname)
databasetransactions(identified_studid,identified_studname,punchdatetime)
JAVASCRIPT FOR AUTO FORM SUBMISSION:
$(function () {
console.log(thetext);
$('#thetext').bind('change keyup', function () {
if ($(this).val().length >= 10) {
$('#Form').submit();
}
})
});
I would add two variables: formSubmitted and previousInput. And every time the length of the text is > 10, I would check if the form was submitted and also if previous input is equal to the current input.
When you submit the form - you set the value of formSubmitted to true.
And in this case your form will be submitted if it wasn't submitted already, or if the previous input is different than the current one which means that another text was entered and it should also be submitted.
And finally on ajax success or error you set the formSubmited to false back to allow new form submitions.
Remember that your form will be also submited if the current input is different than the previous input!
$(function () {
var formSubmitted = false;
var previousInput = null;
$('#thetext').bind('change keyup', function () {
if ($(this).val().length >= 10 && (!formSubmitted || previousInput != $(this).val())) {
var formData = new FormData($('#Form')[0]);
previousInput = $(this).val();
formSubmitted = true;
$.ajax(
url: '/endpoint.php',
method: 'POST',
processData: false,
contentType: false,
data: formData,
success: function(data, status, xhr) {
formSubmitted = false;
},
error: function(data, status, xhr) {
formSubmitted = false;
}
});
}
})
});

Datatable error in console: Uncaught TypeError: Cannot set property 'data of null

My datatable appears to be fully functioning - the filtering and sorting of all my columns work, but I still get this error in my console: Uncaught TypeError: Cannot set property 'data' of null(…)
Here are the most important parts:
notifications_datatable.rb
class NotificationsDatatable
delegate :params, :h, :link_to, :content_tag, to: :#view
def initialize(view)
#view = view
end
def as_json(options = {})
{
draw: params[:draw].to_i,
recordsTotal: total_records,
recordsFiltered: notifications.total_entries,
data: data
}
end
index.html.slim
table#notifications.dataTable.table.table-hover.table-nomargin.dataTable-tools.table-bordered.dataTable-custom.display data-source="<%= notifications_url(format: 'json') %>"
thead
tr
th style="width: 94px;"
= t('.client_id')
th = t('.request_type')
th = t('.applicant_name')
th = t('.organisation')
th = t('.sent_at')
th data-orderable="false"
= t('.actions')
tbody
javascript:
$('#notifications').dataTable({
responsive: true,
PagingType: "full_numbers",
processing: true,
serverSide: true,
ajax: $('#notifications').data('data')
});
If I expand the TypeError in my console I see this javascript and the ajaxData part has a red curly line underneath.
else
{
// Object to extend the base settings
oSettings.jqXHR = $.ajax( $.extend( baseAjax, ajax ) );
// Restore for next time around
ajax.data = ajaxData;
Has anyone seen this before?
Try changing this line:
ajax: $('#notifications').data('data')
to:
ajax: $('#notifications').data('source')
Change:
ajax: $('#notifications').data('data')
To:
ajax: {
url: $('#notifications').data('source')
}
Just change this line in jquery.dataTables.js:
// Restore for next time around
ajax.data = ajaxData;
To:
if (ajax && ajaxData) {
// Restore for next time around
ajax.data = ajaxData;
}

Rails4 strange behavior in test

In my test I want multiple users to be created and the last one logged in.
So here is my code:
test "add_answer to ad" do
user = newuser
text = "mytext mytext mytext mytext mytext mytext mytext"
post :savenew, cityId: City.last.id, text: text , maxPrice: "1", subscribe: false
$stdout.puts "#{assigns(:current_user)} CURUSER"
#ad = assigns(:ad)
user = newuser(0, 'new2#new.com')
post :add_answer, id: #ad.id, text: text
$stdout.puts "#{assigns(:current_user)} CURFIRM"
assert_equal "Ответ успешно добавлен.", flash[:success]
user.destroy
end
How I create new users:
def newuser(rank = 2, email = 'new#new.com')
user = User.new
user.password = '123456'
user.newpassword = true
user.email = email
user.contact = 'new_user'
case rank
when 0
user.urank = URank.firm.id
when 1
user.urank = URank.admin.id
when 2
user.urank = URank.user.id
end
user.save
$stdout.puts "#{user} NEW"
this_controller = #controller
#controller = MainController.new
get :logout
post :login, email: email, pass: '123456'
#controller = this_controller
return user
end
And my logout:
if cookies[:id]
Rails.cache.delete(cookies.signed[:id][0])
cookies.delete(:id)
end
#current_user = nil
(There is no cache it Test)
So as a result when I create new users I can see this:
As you can see the first user is just another user and second == first. What is happening there and how can I fix this?
Thank you!
I don't know why, but the problem was
#current_user ||= User.auth_with_salt(*cookiesId)
In test just do
#current_user = User.auth_with_salt(*cookiesId)

How can access session variable from controller to model in Ruby on Rails

I used session variable were session[:parent] on controller and I want to these variable pass to model. How do pass a params from controller to model?
Here my controller.rb file
def new
#child = Child.new
#child.pickup_people.build
#classes = [['Infant', 0], ['Toddlers', 1], ['Early learners', 2], ['Pre school', 3], ['Pre kindergarten', 4]]
#parent_types = [['Father', 'father'], ['Mother', 'mother'], ['Other', 'other']]
#martial_status = [['Married', 'married'], ['Single', 'single'], ['Divorced', 'divorced'], ['Separated', 'separated'], ['Widowed', 'widowed'], ['Other', 'other']]
#parent = Parent.new
#parents those will be mapped with child, here mentioned to show in form page after creation
if session[:parent_id] != nil
#parent_sessions = Parent.where(:id => session[:parent_id])
end
end
def create
logger.debug "\033[31mI am here\033[31m"
#child = Child.new(child_params)
if current_user.has_role? :day_care
#child.day_care_id = current_user.day_care.id
elsif current_user.has_role? :director
#child.day_care_id = current_user.director.day_care.id
elsif current_user.has_role? :assistant_director
#child.day_care_id = current_user.assistant_director.day_care.id
elsif current_user.has_role? :teacher
#child.day_care_id = current_user.teacher.day_care.id
end
respond_to do |format|
if #child.save
# logger.debug "\033[31m#{session[:parent_id]}\033[31m"
if session[:parent] != nil
session[:parent].each do |p|
Relative.create(:child_id => #child.id, :parent_id => p["id"].to_i, :parent_type => p["type"])
end
end
####
gflash :success => "Child was succesfully created."
format.html { redirect_to #child }
format.json { render :show, status: :created, location: #child }
session[:parent] = nil
session[:parent_id] = nil
logger.debug "\033[31mdestroyed#{session[:parent_id]}\033[31m"
else
gflash :error => "Unable to create, please try again."
format.html { render :new }
format.json { render json: #child.errors, status: :unprocessable_entity }
end
end
end
Thanks for your help!
Models are an interface to the database. They can be used without a session (e.g. from IRB). It would be a violation of MVC to allow the models to talk to the session. So the session object is not visible in models. Either pass it as a parameter to a method in your model or define a method in your model which returns what you want and then store it in the session (from your controller).
For e.g.
class User < ActiveRecord::Base
def item_status
return :no_such_item
end
end
In your controller
session[:item_status] = current_user.item_status
I hope it makes you clear...