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.

Dani AI

Generated

— the simplest, robust pattern is: (1) send a small POST with the layer identifier and the hex color, (2) validate the input on the server, (3) persist using a prepared statement, and (4) return a JSON result so the page can react. pointed the right direction with an XHR, but a modern, cleaner front-end is to POST JSON and parse a JSON response.

Example front-end (using Fetch):

// send { layer, color } as JSON to the server
fetch('/save-color.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ layer: selectedLayer, color: hexColor })
})
  .then(r => r.json())
  .then(resp => {
    if (!resp.success) console.error('Save failed', resp.error);
    // else: optionally mark the layer as "saved"
  })
  .catch(err => console.error('Network error', err));

Server-side: validate the color (regex for 6 hex digits), normalize the value (add leading # if needed), and use PDO prepared statements to avoid injection. Example table and a minimal PHP handler:

CREATE TABLE layer_colors (
  id INT AUTO_INCREMENT PRIMARY KEY,
  layer VARCHAR(50) NOT NULL,
  color CHAR(7) NOT NULL,
  UNIQUE KEY(layer)
);
<?php
// save-color.php (read JSON, validate, store with PDO)
$input = json_decode(file_get_contents('php://input'), true);
$layer = $input['layer'] ?? null;
$color = $input['color'] ?? null;
// validate color: allow "#RRGGBB" or "RRGGBB"
if (!is_string($layer) || !preg_match('/^#?[0-9A-Fa-f]{6}$/', $color)) {
  http_response_code(400);
  echo json_encode(['error'=>'invalid input']);
  exit;
}
if ($color[0] !== '#') $color = '#'.$color;
// use PDO with prepared statements to insert/update...

Quick tips: store the color as CHAR(7) if including #, debounce saves to avoid many requests while dragging/picking, return clear error messages, protect the endpoint with authentication and CSRF checks, and inspect the browser Network tab for request/response details. For Fetch API docs and PDO guidance see the MDN and PHP manual.

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.