5 Replies - 1105 Views - Last Post: 01 April 2011 - 07:19 AM

#1 kajun989  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 11-June 09

Accessing form id values using Javascript DOM

Posted 27 March 2011 - 06:25 AM

Dear Community. I am undertaking an assignment where I have to create a webpage that reads values from a database, and generate the appropriate amount of sliders (scroll bars) according to the number of database entires. The webpage functions like this:

  • On index.php load, it reads all the slider values from the database and automatically generates and sets each slider to that value

  • On setting each individual slider to a new value by adjusting the slider, the code automatically updates the slider value in the database via AJAX.


So far I have gotten both functionalities to work successfully. There is just one problem with the 2nd functionality. I can only get one slider value to save to the database at a time.

I know how to fix the problem, I just do not know to achieve it.

I shall now illustrate via snippets of code:

This is the slider code:
 
<DIV class=carpe_slider_group>
                <DIV class=carpe_horizontal_slider_display_combo>
                  <DIV class=carpe_slider_display_holder>
                    <!-- Default value: 0 -->
                    <input name="Input" class=carpe_slider_display id="display1" value="<?=$row['slider_val']?>" />
                  </DIV>
                  <DIV class=carpe_horizontal_slider_track>
                    <DIV class=carpe_slider_slit></DIV>
                    <DIV class=carpe_slider id=1 display="display1" style="left:<?=$row['slider_val']?>px"></DIV>
                  </DIV>
                </DIV>
                <DIV class=carpe_horizontal_slider_display_combo></DIV>
                <DIV class=carpe_horizontal_slider_display_combo></DIV>
                <DIV class=carpe_horizontal_slider_display_combo></DIV>
              </DIV>



This is actually placed between a php for loop so that according to the number of entries, say x entries in the database, it prints this code x times to get x sliders.

This is the php code on a separate php webpage that AJAX uses to update one slider table entry got for one given slider:
 
<? 
$sliderval=$_GET['sliderval']; //get the value from ajax function
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('my_db'); //change the name of the database if required
$query="UPDATE tbl_slider SET slider_val='$sliderval' WHERE id='1'";
$result=mysql_query($query);

			
?>



In the above code, there the second to last line reads "UPDATE tbl_slider SET slider_val='$sliderval' WHERE id='1'".
This '1' would be used to identify the entry into the database where the silder value for that slider is updated.

We can also see from the slider code that the id of the slider is , that is id=1 (line09). I can make it so that for each iteration of the for statement execution, the id can be changed to 2,3 etc.

I want to be able to pass this dynamic id value to my javascript function that uses AJAX to call the php page that updates the database (code above). I can then use this information to update database entry 2, 3 etc, for that slider(2,3,etc).How can I do this? Can I possibly use DOM to access the this dynamic value of id? If this is so, how can I do so? If this can be done, I can just append this value to the querystring (code below) and get it into the $_GET array.
The Javascript code has posted below if it is of any help. Many Thanks in advance

