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

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

Related

Variable returned by Symfony controller always undefined

Ok, so I have a text field in which I type a string and I have a button next to it.
<div class="sidebar-search">
<div class="input-group custom-search-form">
<<label for="riot-summoner-input">Search a Summoner</label><br>
<input type="text" id="riot-summoner-input" class="form-control" placeholder="Type summoner name..." style="margin-bottom: 20px">
<button type="button" id="valid-summoner">Search</button>
</div>
</div>
By Clicking on this button, the following script gets executed
let res = {{ summoner.summonerLevel }}
$(document).ready(function() {
// Get value on button click and pass it back to controller
$("#valid-summoner").click(function () {
const summoner_input = $("#riot-summoner-input").val();
console.log(summoner_input)
let url = `/coach/?summonerName=${summoner_input}`
history.replaceState(summoner_input, 'Coach Index', url);
console.log(url)
function loadXMLDoc()
{
document.getElementById("display-summonerLevel").innerHTML = `Summoner Level: <h2>${res}</h2>`
}
loadXMLDoc();
});
});
Now as far as I can understand this will change my page url to include the value inserted in the text field and will send it back to my controller without refreshing the page, which it does.
Now in my Controller I'm using that value to do some logic with it
/**
* #Route("/", name="app_coach_index", methods={"GET"})
*/
public function index(CoachRepository $coachRepository, riotApi $callRiot, Request $request): ?Response
{
$value = $request->request->get('summoner_input');
if($value != null){
$this->debug_to_console($value . "Hi");
return $this->render('coach/index.html.twig', [
'coaches' => $coachRepository->findAll(), 'summoner'=> $this->showSummoner("$value")
]);}
else{
$this->debug_to_console($value);
return $this->render('coach/index.html.twig', [
'coaches' => $coachRepository->findAll()
]);
}
}
Now it's interesting to note that I'm doing this in the index function.
Here's the function I'm calling within the index function which is actually the one that gets the value from the script
/**
* #Route("/?summonerName={summoner_input}", name="show_summoner", methods={"GET"})
*/
public function showSummoner($summoner_input)
{
$call = new ApiClient(ApiClient::REGION_EUW, 'API-KEY-HERE');
return $call->getSummonerApi()->getSummonerBySummonerName($summoner_input)->getResult();
}
Now that I'm seeing this I can see that the issue is I'm getting the value in the showSummoner() function but trying to use it in the index function. Which is why I'm not getting a value when I print it to console and the variable is undefined.
Honestly I can't think of any logic I can do to overcome this issue.
EDIT!!!!!!!
Okay, so I know where the problem is arising, the issue is when I'm calling showSummoner($value) within index function. I'm using $value = $request->query->get('summoner_input');
I thought I was getting that value in the index function when in fact I'm getting it in the showSummoner() function. You can tell by the annotations
For index I don't have a parameter in its url, whereas in showSummoner() I have a parameter in the annotations as such.
/**
* #Route("/?summonerName={summoner_input}", name="show_summoner", methods={"GET"})
*/
This is indeed the fact because I'm using that url in the script as such
let url = `/coach/?summonerName=${summoner_input}`
The reason for this is I can't use the parameter in the index url because then I would have to provide the parameter in all the other places I'm using index in even when I don't have a parameter meaning I didn't search for anything.
I hope this gives more clarification
You're trying to get a value from $_GET global, not $_POST.
You can replace :
$value = $request->request->get('summoner_input');
by:
$value = $request->query->get('summoner_input');
You are trying to access the GET parameter using the wrong name ('summoner_input').
$value = $request->request->get('summoner_input');
When you are setting it as summonerName here:
let url = `/coach/?summonerName=${summoner_input}`
You will also want to pass a default value to check for, as the second parameter.
Try this:
$value = $request->request->get('summonerName', false);
if(false !== $value){
/* the parameter is in the url */
}

Remove session params if dropdown value changed

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?

How to do update in listing for web by using firebase

