For everyone wondering what this guy was looking to do - he was wanting buttons with an up state and a down state. He just didnt explain it very well.
This is a very old thread but i googled "ajax change background image" to find out the best way to use an ajax call to a php script which would return an image file location. This file location would be used to change the background of a div. I have already achieved it but wanted to make it as efficient as possible.
This is how i managed it:
mainfile.html: - <html>
-
<head>
-
<script language="javascript" src="ajax_code.js"></script>
-
</head>
-
<body>
-
<div id="image-control" >
-
<input id="change-bg" type="button" value="change-bg" onClick="changeimage('get-new-image.php','image-display')" />
-
</div>
-
<div id="image-display"></div>
-
</body>
-
</html>
-
---------------------------------------------
ajax_code.js: - /* AJAX script to call php script to deal with images
-
*/
-
-
//Create a boolean variable to check for a valid Internet Explorer instance.
-
var xmlhttp = false;
-
//Check if we are using IE.
-
try {
-
//If the Javascript version is greater than 5.
-
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
-
} catch (e) {
-
//If not, then use the older active x object.
-
try {
-
//If we are using Internet Explorer.
-
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
-
} catch (E) {
-
//Else we must be using a non-IE browser.
-
xmlhttp = false;
-
}
-
}
-
//If we are using a non-IE browser, create a javascript instance of the object.
-
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
-
xmlhttp = new XMLHttpRequest();
-
}
-
-
function changeimage(serverPage, objID) {
-
var obj = document.getElementById(objID);
-
xmlhttp.open("GET", serverPage);
-
xmlhttp.onreadystatechange = function() {
-
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
-
var result = xmlhttp.responseText;
-
obj.style.backgroundImage = result;
-
}
-
}
-
xmlhttp.send(null);
-
}
-
get-new-image.php: - <?php
-
##include code to get file name and put in variable $image_name
-
-
$new_image = "url(".$image_name.")";
-
echo $new_image;
-
?>