<script language="javascript" type="text/javascript">
function setSliderVal(value)
{
	xmlHttp=getXMLHTTP();
	if (xmlHttp==null)
 	 {
 	 	alert ("Your browser does not support AJAX!");
 		return;
 	 }
	
	xmlHttp.onreadystatechange=function() 
	{
	  if (req.readyState == 4) { // only if "OK"
		if (req.status == 200) {						
			//dont do any thing here we just need to save the valued in the database				
		} else {
			alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
		}				
	}
	var queryString = "?sliderval=" + value.substring(0,value.length-2); //stripping last two letter which is px 				
	xmlHttp.open("GET","AJAX4Slider.php"+queryString,true);
	xmlHttp.send(null);
	
}

function getXMLHTTP() { //fuction to return the xml http object
		var xmlhttp=false;	
		try{
			xmlhttp=new XMLHttpRequest();
		}
		catch(e)	{		
			try{			
				xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e){
				try{
				req = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch(e1){
					xmlhttp=false;
				}
			}
		}
		 	
		return xmlhttp;
	}
	
</script>



Is This A Good Question/Topic? 0
  • +

Replies To: Accessing form id values using Javascript DOM

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6039
  • View blog
  • Posts: 23,436
  • Joined: 23-August 08

Re: Accessing form id values using Javascript DOM

Posted 27 March 2011 - 07:34 AM

Seems better suited to Javascript, so I'll move this there.
Was This Post Helpful? 0
  • +
  • -

#3 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: Accessing form id values using Javascript DOM

Posted 27 March 2011 - 10:12 AM

Hi, I'm assuming your using some sort of library or something to render your slider, correct me if I am wrong on that account. I see you have the function setSliderVal() to do the AJAZ call for you but don't see you use it anywhere, could we see an example of where you would use it? You would want the value parameter of this function to be the primary key of the sliders record.

Also before you are done you should make sure to scrub the $sliderval variable before using it in your query. This will help prevent SQL injection
Was This Post Helpful? 0
  • +
  • -

#4 kajun989  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 11-June 09

Re: Accessing form id values using Javascript DOM

Posted 27 March 2011 - 09:28 PM

View PostJstall, on 27 March 2011 - 10:12 AM, said:

Hi, I'm assuming your using some sort of library or something to render your slider, correct me if I am wrong on that account. I see you have the function setSliderVal() to do the AJAZ call for you but don't see you use it anywhere, could we see an example of where you would use it? You would want the value parameter of this function to be the primary key of the sliders record.

Also before you are done you should make sure to scrub the $sliderval variable before using it in your query. This will help prevent SQL injection




Yes, I am using a library to render my slider, more specifically, a Javascript file that I include/reference from within my main webpage. The code for this javascript file is posted below. In it, I use/call the setSliderVal() function (check line 152 below).
Yes, I would like the value parameter of this function to be the primary key of the sliders record.
Thanks for the input on the SQL Injection. Many Thanks for the help!

var carpeDefaultSliderLength      = 100
var carpeSliderDefaultOrientation = 'horizontal'
var carpeSliderClassName          = 'carpe_slider'
var carpeSliderDisplayClassName   = 'carpe_slider_display'

// carpeGetElementsByClass: Cross-browser function that returns
// an array with all elements that have a class attribute that
// contains className
function carpeGetElementsByClass(className)
{
	var classElements = new Array()
	var els = document.getElementsByTagName("*")
	var elsLen = els.length
	var pattern = new RegExp("\\b" + className + "\\b")
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i]
			j++
		}
	}
	return classElements;
}
// carpeLeft: Cross-browser version of "element.style.left"
// Returns or sets the horizontal position of an element.
function carpeLeft(elmnt, pos)
{

	if (!(elmnt = document.getElementById(elmnt))) return 0;
	if (elmnt.style && (typeof(elmnt.style.left) == 'string')) {
		if (typeof(pos) == 'number') elmnt.style.left = pos + 'px';
		else {
			pos = parseInt(elmnt.style.left);
			if (isNaN(pos)) pos = 0;
		}
	}
	else if (elmnt.style && elmnt.style.pixelLeft) {
		if (typeof(pos) == 'number') elmnt.style.pixelLeft = pos;
		else pos = elmnt.style.pixelLeft;
	}
	return pos;
}
// carpeTop: Cross-browser version of "element.style.top"
// Returns or sets the vertical position of an element.
function carpeTop(elmnt, pos)
{
	if (!(elmnt = document.getElementById(elmnt))) return 0;
	if (elmnt.style && (typeof(elmnt.style.top) == 'string')) {
		if (typeof(pos) == 'number') elmnt.style.top = pos + 'px';
		else {
			pos = parseInt(elmnt.style.top);
			if (isNaN(pos)) pos = 0;
		}
	}
	else if (elmnt.style && elmnt.style.pixelTop) {
		if (typeof(pos) == 'number') elmnt.style.pixelTop = pos;
		else pos = elmnt.style.pixelTop;
	}
	return pos;
}
// moveSlider: Handles slider and display while dragging
function moveSlider(evnt)
{
	var evnt = (!evnt) ? window.event : evnt; // The mousemove event
	if (mouseover) { // Only if slider is dragged
		x = slider.startOffsetX + evnt.screenX // Horizontal mouse position relative to allowed slider positions
		y = slider.startOffsetY + evnt.screenY // Horizontal mouse position relative to allowed slider positions
		if (x > slider.xMax) x = slider.xMax // Limit horizontal movement
		if (x < 0) x = 0 // Limit horizontal movement
		if (y > slider.yMax) y = slider.yMax // Limit vertical movement
		if (y < 0) y = 0 // Limit vertical movement
		carpeLeft(slider.id, x)  // move slider to new horizontal position
		carpeTop(slider.id, y) // move slider to new vertical position
		sliderVal = x + y // pixel value of slider regardless of orientation
		sliderPos = (slider.distance / display.valuecount) * 
			Math.round(display.valuecount * sliderVal / slider.distance)
		v = Math.round((sliderPos * slider.scale + slider.from) * // calculate display value
			Math.pow(10, display.decimals)) / Math.pow(10, display.decimals)
		display.value = v // put the new value in the slider display element
		return false
	}
	return
}
// slide: Handles the start of a slider move.
function slide(evnt)
{
	if (!evnt) evnt = window.event; // Get the mouse event causing the slider activation.
	slider = (evnt.target) ? evnt.target : evnt.srcElement; // Get the activated slider element.
	dist = parseInt(slider.getAttribute('distance')) // The allowed slider movement in pixels.
	slider.distance = dist ? dist : carpeDefaultSliderLength // Deafault distance from global var.
	ori = slider.getAttribute('orientation') // Slider orientation: 'horizontal' or 'vertical'.
	orientation = ((ori == 'horizontal') || (ori == 'vertical')) ? ori : carpeSliderDefaultOrientation
		// Default orientation from global variable.
	displayId = slider.getAttribute('display') // ID of associated display element.
	display = document.getElementById(displayId) // Get the associated display element.
	display.sliderId = slider.id // Associate the display with the correct slider.
	dec = parseInt(display.getAttribute('decimals')) // Number of decimals to be displayed.
	display.decimals = dec ? dec : 0 // Default number of decimals: 0.
	val = parseInt(display.getAttribute('valuecount'))  // Allowed number of values in the interval.
	display.valuecount = val ? val : slider.distance + 1 // Default number of values: the sliding distance.
	from = parseFloat(display.getAttribute('from')) // Min/start value for the display.
	from = from ? from : 0 // Default min/start value: 0.
	to = parseFloat(display.getAttribute('to')) // Max value for the display.
	to = to ? to : slider.distance // Default number of values: the sliding distance.
	slider.scale = (to - from) / slider.distance // Slider-display scale [value-change per pixel of movement].
	if (orientation == 'vertical') { // Set limits and scale for vertical sliders.
		slider.from = to // Invert for vertical sliders. "Higher is more."
		slider.xMax = 0
		slider.yMax = slider.distance
		slider.scale = -slider.scale // Invert scale for vertical sliders. "Higher is more."
	}
	else { // Set limits for horizontal sliders.
		slider.from = from
		slider.xMax = slider.distance
		slider.yMax = 0
	}
	slider.startOffsetX = carpeLeft(slider.id) - evnt.screenX // Slider-mouse horizontal offset at start of slide.
	slider.startOffsetY = carpeTop(slider.id) - evnt.screenY // Slider-mouse vertical offset at start of slide.
	mouseover = true
	document.onmousemove = moveSlider // Start the action if the mouse is dragged.
	document.onmouseup = sliderMouseUp // Stop sliding.
	
	return false
}
// sliderMouseUp: Handles the mouseup event after moving a slider.
// Snaps the slider position to allowed/displayed value. 
function sliderMouseUp()
{
	if (mouseover) {
		v = (display.value) ? display.value : 0 // Find last display value.
		pos = (v - slider.from)/(slider.scale) // Calculate slider position (regardless of orientation).
		if (slider.yMax == 0) {
			pos = (pos > slider.xMax) ? slider.xMax : pos
			pos = (pos < 0) ? 0 : pos
			carpeLeft(slider.id, pos) // Snap horizontal slider to corresponding display position.
		}
		if (slider.xMax == 0) {
			pos = (pos > slider.yMax) ? slider.yMax : pos
			pos = (pos < 0) ? 0 : pos
			carpeTop(slider.id, pos) // Snap vertical slider to corresponding display position.
		}
		if (document.removeEventListener) { // Remove event listeners from 'document' (W3C).
			document.removeEventListener('mousemove', moveSlider, false)
			document.removeEventListener('mouseup', sliderMouseUp, false)
		}
		else if (document.detachEvent) { // Remove event listeners from 'document' (IE).
			document.detachEvent('onmousemove', moveSlider)
			document.detachEvent('onmouseup', sliderMouseUp)
		}
	}
	//Here is the function call for ajax to save values
	//alert(document.elements["id"].value);//test
	setSliderVal(document.getElementById('slider1').style.left)//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	mouseover = false // Stop the sliding.
}
function focusDisplay(evnt)
{
	if (!evnt) evnt = window.event; // Get the mouse event causing the display activation.
	display = (evnt.target) ? evnt.target : evnt.srcElement; // Get the activated display element.
	lock = display.getAttribute('typelock') // Is the user allowed to type into the display?
	if (lock == 'on') {
		display.blur()
	}
	return
}
window.onload = function() // Set up the sliders and the displays.
{
	sliders = carpeGetElementsByClass(carpeSliderClassName) // Find the horizontal sliders.
	for (i = 0; i < sliders.length; i++) {
		sliders[i].onmousedown = slide // Attach event listener.
	}
	displays = carpeGetElementsByClass(carpeSliderDisplayClassName) // Find the displays.
	for (i = 0; i < displays.length; i++) {
		displays[i].onfocus = focusDisplay // Attach event listener.
	}
}