I am creating admin panel in website and I am using firebase as a database in backend.I am able to display listing but when I click on the particular listing there status should change from 'pending' to 'accept' but it doesnt.I dont know where I did mistake.Please give suggestion and I attach js file and database screenshot
pl.js
var firebaseheadingRef = firebase.database().ref().child("user");
firebaseheadingRef.on('child_added',datasnapshot=>{
var title= datasnapshot.child("listing").child("title").val();
var userid= datasnapshot.child("username").val();
var type= datasnapshot.child("listing").child("title").val();
var publisheddate= datasnapshot.child("listing").child("publish").val();
var expirydate= datasnapshot.child("listing").child("expire").val();
$("#tablebody").append("<tr><td>"+title+"</td><td>"+userid+"</td><td>"+type+"</td><td>"+publisheddate+"</td><td><button type=button id=accept onclick=accept()>Accept</button><button type=button>Reject</button></td></tr>");
});
function accept()
{
firebaseheadingRef.on('child_changed',datasnapshot=>{
datasnapshot.child("listing").child("status").update({"status":"accept"});
setCommentValues(postElement, data.key, data.val().text, data.val().author);
});
}
database
listing display picture where I click on accept button then update of status should done
There are two places where you need to change your code:
First, in the code that generates the table, you have to pass the id of the node to the function call, as follows. You get the node id with the key property of the DataSnapshot.
.....
$("#tablebody").append("<tr><td>"+title+"</td><td>"+userid+"</td><td>"+type+"</td><td>"+publisheddate+"</td><td><button type=button id=accept onclick=accept('" + datasnapshot.key + "')>Accept</button><button type=button>Reject</button></td></tr>");
...
And secondly you have to write your accept() function in such a way it updates the database value, with the set() method. Like the following
function accept(userId) {
var nodeRef = firebase.database().ref("/user/" + userId + "/listing/status");
return nodeRef.set('accept');
}

Old cookies vanish when add new cookies angularjs

I'm try add cookies . It's work well but when I refresh page and add new cookies , old cookies disappear , and cookies.length not update . It update after i refresh page . Here is my code
vm.cart = [];
vm.add = function(tensp,gia,img){
vm.cart.push({tensp:tensp,gia:gia,img:img,sl:1})
$cookies.putObject('cart',vm.cart);
}
And display in html .
vm.cookies = $cookies.getObject('cart');
{{vm.cookies.length}}
Where is my wrong . Please help me . Here is my plnkr
https://plnkr.co/edit/StURuPuEBr8ykIUPdvBV?p=preview
Whenever you refresh the page. vm.cart will be set to []. And when you click "Add", one item will be added to vm.cart. vm.cart now contains one item. When vm.cart is put into cookies, all existing items in cookies will be overwritten.
If you want to keep all items in cookies, put items directly to cookies and retrieve items directly from cookies as follows
var item = {
id: id,
masp: masp,
tensp: tensp
};
var cart = $cookies.getObject('cart');
if (cart) {
var items = JSON.parse(cart);
items.push(item);
$cookies.putObject('cart', JSON.stringify(items));
} else {
$cookies.putObject('cart', JSON.stringify([ item ]));
}
Here's a demo.

Javascript push Object to cookies using JSON

Hi All on click button I need to add object to array and then write array to cookies.
From the start this array can be not empty so I parse cookie first.
function addToBasket(){
var basket = $.parseJSON($.cookie("basket"))
if (basket.length==0||!basket){
var basket=[];
basket.push(
{ 'number' : this.getAttribute('number'),
'type' : this.getAttribute('product') }
);
}
else{
basket.push(
{ 'number' : this.getAttribute('number'),
'type' : this.getAttribute('product') }
);
}
$.cookie("basket", JSON.stringify(basket));
}
And HTML
<button type="button" class="btn btn-success btn-lg" number="12" product="accs" onclick="addToBasket()">Add</button>
Unfortunately I'm getting Uncaught ReferenceError: addToBasket is not defined onclick.
Can't understand what am I doing wrong?
Thanks!
I simplified your code a good deal, heres a fiddle: http://jsfiddle.net/yJ6gp/
I wired the click event using jQuery and simplified some of your code (see comments). Note I changed your html a little so I could select the add basket button by class - change as desired.
$(function () {//doc ready
$.cookie.json = true; //Turn on automatic storage of JSON objects passed as the cookie value. Assumes JSON.stringify and JSON.parse:
$('.add-basket').click(function() {
var basket = $.cookie("basket") || []; //if not defined use an empty array
var $this = $(this);
basket.push({
'number': $this.attr('number'),
'type': $this.attr('product')
});
console.log(basket);
$.cookie("basket", basket);
});
});

Categories