Hey guys,

I am making a website where I have a panel of colors to choose from and it allows the user to click on a layer on the page and then click on the color they wish to change that layer to. Everything works fine and the color changes, BUT I need to be able to save the color changes. So basically I need a way to insert the value of the color variable into my MySQL database. People have told me that this can be accomplished using Ajax since I am using javascript to make the color changes, but I cannot seem to figure out how to do this. Here is an example of what I'm talking about. My function which changes the color of a certain layer is like this:

function color(strColor)
{
 var i;
 for (i=0;i<document.change.elem.length;i++)
 {
  if (document.change.elem[i].checked) break;
 }
 if (document.change.elem[i].value == 'aName')
 {
  document.getElementById(document.change.elem[i].value).style.backgroundColor = '#'+strColor;
  document.change.elements['color'+document.change.elem[i].value].value = '#'+strColor;
 }

Obviously strColor is the variable that holds the color value. So how can I use Ajax to take this value and insert it into my database. Thanks so much for your help.

I think you have t just send color-vlaue to database through ajax. If so you have to send a asyncronous request to the server using ajax techonolgy. This can be done after you have chaged the color of the layer successfully. here is the simple ajax code to send data to he server.

function xmlhttpPost(mycolor) {
    var xmlHttpReq = false;
    var self = this;
    var strURL = "path of your servlet to do database entry";
    var sParams = "?color=" + mycolor;
     strURL =  strURL + sParams;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            alert("Color successfully saved in database.");
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

call this function as soon as you have changed the layer color successfully.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.