This post has been edited by kajun989: 27 March 2011 - 09:29 PM

Was This Post Helpful? 0
  • +
  • -

#5 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: Accessing form id values using Javascript DOM

Posted 28 March 2011 - 12:44 PM

Hi,

I'm not familiar with the library so am only guessing about how it works. One thing you could do is make the slider's id attribute corresponds with it's primary key in the database.

I'm seeing in the MouseUp function where you are calling your function references to a slider variable, I'm guessing that it's the object that triggered the event. If that's the case you could just pass it to your function. From there you could get the id of the object and the value:
function setSliderVal(slider)
{
    var queryString = "?sliderval=" + slider.substring(0,slider.style.left.length-2) + "&id=" + slider.id;
}



Something like that. Again I'm not 100% sure about how the slider works so you may have to find another solution, I hope this helps.
Was This Post Helpful? 0
  • +
  • -

#6 kajun989  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 11-June 09

Re: Accessing form id values using Javascript DOM

Posted 01 April 2011 - 07:19 AM

View PostJstall, on 28 March 2011 - 12:44 PM, said:

Hi,

I'm not familiar with the library so am only guessing about how it works. One thing you could do is make the slider's id attribute corresponds with it's primary key in the database.

I'm seeing in the MouseUp function where you are calling your function references to a slider variable, I'm guessing that it's the object that triggered the event. If that's the case you could just pass it to your function. From there you could get the id of the object and the value:
function setSliderVal(slider)
{
    var queryString = "?sliderval=" + slider.substring(0,slider.style.left.length-2) + "&id=" + slider.id;
}



Something like that. Again I'm not 100% sure about how the slider works so you may have to find another solution, I hope this helps.



This did the trick. Thank you!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1