Add/change session variable only on click on an element - javascript

On my web i have a button. On click on it i want to add a var called key in clients $_SESSION array.. I`m doing it with AJAX like so:
$('button').click(function() {
$.get('engine.php', {key: 1}, function(data) {
console.log('You grabbed the key..');
});
});
In engine.php i`m doing this:
if(!empty($_GET['key'])) {
session_start();
$_SESSION['key'] = true;
}
But it is not good for security reasons.. Every user can type in console a get request and get this var.. How should i do it so the user can get this var only by clicking on a button ?

Related

jsTree plugin - Pages on the website are stuck in a constant reload loop

Guys i have problem with jsTree jQuery plugin. In my app am listing product categories.
I load categories from ajax and push in <div id="jstree_demo_div"> as writteb in the official documentation.
What i do:
First i enable links, when someone click on specific <li> go onspecific page and pass category id param in URL query ?id={id}. With that param i load all products from selected category.
Code for that:
.on('changed.jstree', function (e, data) {
var id = $('#jstree_demo_div').jstree().get_selected("id")[0].id;
if(id) {
window.location.href = '?id='+id;
}
The code above works!
Second after enabling links i need to programmatically set selected node based on url query param id.
Code
.on('loaded.jstree', function(e) {
var idParam = location.search.split('id=')[1]; // get param
$('#jstree_demo_div').jstree().select_node(idParam); // this make loop problem
});
When i put this part code for selecting specific node i get constant reload loop.
If i remove window.location.href = '?id='+id; loop stop.
If i leave window.location.href = '?id='+id; and remove $('#jstree_demo_div').jstree().select_node(idParam); loop stop and selection works.
This toggeder not work but i need both part of code.
If someone click on specific node -> open that link -> and select that node.
Here is full code
$('#jstree_demo_div').jstree({
'core' : {
'select_node' : 4,
'data' : {
'url' : '/admin/proizvod-kategorije',
'data' : function (node) {
return { 'id' : node.id };
}
}
}
}).on('changed.jstree', function (e, data) {
var id = $('#jstree_demo_div').jstree().get_selected("id")[0].id;
if(id) {
window.location.href = '?id='+id;
}
// e.preventDefault(); <-- not stop looping
}).on('loaded.jstree', function(e) {
var idParam = location.search.split('id=')[1];
$('#jstree_demo_div').jstree().select_node(idParam);
// i try but not work
// e.preventDefault();
});
How prevent looping?
Thanks

Click on checkbox and go to url with saved data

I have filters on my page. I need do, when people click on checkbox, redirect on page with get param ?attr=id-with-comma, example: ?attr=1,2,3,4. Where 1, 2, 3, 4 - value of checked checkbox. I have code:
function checkFunc() { // this function call when checkbox is clicked
var id = $("[name=attr]:checked").map(function () {
return this.value;
}).get().join(",");
window.location.href = '?attr=' + id;
}
I use GET.
How save data from address bar, when page reloading and write filters? Now I rewrite attr=...

Rerun original function upon completion of another function in jQuery AJAX

I'm still trying to master jQuery, AJAX, and JSON.
On my application, I have the following dropdown select menu:
<select id="serviceload" name="serviceload"></select>
I auto populate the OPTIONS with another function which I don't think is necessary to display here. Just know that the above SELECT has 1 or more OPTION values.
This is followed by the content section:
<div class="row" id="completeProfile">
// series of DIVS and TABLES
</div>
Initially, the content section is hidden, so the user will only see the dropdown menu:
$('#completeProfile').hide();
And now, the jQuery: this next piece of code is what I use when the user chooses a selection from the dropdown menu. Every time they pick a new selection, queries rerun, and new content is displayed to the screen, unless they select a blank OPTION.
$('#serviceload').change(function () {
var page = $('#serviceload').val();
if (page == "") {
$('#completeProfile').hide();
} else {
$.post('api/profileSearch.php', {
page: page
}, function (data) {
var obj = JSON.parse(data);
$('#portBody').empty();
var htmlToInsert = obj.map(function (item) {
return '<tr><td>' + item.PORT + '</td><td>' + item.NAME + '</tr>';
});
$('#portBody').html(htmlToInsert);
});
// I do several more $.post to return data into specific tables
// Take note of this next $.post
$.post('api/vesselSearch.php', {
page: page
}, function (data) {
var obj = JSON.parse(data);
$('#vesselinfo').empty();
var htmlToInsert = obj.map(function (item) {
return '<tr><td>Edit</td><td>' + item.VESSEL_NAME + '</td></tr>';
});
});
// after all the queries are ran, and the data is returned, now we show the content
$('#completeProfile').show();
}
});
In the vesselInfo portion above, there is section that prints a hyperlink with which you can click, and it opens a modal window. This is for editing purpose. This functions properly.
Here is where the issue lies.
Back in the content section, there is another hyperlink that opens a modal window to add a new vessel.
<h3>Vessels</h3> / Add New
This opens an Add New Vessel modal. In that modal there is a FORM with a button that reads like this:
<button type="button" id="addVesselSubmit">Add</button>
When this button is clicked, it sends the values entered by the user to a PHP script which updates a table.
$('#addVesselSubmit').click(function () {
var addservice = $('#addservice').val();
var addvessel = $('#addvessel').val();
$.post('api/addInfo.php', {
addservice: addservice,
addvessel: addvessel
}, function (data) {
// here is where my problem lies
if (data == 0) {
alert("Vessel was not saved");
} else {
alert("Vessel was saved");
// At this point, I need to rerun the main function above so that it shows the vessel that was added immediately to the content section without a page refresh
}
});
});
So in the code directly above, if the new record was successfully saved to the table, the whole content section should rerun without a page refresh, with the new record automatically showing in the vesselInfo section.
I think the code that is used to display the content needs to be turned into a main function that can be called when the addVesselSubmit is successful, but I am not sure how to proceed with that.
To reiterate my question: I need to be able to save a new record, and print the new record to the page without a page refresh.
$.post('api/addInfo.php', {
addservice: addservice,
addvessel: addvessel
}, function (data) {
// here is where my problem lies
if (data == 0) {
alert("Vessel was not saved");
} else {
alert("Vessel was saved");
// At this point, I need to rerun the main function above so that it shows the vessel that was added immediately to the content section without a page refresh
//Trigger a change on element
$('#serviceload').trigger('change');
/*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
}
});

how to access routing controller form main to nested controller in angular.js?

This is my routing code:
$routeProvider
.when('/', 'main')
.when('/books','main.book')
.segment('main', {
templateUrl:'templates/main.html',
controller:MainCtrl})
.within()
.segment('book', {
templateUrl:'templates/book.html',
controller:BookCtrl
})
These are the controllers:
function Mainctrl()
{
},
function Bookctrl($http,$cacheFactory)
{
var bookCache = $cacheFactory('Books');
var book = bookCache.get("BookName");
if(!book){
alert("first time");
var data=[{"name":"1"},{"name":"2"},{"name":"3"}];
bookCache.put("BookName",data);
} else {
alert("second time");
alert(book);
}
}
First I am loading main.html page. It has one nested view and has one button (Book). When the user clicks on that button I am just loading book.html into that nested view and then within the BookCtrl function I am sending a request to the server to get the data from the server. I am getting a response and I have displayed all data that is working fine. But when I click on that button each time a request is sent to server. So instead of that I have planned to keep all of the data in an array when I click the first time. I have tried by using the above code but when I click for the first time the array is empty so it is pushing data into the array but when I click again it is not showing anything. That means I am not getting any alert. What am I doing wrong?
If you are asking about how to cache items and use them between controllers use cacheFactory
var bookCache = $cacheFactory('Books');
...
var book = bookCache.get("BookName")
//book will be undefined if not cached
if(!book){
//do request to get book
$http.getJSON(url,function(data)
{
var book = {name:data.name,isbn:data.isbn};
//then save it
bookCache.put("BookName",);
//do something with it
showBook(book);
});
} else {
//book was cached, do something with it
showBook(book);
}
you can then access the cache in the other controllers by getting the cache object
function Mainctrl() {
//Will be undefined if it hasnt been created yet.
var bookCache = $cacheFactory.get('Books');
}

class not updating via jquery

$(document).ready(function() {
var session = {};
// Getting PHP session variables into javascript object in order to restric actions for certain users.
$.getJSON('session.php',function(data){
session = data;
console.log(session.role); // currently showing 2.
});
// Display datagrid on page
getRecords();
// If not admin, disable certain actions
if(session.role != 1){ // means it is 2
$("#deletecustomer").attr('class','btn btn-danger disabled');
}
});
Hi,
i m trying to disable the delete record button based on the user role. But i dont know why it is not updating the class of my button even though the console is showing role = 2.
Thanks
Since AJAX is asynchronous, please play with it in the callback:
$(document).ready(function() {
var session = {};
// Getting PHP session variables into javascript object in order to restric actions for certain users.
$.getJSON('session.php',function(data){
session = data;
console.log(session.role); // currently showing 2.
// Display datagrid on page
getRecords();
// If not admin, disable certain actions
if(session.role != 1){ // means it is 2
$("#deletecustomer").attr('class','btn btn-danger disabled');
}
});
});
EDIT: Without possibility to put thisinside the same parts of code, you can do:
var session = {};
var getSessionData = function(callback) {
$.getJSON('session.php',function(data){
session = data;
console.log(session.role); // currently showing 2.
// Display datagrid on page
callback.call();
});
}
var updateButton = function() {
getRecords();
// If not admin, disable certain actions
if(session.role != 1){ // means it is 2
$("#deletecustomer").attr('class','btn btn-danger disabled');
}
}
getSessionData(updateButton);

Categories