Remove session params if dropdown value changed - javascript

Is it possible to delete session[:sth] using jQuery/Javascript ?
In the Rails controller I set the session parameters:
def new
#other logic (...)
session[:patient_id_to_add_caregiver] = params[:patient_to_caregiver]
end
Below I've got simple function to handle case when the user selects one field from dropdown list, search field and search results should be hidden:
registrants.js
function toggle_caregiver_fields_on_ready(){
var caregiverSectionElement = $("#registrant_registration_attributes_registrant_id");
if ($("#registrant_registration_attributes_registered_as").val() === 'caregiver') {
$('.patient-caregiver-section').removeClass('hidden');
$('#patient-search-results').removeClass('hidden');
} else {
$('.patient-caregiver-section').addClass('hidden');
$('#patient-search-results').addClass('hidden');
}
}
In the same JS function I want to clear session[:patient_id_to_add_caregiver] when (#registrant_registration_attributes_registered_as").val() === 'caregiver'). I've tried with sessionStorage.clear(); to be:
if ($("#registrant_registration_attributes_registered_as").val() === 'caregiver') {
sessionStorage.clear();
$('.patient-caregiver-section').removeClass('hidden');
(...)
But nothing happened. Is it possible to clear this session storage?

Related

How to redirect to new route when click on anchor tag using JS?

I have an anchor tag in an `EJs file-
<a href="/posts/" tile>Read More</a>
And a route in app.js file-
app.get('/posts/:userId', function (request6, response6) {
var resquestedTitle = _.lowerCase(request6.params.userId);
// For each postObject(elements)inside posts array we check the if condition
posts.forEach(function (elements) {
// Inside {} we have access to individual postObjects inside posts array
// From the compose
var storedTitle = _.lowerCase(elements.tile);
// Checking for each postObject whether if storedTitle matches the requested title
if (resquestedTitle === storedTitle) {
// When the requestedTitle matches the storedTitle(tile of postObject), only then we render the post page
// Rendering post.ejs using respose6.render method, post is the name of page we want to render
response6.render('post', {
// Inside {} we pass in JavaScript objects with key value pair
// actualPosts and elements.tile are key value pair
actualPosts: elements.tile,
postContent: elements.bodytext,
id: request6.params.userId,
});
} else {
console.log('Match Not Found' + resquestedTitle);
}
});
});
Here is the anchor tag on which click I want to redirect to some route i.e /posts/anything.
Read More

Deleting a row from a table and passing a Boolean flag to API, without deleting the actual object

I'm doing a spa with AngularJS and consuming an api with mvvm in C #.
I can delete a line after clicking the delete button, but on the server I want only to change a boolean flag to true by keeping the data in Sql Server.
I've tried other ways, and I was even deleting the object through Postman, but I do not want to delete but only change a Boolean property to the record that no longer exists in my view table.
I'll leave my code so it can be better understood.
Any help is welcome.
I have tried to pass the id and the object in api controller, similar to http.put, because I want to change a Boolean property, so I wanted to keep the id, name, last name, email and isdelete that after the click, changes to delete the line in the view becomes true in the database.
<tbody>
<tr ng-repeat="register in registers">
<td style="display:none">{{register.UserId}}</td>
<td>{{register.Name}}</td>
<td>{{register.LastName}}</td>
<td><input type="checkbox" ng-model="register.IsActive" disabled /></td>
<td>{{register.Email}}</td>
<td>
<a ng-click="editRegister($event, register)" class="glyphicon glyphicon-edit"></a>
</td>
<td>
</td>
</tr>
</tbody>
My controller.js:
$scope.deleteRegister = function (register) {
var index = -1;
var listOfRegister = eval($scope.registers);
for (var i = 0; i < listOfRegister.length; i++) {
if (listOfRegister[i].register === register) {
index = i;
break;
}
}
if (index === -1) {
alert("Something gone wrong");
}
$scope.registers.splice(index, 1);
$http({
method: 'Delete',
url: 'http://localhost:51734/api/UserAPI/',
}).then(function (res) {
alert('Exc');
$scope.GetAllRegisters();
})
};
And My controller.api:
[HttpPut]
[Route("api/UserAPI")]
public HttpResponseMessage Delete(UserViewModel uservm)
{
try
{
var registerDeleted = ctx.User.Find(uservm.UserId);
uservm.IsDelete = false;
uservm.IsActive = true;
if (registerDeleted != null)
{
uservm.IsActive = false;
uservm.IsDelete = true;
registerDeleted.Name = uservm.Name;
registerDeleted.LastName = uservm.LastName;
registerDeleted.IsActive = uservm.IsActive;
registerDeleted.Email = uservm.Email;
registerDeleted.IsDelete = uservm.IsDelete;
ctx.Entry(registerDeleted).State = System.Data.Entity.EntityState.Modified;
ctx.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "User not found");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
Thanks!
what you are talking about is soft deleting rows of data.
in the database add a new boolean field called Status or IsDeleted or whatever you fancy, with a default value of false.
When you hit the Delete button on the UI, issue a request to simply update that flag from false to true
When you request the list of things to show on the UI, oly return those where the flag is set to false.
This is basically the whole idea behind soft deleting data. You only mark the data is deleted, you don't actually delete it.
If you want, later on you can add a process where you move the soft deleted data to an archived table, just to keep things tidy. Doing things this way has the added benefit that you can always undelete the data, should you need to. All you need really is to change the flag back to false and you're done, everything works and the data gets displayed.
One final point from me, if you all you want to do is soft delete an item, then all you need is to pass the id of the record. you don't need to worry about changes to other fields. You wouldn't normally update information AND delete it at the same time. So create a simple controller which responds to PUT, for example:
[HttpPut]
[Route("api/UserAPI")]
public HttpResponseMessage Delete(int userId)
{
var foundUser = ctx.User.Find(userId);
foundUser.IsDeleted = true;
ctx.SaveChanges();
}
of course, add all your validation, return codes, everything you need, but this is essentially all you need.
Don't forget to change the method which returns the active users, to ignore those where the IsDeleted flag is true.
If the API is the issue you are setting uservm.IsDelete = false; then setting registerDeleted.IsDelete = uservm.IsDelete; therefore it would always be false in the database.
If the template is the issue i would recommend getting the index from the data-ng-repeat, this would reduce the amount of code you have written and make it easier to see what is going on.
This will remove the row from the table:
<tr data-ng-repeat="(index, register) in registers">
<td>
</td>
</tr>
$scope.deleteRegister = function (index) {
$scope.registers.splice(index, 1);
}
Update from comment:
You need to retrieve the object then make the change, and save it.
var registerDeleted = ctx.User.Find(uservm.UserId);
if (registerDeleted != null)
{
registerDeleted.IsDelete = true;
registerDeleted.IsActive = false
ctx.SaveChanges();
}
Now I already know how to delete a record from my View.index, which is with splice in my controller.js
$scope.deleteRegister = function (index) {
$scope.registers.splice(index, 1);
$http({
method: 'PUT',
url: 'http://localhost:51734/api/UserAPI/',
}).then(function (res) {
alert('Exc');
$scope.GetAllRegisters();
})
};
But I can not get it to communicate with my method in my controller.api, I want to change only the flag isDelete = true, after clicking the delete button on my UI.
My controller.api
//DELETE: api/UserAPI/5
[HttpPut]
[Route("api/UserAPI")]
public HttpResponseMessage Delete(int userId)
{
try
{
var foundUser = ctx.User.Find(userId);
if (foundUser != null)
{
foundUser.IsDelete = true;
ctx.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
And my view.index
<tr ng-repeat="(index, register) in registers">
<td>
</td>
</tr>

Save the current user value to use it in HTML

[EDIT] i'm using Meteor
Hi everyone,
i've searched and tried many things but i can't do what i want.
I'm doing a tutorial to do a ToDo list, and when u check a task, i want to put the name of the user who checked the task.
<template name="task">
<li class="{{#if checked}}checked{{/if}}">{{#if checked}}<!-- the name of the user who checked it -->{{/if}}
<!-- the rest isn't useful for my question -->
I've tried with {{currentUser.username}} but when i log with someone else the name change...
There is the JS for the event handler
'click .toggle-checked'() {
// Set the checked property to the opposite of its current value
Meteor.call('tasks.setChecked', this._id, !this.checked);
}
And the JS for the method call
'tasks.setChecked'(taskId, setChecked) {
check(taskId, String);
check(setChecked, Boolean);
Tasks.update(taskId, { $set: { checked: setChecked } });
}
Thank you for the help
If you use {{currentUser.username}} you will always have the data of the logged in user.
To get what you want you need to register the _id of the user who checked the task in your method:
'tasks.setChecked'(taskId, setChecked) {
check(taskId, String);
check(setChecked, Boolean);
// Check that 'setChecked' is true and that the user is logged in,
// Otherwise just update the status
if (setChecked && this.userId) {
Tasks.update(taskId, {
$set: {
checked: setChecked,
userId: this.userId,
}
});
} else {
Tasks.update(taskId, {
$set: {
checked: setChecked,
}
});
}
}
Make sure you update your schema accordingly if you are using one.
Then in your template, retrieve the user data and display it:
// file task.js
import './task.html';
Template.task.helpers({
checkerUser() {
// The template data are those of the current task, check if userId is defined and task is checked
const { userId, checked } = Template.currentData();
/* Or you can do
* const userId = Template.currentData().userId;
* checked = Template.currentData().checked;
*/
if (userId && checked) {
return Meteor.users.findOne({ _id: userId }).profile.username;
}
return null;
}
});
Template.task.events({
'click .toggle-checked'() {
// Set the checked property to the opposite of its current value
Meteor.call('tasks.setChecked', this._id, !this.checked);
}
})
And finally in HTML:
// file task.html
<template name="task">
<li class="{{#if checked}}checked{{/if}}">
{{#if checkerUser}}Completed by {{checkerUser}}{{/if}}
</li>
</template>
Technically, in your method you should also check more in-dept the different situations. For instance, when you uncheck a task, it should remove the userId from the record so that if a non logged-in user checks it again, the name won't be the one of the first user (or you could $unset userId if user is not logged in when setting checked = true)

Meteor easy search and iron-router

I'm using this easy serach for my project https://github.com/matteodem/meteor-easy-search
my search Index
EasySearch.createSearchIndex('searchIndex', {
'collection' : blog,
'field' : ['title', 'tags'],
'limit' : 20,
"use":"mongo-db",
'query' : function (searchString) {
// Default query that will be used for searching
var query = EasySearch.getSearcher(this.use).defaultQuery(this, searchString);
return query;
}
});
and now I have search box and when User enters something and click on enter I want to route to search page
this.route("search",{
path:'/search/:slug',
waitOn:function(){
//here I want the search data to be sent to search page
var query=this.params.slug;
EasySearch.search('searchIndex', query, function (err, data) {
console.log(data);
});
},
data:function(){
}
});
In this router I want the searchIndex data to be sent to search page, how to do this
my click event
'submit .search':function(e){
e.preventDefault();
var quer=$("#query").val();
// Router.go('search');
}
UPDATE
My main question is in the router waiton function how we get the data in callback and send it to the search page?
In your click event handler, you have commented out the line: Router.go('search').
If you write
Router.go('search', {slug: quer})
That would route you to the search page with the query data collected from the page, if that is what you want.

How to remove the item in session using javascript for codeigniter?

I am working on a shopping cart php(codeigniter) project. So I have add the item in the session like the code following. The problem is, I would like to remove the item in session in the checkout page.
But of course I can not call the php function to remove the session in javascript , that means , when the remove button is click , how can I do (not restrict to use ajax, simple is the best), I can remove the item in session ? Thanks
if ($this->form_validation->run()) {
if ($this->session->userdata('purchase') !== false)
$purchase_list = $this->session->userdata('purchase');
else
$purchase_list = array();
$purchase = array(
'id' => $product[0]['id'],
'quantity' => $this->input->post('quantity')
);
if ($this->input->post('opt1') !== false)
$purchase['opt1'] = $this->input->post('opt1');
if ($this->input->post('opt2') !== false)
$purchase['opt2'] = $this->input->post('opt2');
array_push($purchase_list, $purchase);
$this->session->set_userdata('purchase', $purchase_list);
redirect('cart');
}
You can define a function in your controller to unset the session e.g.
class Controllername extends CI_Controller {
function index(){}
function reset_session(){
$sesion_variable = 'name_of_session';
$this->session->unset_userdata($session_variable);
}
}
And you can call that via CURL or ajax. On checkout page
from CodeIgniter's session class documentation
This assumes you understand your cart and will know where to actually unset session data in your checkout scenery.
you can set the value of desired item in your session using this syntax:
$this->session->set_userdata('purchase', null); // will set the purchase session data to null
you only know which key to set to null though

Categories