www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 23

Thread: [RESOLVED] Very simple method doesn't work reliably

  1. #1
    Join Date
    Jul 2010
    Posts
    34

    resolved [RESOLVED] Very simple method doesn't work reliably

    In a nutshell, I'm using JavaScript to populate and control select boxes in a form. What I'm doing is passing arrays from PHP to JavaScript so they can be accessible after the page loads into the browser.

    This is how I do it...

    PHP parses the array data into my JavaScript output
    PHP Code:
    // $js_content is passed to html within script tags
    $js_content "var dataArray = new Array();";

    foreach (
    $dataArray as $key => $val)
    {
        
    $js_content.= "
    dataArray['"
    .$key."'] = \"".$val."\";";
    }

    $js_content.= "
                
    function setVariable(selection)
    {
        alert('dataArray[' + selection + '] = ' + dataArray[selection]);
    }"

    Then the form uses an onchange handler to activate the function
    HTML Code:
    <select name="select_field" onchange="setVariable(this.options[this.selectedIndex].value);">
    	<!-- options... -->
    </select>
    Finally, when the two are put together, the user should choose an option in the select box and the JavaScript should execute; and it works... mostly.

    See, this section of the script works perfectly:
    HTML Code:
    var purchasetypeArray = new Array();
    purchasetypeArray['0'] = "Sale";
    purchasetypeArray['1'] = "Lease";
    purchasetypeArray['2'] = "Participation";
    purchasetypeArray['3'] = "Maintenance";
    purchasetypeArray['4'] = "Warranty";
    
    function selectType(selection)
    {
    	alert('purchasetypeArray[' + selection + '] = ' + purchasetypeArray[selection]);
    	
    	switchMenu('typedetails_Sale',			'none');
    	switchMenu('typedetails_Lease',			'none');
    	switchMenu('typedetails_Participation',	'none');
    	switchMenu('typedetails_Maintenance',	'none');
    	switchMenu('typedetails_Warranty',		'none');
    	
    	switchMenu('typedetails_' + purchasetypeArray[selection], 'block');
    }
    But these, however, does not:
    HTML Code:
    var categoryArray = new Array();
    categoryArray['0'] = "Software Upgrade";
    categoryArray['1'] = "Hardware Upgrade";
    categoryArray['3'] = "Spare Parts";
    categoryArray['4'] = "Warranty Parts";
    categoryArray['5'] = "New Table";
    categoryArray['6'] = "Refurbished Table";
    categoryArray['7'] = "Maintenance";
    categoryArray['8'] = "Return";
    categoryArray['9'] = "Service Parts";
    
    function setCategory(selection)
    {
    	var myCategory = categoryArray[selection];
    	alert('categoryArray[' + selection + '] = ' + categoryArray[selection]);
    	
    	switchMenu('Software Upgrade',	'none');
    	switchMenu('Hardware Upgrade',	'none');
    	switchMenu('Return',		'none');
    	
    	if (currentTable == 'defaultValue')
    	{
    		alert('Table must be selected.');
    		document.new_request.categoryid[0].selected = '1';
    	}
    	else
    	{
    		switchMenu(myCategory, 'block');
    	}
    }
    
    var currentPartNo = '';
    
    var partArray = new Array();
    partArray['119'] = "Key for Bill Validator";
    partArray['121'] = "Key for Power Door";
    partArray['120'] = "Key For Shoe";
    <!-- ect, ect... -->
    
    function setPartNo(selection)
    {
    	alert('partArray[' + selection + '] = ' + partArray[selection]);
    	document.new_request.partname.value = partArray[selection];
    	
    	currentPartNo = selection;
    	
    	setUnitPrice();
    }
    What I don't understand, though, is that the point at which it breaks down is only when I try to access the categoryArray. I've switched up the code to have it access other arrays and it works. Additionally, though, I've set other functions to reference the category array and they also malfunction. The only problem is that I can't find any errors.

  2. #2
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Well, without testing the code, I have noticed something. Despite PHP, JavaScript make a subtle difference between a simple ordered list of values (array), and a collection of pairs property:value (object)

    Array:
    Code:
    var array=[];  //short notation for var array=new Array()
    array[0]='a';
    array[1]='b';
    array[2]='c';
    Note the blue: Within the simple arrays, the identifier (the key) is a number, not a string. Well, JavaScript is tolerant in this case, an it will take it as a number, till the end. But, important: the last (the greatest) identifier sets the rank of the array. The identifier is not required; it can be implicit.
    Code:
    var array=['a','b','c']
    Now, if you think like in PHP, you would expect like an array like:
    Code:
    var categoryArray = new Array();
    categoryArray['0'] = "Software Upgrade";
    categoryArray['1'] = "Hardware Upgrade";
    categoryArray['3'] = "Spare Parts";
    categoryArray['4'] = "Warranty Parts";
    categoryArray['5'] = "New Table";
    categoryArray['6'] = "Refurbished Table";
    categoryArray['7'] = "Maintenance";
    categoryArray['8'] = "Return";
    categoryArray['9'] = "Service Parts";
    to have 9 members. No: it has 10, no matter you have skipped the categoryArray['2'], it is included anyway, and it is undefined typed;

    My advice is to use the short notation.

    For arrays:
    Code:
    var array=['a','b','c']
    Or use objects:
    Code:
    var object={
    'first_value':'a',
    'second_value':'b',
    'third_value':'c'
    }
    See also: JSON
    www.json.org
    Last edited by Kor; 07-29-2010 at 08:52 AM.

  3. #3
    Join Date
    Jul 2010
    Posts
    34
    I tried using non-quoted numbers, but the script never accepted them. It only started working once I started quoting the index keys to make the arrays associative.

    I'll try the object method and return with my results.

  4. #4
    Join Date
    Jul 2010
    Posts
    34
    I assume you reference objects in the same way as arrays?

    object[index]?

  5. #5
    Join Date
    Aug 2007
    Posts
    3,767
    Array:
    Code:
    var arr = [1,2,3] // or new Array(1,2,3);
    arr[0]; // 1
    arr[2]; // 3
    arr.length; == 3
    An associative array in JavaScript is really an object. There isn't an index.
    Code:
    var obj = {"key": "value", "a":1,"b":2,"c":3} // or new Object(); obj.key = value; obj["key"] = value;
    obj.key; // value
    obj.a; // 1
    obj["b"]; // 2
    If you had a problem with arr[1], you had problems elsewhere.
    Great wit and madness are near allied, and fine a line their bounds divide.

  6. #6
    Join Date
    Jul 2010
    Posts
    34
    would I make a multidimensional object in the same way as a multidimensional array?

    How I'm doing it now:
    PHP Code:
    $js_content "var priceArray = new Array();";
    foreach (
    $priceArray as $key => $val)
    {
        
    $js_content.= "
                priceArray['"
    .$key."'] = new Array();
                priceArray['"
    .$key."']['std'] = \"".$val['std']."\";
                priceArray['"
    .$key."']['igt'] = \"".$val['igt']."\";";


  7. #7
    Join Date
    Aug 2007
    Posts
    3,767
    But priceArray is not an array, it's an object (if my memory of PHP foreach loops is correct).
    Code:
    $js_content = "var priceArray = {};";
    foreach ($priceArray as $key => $val)
    {
        $js_content.= "
                priceArray['".$key."'] = {};
                priceArray['".$key."']['std'] = \"".$val['std']."\";
                priceArray['".$key."']['igt'] = \"".$val['igt']."\";";
    }
    Your code will work anyway, because all arrays are objects in JavaScript, but not necessarily as you intent. And yes, you can nest arrays and objects to your heart's content.
    Great wit and madness are near allied, and fine a line their bounds divide.

  8. #8
    Join Date
    Jul 2010
    Posts
    34
    I got it to build the category array with this:
    HTML Code:
    $js_content.= "
    			var categoryArray = 
    			{";
    end($categoryArray);
    $lastVal = current($categoryArray);
    foreach ($categoryArray as $key => $val)
    {
    	$js_content.= "
    				'".$key."' : '".$val."'";
    	$js_content.= ($val != $lastVal)? "," : "";
    }
    			
    $js_content.= "
    			}";
    But I'm still encountering the same malfunction. Whenever I reference the (now object) $categoryArray from within my function, it does nothing.

    I disabled all of the script and had it run a simple alert box
    HTML Code:
    alert('setCategory('+ selection +')');
    and it worked, it traced the user's selection, so I know that variable is functioning properly. Then I tried both the "categoryArray.selection" and "categoryArray[selection]" methods but neither worked. So finally I tried a static trace and tried "categoryArray.1", "categoryArray[1]", and "categoryArray['1']"; but to no avail.

  9. #9
    Join Date
    Jul 2010
    Posts
    34
    Oh, my object-generating code outputs this:
    HTML Code:
    			var categoryArray = 
    			{
    				'0' : 'Software Upgrade',
    				'1' : 'Hardware Upgrade',
    				'3' : 'Spare Parts',
    				'4' : 'Warranty Parts',
    				'5' : 'New Table',
    				'6' : 'Refurbished Table',
    				'7' : 'Maintenance',
    				'8' : 'Return',
    				'9' : 'Service Parts'
    			}

  10. #10
    Join Date
    Jul 2010
    Posts
    34
    I just noticed that I didn't have the terminating semicolon at the end there. I added it after the end bracket and ran my tests again and it still doesn't work.

  11. #11
    Join Date
    Jul 2010
    Posts
    34
    alright, this has got to be a scope problem.

    I am sort of trying random things to see if they change anything and one of the things I tried was just tracing categoryArray with no selection and it returned "undefined"

    I thought that was peculiar, so I commented out my definition of categoryArray and added a definition within the function; it is empty, but it is defined. Then when I traced it, it simply returned an empty string, but not "undefined".

    Which leads me to conclude that for some reason my function cannot access the array existing in the parent scope even though my other functions can access their parent variables just fine.

    That said, is there any specific method to accessing parent variables like a global call in PHP?

    For example:
    PHP Code:
    function myFunct()
    {
        global 
    $myVar;
        echo 
    "Now I can access $myVar!";


  12. #12
    Join Date
    Jul 2010
    Posts
    34
    I would just define it within the function, but I need that array accessible to other functions as well.

    Edit: sorry for the multiple posts. I swear that edit button wasn't there last night when I looked for it, but I could have just been very tired.

    On the other hand, when I DO move the array definition to within the function, it traces appropriately, returning each value of the array. I do not understand why it cannot find my array outside the function...
    Last edited by Errant_Shadow; 07-29-2010 at 10:51 AM.

  13. #13
    Join Date
    Jul 2010
    Posts
    34
    While exploring this, I've come across yet another oddity.

    Even though I'm setting variables with defaults, they are tracing as undefined unless I set them at least once with their function. However, when I include a call to their function with a default value to set, it doesn't execute; it ONLY executes when called by the event handler attached to the form fields...

    This still traces as "undefined" until I made a selection on the table field of my form.
    HTML Code:
    			var currentTable = 'defaultValue';
    			
    			function setTable(selection)
    			{
    				currentTable = selection;
    				alert('currentTable = ' + currentTable);
    			}
    			setTable('defaultValue');

  14. #14
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Quote Originally Posted by Errant_Shadow View Post
    I would just define it within the function, but I need that array accessible to other functions as well.
    Define it outside the functions:
    Code:
    var myArray;
    function bulidArray(){
    for(var i=0;i<10;i++){
    myArray[myArray.length]=i;
    }
    }
    function showArray(){
    alert(myArray)
    }
    buildArray();
    showArray();
    JavaScript uses 2 type of variables: global and local. The type is not set by a different token, it is set only by the position of the variable. If it is defined outside the functions, it is global. If it is defined inside the functions, it is local.

    To define a variable, you have to use the token var. This token it is to be used only once, when the variable is defined.
    Code:
    var globalvariable='something'; // this is global
    function MyFunction(){
    var localVariable='something'; // this is local
    }

  15. #15
    Join Date
    Jul 2010
    Posts
    34
    That's what I'm doing.

    I might be on to something though. I'll know more in a little while and I'll post as soon as I do.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles