Click on checkbox and go to url with saved data - javascript

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=...

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

location.href refreshes instead of redirecting

I'm making a javascript game and once the user finished the game, the user will enter their initials and hit submit. Once they hit submit, it'll redirect them to a new page (end.html). I'm not sure if I've set up my click event incorrectly or I'm using the wrong location.href. But, when I hit the submit button, it brings the user back to the start screen(index.html), instead of the end (highscore) page.
The script tag is located on the bottom of the HTML pages, tags are correctly named. I tried the DOMContentLoaded function and that didn't seem to work. If I need to provide more of my code, please let me know.
here's the js snippet
submitScore.addEventListener("click", function () {
var initials = document.getElementById("initials").value;
// calling highscore page function
endPage(initials, time);
});
function endPage(inits, scores) {
var userData = {
inits: inits,
scores: scores
};
highscores.push(userData);
localStorage.setItem("userData", JSON.stringify(highscores));
location.href = "end.html"
}
I personally have never used location.assign - have you tried location.replace()?
submitScore.addEventListener("click", function () {
var initials = document.getElementById("initials").value;
// calling highscore page function
endPage(initials, time);
});
function endPage(inits, scores) {
var userData = {
inits: inits,
scores: scores
};
highscores.push(userData);
localStorage.setItem("userData", JSON.stringify(highscores));
location.replace(`${location.origin}/end.html`);
// get base url and append 'end.html'
}
EDIT [for others confused]: Actual bug was that the button was being submitted - bravo epascarello for this code:
submitScore.addEventListener("click", function (evt) {
evt.preventDefault(); // prevent default behaviour of event

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');
/*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^*/
}
});

Add/change session variable only on click on an element

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 ?

Back button / backspace does not work with window.history.pushState

I have made a solution for my website which includes using ajax to present the general information on the website. In doing this, I am changing the URL every time a user loads some specific content with the window.history.pushState method. However, when I press backspace or press back, the content of the old url is not loaded (however the URL is loaded).
I have tried several solutions presented on SO without any luck.
Here is an example of one of the ajax functions:
$(document).ready(function(){
$(document).on("click",".priceDeckLink",function(){
$("#hideGraphStuff").hide();
$("#giantWrapper").show();
$("#loadDeck").fadeIn("fast");
var name = $(this).text();
$.post("pages/getPriceDeckData.php",{data : name},function(data){
var $response=$(data);
var name = $response.filter('#titleDeck').text();
var data = data.split("%%%%%%%");
$("#deckInfo").html(data[0]);
$("#textContainer").html(data[1]);
$("#realTitleDeck").html(name);
$("#loadDeck").hide();
$("#hideGraphStuff").fadeIn("fast");
loadGraph();
window.history.pushState("Price Deck", "Price Deck", "?p=priceDeck&dN="+ name);
});
});
Hope you guys can help :)
pushState alone will not make your page function with back/forward. What you'd need to do is listen to onpopstate and load the contents yourself similar to what would happen on click.
var load = function (name, skipPushState) {
$("#hideGraphStuff").hide();
// pre-load, etc ...
$.post("pages/getPriceDeckData.php",{data : name}, function(data){
// on-load, etc ...
// we don't want to push the state on popstate (e.g. 'Back'), so `skipPushState`
// can be passed to prevent it
if (!skipPushState) {
// build a state for this name
var state = {name: name, page: 'Price Deck'};
window.history.pushState(state, "Price Deck", "?p=priceDeck&dN="+ name);
}
});
}
$(document).on("click", ".priceDeckLink", function() {
var name = $(this).text();
load(name);
});
$(window).on("popstate", function () {
// if the state is the page you expect, pull the name and load it.
if (history.state && "Price Deck" === history.state.page) {
load(history.state.name, true);
}
});
Note that history.state is a somewhat less supported part of the history API. If you wanted to support all pushState browsers you'd have to have another way to pull the current state on popstate, probably by parsing the URL.
It would be trivial and probably a good idea here to cache the results of the priceCheck for the name as well and pull them from the cache on back/forward instead of making more php requests.
This works for me. Very simple.
$(window).bind("popstate", function() {
window.location = location.href
});
Have same issue and the solution not working for neither
const [loadBackBtn, setLoadBackBtn] = useState(false);
useEffect(() => {
if (loadBackBtn) {
setLoadBackBtn(false);
return;
} else {
const stateQuery = router.query;
const { asPath } = router;
window.history.pushState(stateQuery, "", asPath);
},[router.query?.page]

Categories