Run the PHP script when clicking the link without refreshing the page.

Ok, so I made a style switch in php, and I use it as a hidden function on my site that runs when the user enters "teema", and the modal block appears at the top of the page contents and displays available themes.

<ul> <li><a href="teema.php?teema=default" class="ajaxLink">Normaali</a></li> <li><a href="teema.php?teema=superhero" class="ajaxLink">Superhero</a></li> <li><a href="teema.php?teema=spacelab" class="ajaxLink">Spacelab</a></li> <li><a href="teema.php?teema=united" class="ajaxLink">United</a></li> <li><a href="teema.php?teema=cyborg" class="ajaxLink">Cyborg</a></li> </ul> 

However, I want to change the theme without refreshing the page, so css should load in the background. Here teema.php:

 <?php $style = $_GET['teema']; setcookie("teema", $style, time()+604800); if(isset($_GET['js'])) { echo $style; } else{ header("Location: ".$_SERVER['HTTP_REFERER']); } ?> 

And php for the index that validates the cookie:

 <?php if(!empty($_COOKIE['teema'])) $style = $_COOKIE['teema']; else $style = 'default'; ?> <link rel="stylesheet" href="css/<? echo $style;?>.css" id="theme"> 

How can I load the new css in the background and drag it to the old css using jQuery?

+4
source share
3 answers

You can simply make an ajax request so that the cookie is returned

Using jQuery:

 $('.ajaxLink').click(function(e) { e.preventDefault(); var teemaUrl=this.href; var teema=teemaUrl.split('=').pop() $.get(teemaUrl, { js:true}, function(data){ $('#theme').attr('href','css/'+ teema+'.css') }) }); 

This will teema value from the href link, call that href (you may need to add path information) and update the link tag href with ID = theme

+1
source

You can give a response like JavaScript content in a PHP file and manage the stylesheet.

Change the code as follows:

 <?php $style = $_GET['teema']; setcookie("teema", $style, time()+604800); if(isset($_GET['js'])) { // echo $style; } else{ // header("Location: ".$_SERVER['HTTP_REFERER']); } header("Content-type: text/javascript"); ?> document.getElementById("theme").setAttribute("href", "teema.css"); 

Using AJAX and PHP to change themes.

Since you are already using id="theme" in the <link /> , we can easily set the material in jQuery using AJAX.

So you give a topic request this way:

 $.getScript("theme.php?teema=theme"); 

And in PHP:

 header("Content-type: text/javascript"); $('#theme').attr('href', 'css/<?php echo $_GET['teema']; ?>'); 
+1
source

Change the contents of this link ( $('$#theme').attr('href', 'css/' + selectedtheme +'.css'); and you can also set the cookie in javascript ( document.cookie = 'theme=' + selectedtheme )

+1
source

Source: https://habr.com/ru/post/1445357/


All Articles