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.
[code]<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>[/code]
Next create a file called processor.php. Here is the script to put in that file.
[php]<?php
if(isset($_POST[‘bgc’])){
$bgc=$_POST[‘bgc’];
$txc=$_POST[‘txc’];
echo ‘<style>body{background-color:’.$bgc.’; color:’.$txc.’;}</style>’;
}; ?>[/php]
2 Comments
Hi, Do you have the solution with jQuery and Ajax?
Sure thing. This would be your index.php or whatever you want to name it.
[code]<html>
<head>
<title>jQuery Ajax Color Change Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</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">Change Color</button>
<br/>
<div id="display"></div>
<script>
$(document).ready(function(){
$("#sub").click(function(){
var bgcolor = $("#bgcolor").val();
var textcolor = $("#textcolor").val();
var dataString = ‘bgcolor1=’+ bgcolor + ‘&textcolor1=’+ textcolor;
$.ajax({
type: "POST",
url: "processor.php",
data: dataString,
cache: false,
success: function(result){
$("#display").html(result);
}
});
return false;
});
});
</script>
</body>
</html>[/code]
This would be your processor.php
[code]<?php
if(isset($_POST[‘bgcolor1’])){
$bgc=$_POST[‘bgcolor1’];
$txc=$_POST[‘textcolor1’];
echo ‘<style>body{background-color:’.$bgc.’; color:’.$txc.’;}</style>’;
}; ?>[/code]