Javascript push Object to cookies using JSON - javascript

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);
});
});

Related

HTML Button filtering based on two conditions

I have a button that is named "atCloudBttn", when you click it, it filters my data by status by all data that is pending.
How could I make this button also filter by another condition. The other condition would be IO by yes so, ('IO', 'Yes')?
<button role="button" name="atCloudBttn" class="btn btn-primary" (click)="changeFilter('Status', 'Pending')">
The change filter functions code is written in Typescript and I have included it below. I'm not 100% sure if I have to edit this code as well to reflect the change in structure.
ChangeFilter(field: string, term: string) {
this.filteredtable = true;
var filter = {};
filter[field] = term;
var title = ' ';
var activeColDef = this.columnDefs;
Why don't you write these two condition in a js function
and use click="functionname()" or add .addEventListener("click",functionname());

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 */
}

Laravel js DataTable: how do I assign a value from js back to the .blade?

I have these rows:
each row is being outputted by the DataTable plugin within app.js
my target is this particular value, ${row.category_id}
let TABLE = $('#categoryList').DataTable({
{ data: 'id', name: 'id', width: '10%', orderable: false, searchable: false,
render: (data, type, row) =>{
let html = "";
if(row.category_name && row.category_name.toUpperCase() !== "GENERAL"){
html += `<ul class="list-inline no-margin">`;
html += `<li class="list-inline-item">
<button type="button" value="${row.category_id}" class="edit_category btn btn-outline-secondary"><i class="fas fa-edit" aria-hidden="true"></i> Edit</button>
</li>`;
html += `</ul>`;
}
return html;
}
}
});
now I have this blade file, index.blade.php that is connected to app.js using:
<script src="{{asset('/modules/bbr-category-configuration/js/app.js')}}"></script>
What I need to resolve is the constant below:
#section('scripts')
<script type="text/javascript">
const SELECTED_CATEGORY_ID = 1;
</script>
#endsection
by default it is set as 1, but this needs to changed each time the 'Edit' button is clicked (refer to the screenshot). Once the button is clicked, I need to get ${row.category_id} and assign it to the const SELECTED_CATEGORY_ID. What is the correct way of doing this?
TLDR: how do I pass a value from .js back to .blade.php?
What I tried:
my first obstacle is to get the value from ${row.category_id} on click, but here is where I got stuck
$(document).on('click', '.edit_category', function () {
console.log(${row.category_id});
});
I cannot console.log (to test if I got the correct variable) outside the DataTable because it cannot be read, or do it inside toe columns because it is not the right syntax.
please feel free to ask for any clarifications.
First of all, if your variable's data will change during the process then it is not const it should be declared as let. You should know the difference between var let and const.
And you can use data-* attributes in the edit button so you can easily fetch the category_id when that button is clicked eg:
<button type="button" data-category=`${row.category_id}`class="edit_category">Edit</button>
Then on click event, you can get that data using
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).data('category');
});
You can fetch the value attribute of the button too using jquery. But generally, I don't use that. Or I haven't seen much usage of that too. You can try it like this too
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).value;
});

JS: function not defined, Unable to create JSON object because JS not able to recognize the key is string

I have JS script function that holds cart items to order food.
This function is passed with 2 parameters ID and price.
My script file looks like
<script>
function addtocart(mitem, mprice) {
var price = String(mprice)
var mobj = { String(mitem): price }
var storeobj = JSON.stringify(mobj)
localStorage.setItem('cart', storeobj)
}
</script>
My button looks like this
<p style="position: absolute; bottom: 0px"><button class="button" style="width: 200px" onclick="addtocart( '{{M.Menu_Item}}', '{{M.Menu_ItemPrice}}' )" >Add to Cart</button>
When I click on the button in developer console in chrome says that addtocart function not defined.
I did read about on click listens but I have to pass the parameter for each button click, which is different. What might I be doing wrong?
You need to use [ ] to set mobj.
var mobj = { [String(mitem)]: price };
Basically, Chrome is throwing "Uncaught SyntaxError: Unexpected token :" at
var mobj = { String(mitem): price }
which means it is not recognizing your JS code due to syntax error.

datatables colReorder order method with array from variable

I would like to get a dynamically generated array and pass it into the "order" option of colReorder.
The following works fine:
var colOrder = [2,1,0];
$(document).ready(function() {
dataTable = $('#example').DataTable( {
colReorder: true
} );
dataTable.colReorder.order(colOrder);
} );
Note the array colOrder. I can put a variable for that static array into the dataTables order option.
When I test by having javascript alert the contents of colOrder, I get: 2,1,0 (no brackets)
However, the following does not work:
HTML:
<input id="test" type="hidden" value="2,1,0" />
Javascript:
var colOrder = new Array($('#test').val().split(","));
$(document).ready(function() {
dataTable = $('#example').DataTable( {
colReorder: true
} );
dataTable.colReorder.order(colOrder);
} );
When I test by having javascript alert the contents of colOrder this time, I get: 2,1,0 (no brackets) -- I see no difference! The DataTable is generated, and colReorder even works, but the order I provide with that variable doesn't work.
I get the following error: ColReorder - array reorder does not match known number of columns. Skipping.
Can someone help me? Here is the jsfiddle: https://jsfiddle.net/runnerjoe/k47puxux/1/
Your non-functioning code is producting [["2","1","0"]], not [2,1,0]. Remove the new Array wrapper, as it is nesting the values in another array. You may also need to convert the strings to integers:
var colOrder = $('#test').val().split(",").map(function(index) {
return parseInt(index, 10);
});
Updated fiddle

Categories