You can change a color on a web page with ajax. In this tutorial we make use of the HTML input type of color. We then generate an Ajax request to the processor. This in turn returns CSS code that changes the color on the webpage. To see how this is done watch the video.



Scripts for Changing Color on Webpage With Ajax

Create a file and name it index.php. Here is the code to put in that script.
<html>
<head>
<title>Ajax Color Change Example</title>
</head>
<body>
<p>Pick a Background Color</p>
<input type="color" id="bgcolor" value="#000000"> <p>Pick a Text Color</p>
<input type="color" id="textcolor" value="#ffffff">
<br/>
<button type="button" id="sub" onclick="ajax_color();">Change Color</button>
<br/>
<div id="status"></div>

<script>
function ajax_color(){
var hr = new XMLHttpRequest();
var url = "processor.php";
var bg = document.getElementById("bgcolor").value;
var tx = document.getElementById("textcolor").value;
var vars = "bgc="+bg+"&txc="+tx;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
//alert('Color Is About To Change!');
}
}
hr.send(vars); // After Check Steps are done execute the request
document.getElementById("status").innerHTML = "color change in progress...";
}
</script>
</body>
</html>
Next create a file called processor.php. Here is the script to put in that file.
<?php
if(isset($_POST['bgc'])){
$bgc=$_POST['bgc'];
$txc=$_POST['txc'];
echo '<style>body{background-color:'.$bgc.'; color:'.$txc.';}</style>';
}; ?>


Sign Up To Comment