www.webdeveloper.com
Results 1 to 13 of 13

Thread: Javascript says variable is undefined?!?!?

  1. #1
    Join Date
    Feb 2011
    Posts
    38

    Cool Javascript says variable is undefined?!?!?

    Hi,

    I'm pulling my hair out because I have checked, checked and checked again and I cannot find the problem!!

    Here's my code...
    Code:
    <script language="JavaScript"> 
     
    	function createInstance()
    	{
            var req = null;
    		if (window.XMLHttpRequest)
    		{
     			req = new XMLHttpRequest();
    		} 
    		else if (window.ActiveXObject) 
    		{
    			try {
    				req = new ActiveXObject("Msxml2.XMLHTTP");
    			} catch (e)
    			{
    				try {
    					req = new ActiveXObject("Microsoft.XMLHTTP");
    				} catch (e) 
    				{
    					alert("XHR not created");
    				}
    			}
    	        }
            return req;
    	};
    	
    	function delcat()
    	{
    		var req =  createInstance();
    		var cat_id = document.delcatform.delcatid.value;
    		var data = "action=delete_cat&cat_id=" + cat_id;
     
    		req.onreadystatechange = function()
    		{ 
    			if(req.readyState == 4)
    			{
    				if(req.status == 200)
    				{
    				
    				}	
    				else	
    				{
    					alert("Error: returned status code " + req.status + " " + req.statusText);
    				}	
    			} 
    		}; 
            
    		req.open("POST", "ajax-test2.php", true); 
    		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    		req.send(data);
    		alert(data);
    	};
    	
    </script>
    	
    <?php
    
    include ('../dbconfig.php');
    
    $result = mysql_query("SELECT * FROM category ORDER BY cat_id ASC");
    while ($row = mysql_fetch_array($result))
    	{
    	echo $row['cat_name'];
    	echo '<form name="delcatform" method="POST" action="">
        <input type="text" name="delcatid" value="'.$row['cat_id'].'" /><br />
    	<input type="submit" value="Delete Category"  onClick="delcat()">
    	</form<br />';
    	}
    	
    ?>
    I am having a few problems with trying to get three different forms to work from the one page but I'll go into that after I have this one fixed!!...I have set it to alert the data so that I can see the information is being submitted properly. In the alert box it tells me "action=delete_cat&cat_id=undefined".

    Any help with solving would be appreciated....

    thanks in advance

    Smithster

  2. #2
    Join Date
    May 2003
    Location
    Between Baltimore and DC
    Posts
    3,579
    var cat_id = document.delcatform.delcatid.value;
    alert(cat_id);

    what does that say?

    Eric
    Tech Author [Ajax In Action, JavaScript: Visual Blueprint] | twitter | linkedin | http://www.pascarello.com

  3. #3
    Join Date
    Feb 2011
    Posts
    38
    Quote Originally Posted by A1ien51 View Post
    var cat_id = document.delcatform.delcatid.value;
    alert(cat_id);

    what does that say?

    Eric
    Hi Eric

    It outputs "undefined". I have just thought that it has something to do with the whole form being within the while statement, which means it's echoing each form onto the page with the same name....I don't know how to get around that though.....any ideas?

    Regards

  4. #4
    Join Date
    May 2003
    Location
    Between Baltimore and DC
    Posts
    3,579
    onclick="delcat(this.form)"

    and


    function delcat(frm){
    var req = createInstance();
    var cat_id = frm.delcatid.value;

    Eric
    Tech Author [Ajax In Action, JavaScript: Visual Blueprint] | twitter | linkedin | http://www.pascarello.com

  5. #5
    Join Date
    Feb 2011
    Posts
    38
    You beauty!! I nearly hung myself from the loft trying to figure this out ha ha!!

    Thanks very much, that may actually help me out with the other problems I have but I'll post back if anymore probs.

    Thanks again

    Regards

    Smithster

  6. #6
    Join Date
    Feb 2011
    Posts
    38

    Cool

    Ok, I successfully managed to get it all working with 3 different forms in play too!!

    My next issue though is with file uploading. I need to upload a csv doc and then php puts the data into the database. Can I use the same ajax code to pass on the file details to the php script?

    I have tried with this but although the file is uploading, I don't think the variables are being sent correctly.

    Here's my code...
    Code:
    <script>
    		var req =  createInstance();
    		var action = frm.action.value;
    		if (frm.action.value == 'uploadcsv')
    			{
    			var uploaded = frm.uploaded.value;
    			var data = "action=" + action + "&uploaded=" + uploaded;
    			}
    </script>
    
    <form enctype="multipart/form-data" action="" method="POST">
    			Please choose a file: <input name="uploaded" type="file" /><br />
    			<input type="hidden" name="action" value="uploadcsv" />
    			<input type="submit" value="Upload CSV" onClick="uploadcsv(this.form)" />
    			</form>
    Thanks in advance

    Smithster

  7. #7
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    action is already an attribute, thus it can not have itself an attribute of its own like value

    On the other hand you try to refer the form element straight in an open code (outside any function) before that element (the form) is actually loaded.

  8. #8
    Join Date
    Feb 2011
    Posts
    38
    Quote Originally Posted by Kor View Post
    action is already an attribute, thus it can not have itself an attribute of its own like value
    I have used action as a variable on my other forms which submit data to the server and it hasn't failed so I don't think it is an issue.
    Quote Originally Posted by Kor View Post
    On the other hand you try to refer the form element straight in an open code (outside any function) before that element (the form) is actually loaded.
    Not following this part.... :/

  9. #9
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Quote Originally Posted by smithster View Post
    I have used action as a variable on my other forms which submit data to the server and it hasn't failed so I don't think it is an issue.

    Not following this part.... :/
    OK, let's detail:
    1.
    Code:
    <script>
    //...
    </script>
    You miss the type. Should be:
    Code:
    <script type="text/javascript">
    2.
    Code:
    <script type="text/javascript">
    var action = frm.action.value;
    //..
    </script
    - frm was not defined. What is frm?
    - even it would have been defined elsewhere, it looks like it refers an HTML element, probably a form. But the HTML elements were not loaded yet the moment you wrote that code line. As a general rule you have to use functions and wrote the code lines inside the functions, not outside them.
    - if frm refers a FORM element, action should be the HTML attribute action of the form. But the attribute action can not have again a value attribute of his own. It has simply a value, but not a property called value.

    Could be, maybe:
    Code:
    function myFunction(){
    var action=document.getElementById('frm').action;
    }
    If the form has an id="frm"
    Last edited by Kor; 02-07-2011 at 07:35 AM.

  10. #10
    Join Date
    Feb 2011
    Posts
    38
    Ok, sorry I must have caused confusion, I posted only a snippet of the entire code as I had already posted the entire code in the earlier post. I only posted the part that was relevant.

    To save confusion, here is the entire code...
    PHP Code:
    <script type="text/javascript">
        function 
    createInstance()
        {
            var 
    req null;
            if (
    window.XMLHttpRequest)
            {
                 
    req = new XMLHttpRequest();
            } 
            else if (
    window.ActiveXObject
            {
                try {
                    
    req = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (
    e)
                {
                    try {
                        
    req = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (
    e
                    {
                        
    alert("XHR not created");
                    }
                }
                }
            return 
    req;
        };
     
        function 
    uploadcsv(frm)
        {
            var 
    req =  createInstance();
            var 
    action frm.action.value;
            if (
    frm.action.value == 'uploadcsv')
                {
                var 
    uploaded frm.uploaded.value;
                var 
    data "action=" action "&uploaded=" uploaded;
                }
     
            
    req.onreadystatechange = function()
            { 
                if(
    req.readyState == 4)
                {
                    if(
    req.status == 200)
                    {
                    
                    }    
                    else    
                    {
                        
    alert("Error: returned status code " req.status " " req.statusText);
                    }    
                } 
            }; 
            
            
    req.open("POST""functions.php"true); 
            
    req.setRequestHeader("Content-Type""application/x-www-form-urlencoded");
            
    req.send(data);
            
    alert(data);
        }
    </script>
                <form enctype="multipart/form-data" action="" method="POST">
                Please choose a file: <input name="uploaded" type="file" /><br />
                <input type="hidden" name="action" value="uploadcsv" />
                <input type="submit" value="Upload CSV" onClick="uploadcsv(this.form)" />
                </form> 
    Hope that helps

  11. #11
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    Oh, I see. If so, the same line brings you problems:
    Code:
    var action = frm.action.value;
    The form has already a native HTML attribute called action, but it has also an element (an INPUT element) with the name="action", which will confuse the interpreter.
    Code:
    <form enctype="multipart/form-data" action="" method="POST">
    ...
    <input type="hidden" name="action" value="uploadcsv" />
    What is frm.action, he might think ? The attribute or the element? Usually he decides for the attribute.

    The solve? Change the name of the element. say: "Action"
    Code:
    var req =  createInstance();
            var action = frm.Action.value;
            if (frm.Action.value == 'uploadcsv')
                {
                var uploaded = frm.uploaded.value;
                var data = "Action=" + action + "&uploaded=" + uploaded;
                } 
    ...
    <input type="hidden" name="Action" value="uploadcsv" />
    Last edited by Kor; 02-07-2011 at 09:28 AM.

  12. #12
    Join Date
    Feb 2011
    Posts
    38
    I have changed from action to task although I understand where you're coming from but action has never failed me before.

    Anyway, with using task instead, it still doesn't work. I have included alert(data); which says action=uploadcsv&uploaded=C:\fakepath\prices.csv

    I'd like to check the PHP side....
    PHP Code:
    if ($_POST['action'] == 'uploadcsv')
        {
        
    $target ""
        
    $target $target basename$_FILES['uploaded']['name']) ; 
        
    $ok=1
        if(
    move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 
            {
            echo 
    "The file "basename$_FILES['uploadedfile']['name']). " has been uploaded";
            } 
        else
            {
            echo 
    "Sorry, there was a problem uploading your file.";
            }
        } 
    I know it isn't secure, right now I just want to get it working!! I don't think it's the PHP because the file upload works without the javascript if I just post straight to the php script. But I need it to work from the current page without a refresh.

    Regards

    Paul

  13. #13
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    If you want to send an URL as a value on submit, you should encode it:
    http://www.openjs.com/scripts/data/u..._encoded_data/

Thread Information

Users Browsing this Thread

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

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