SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Guru
    Join Date
    Nov 2005
    Location
    Midwest
    Posts
    777
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Retrieve JSON data from text field is unsuccessful

    Hello

    I am trying to save JSON data to a text field so that I can use it later. To make a long story short, I am trying to develop a way to remember DHTML changes so when the user hits the back button, it will go back thru DHTML changes. My problem is that when I put the JSON data in the text box, when I retrieve the data, it is no longer JSON data. Below is an example of some code I am using as a proof of concept. I have also tried eval() on the data and that was not successful either.

    Any help would be appreciated.

    Code:
    <html>
    <head>
    
    <script language="JavaScript">
    function remember()
    {
    	addToIframe( document.getElementById( "inputText" ).value );
    }
    
    function addToIframe( newContent )
    {	
    	var tempHTML = "<html><body><input type='text' id='remData' value='" + newContent + "'/></body></html>"
    	
    	var iframe = document.getElementById( "historyFrame" );
        var doc = iframe.contentDocument;
        
    	if ( doc == undefined || doc == null )
    	{
            doc = iframe.contentWindow.document;
    	}
    	
        doc.open();
        doc.write( tempHTML );
        doc.close();
    }
    
    function displayPrevValue()
    {
    	document.getElementById( "historyFrame" ).contentWindow.history.back();
    }
    
    function getData()
    {
    	var value = document.getElementById( "historyFrame" ).contentWindow.document.getElementById( "remData" ).value;
    	alert( value );
    }
    
    function getJsonData()
    {
    	var value = document.getElementById( "historyFrame" ).contentWindow.document.getElementById( "remData" ).value;
    	displayJson( value );
    }
    
    function jsonObject()
    {
    	var jsonData = 
    	{
    		"key1" : "value for key1",
    		"key2" : "value for key2"
    	}
    	
    	displayJson( jsonData );
    	
    	addToIframe( jsonData );
    }
    
    function displayJson( jsonData )
    {
    	alert( jsonData.key1 );
    	alert( jsonData.key2 );
    }
    </script>
    </head>
    <body onLoad="document.getElementById( 'inputText' ).focus();">
    <input type="text" id="inputText" />
    <input type="button" value="Remember" id="Remember" onClick="remember();" />
    <input type="button" value="Do Not Remember" id="NoRemember" />
    
    <br><br>
    
    <input type="button" value="Add JSON Object" id="jsonObject" onClick="jsonObject();" />
    
    <br><br><br>
    
    Iframe:
    <br>
    <input type="button" value="Previous Value" id="prevValue" onClick="displayPrevValue();" />
    <input type="button" value="Get Value" id="getValue" onClick="getData();" />
    <input type="button" value="Get Value" id="getJsonValue" onClick="getJsonData();" />
    
    <br><br><br>
    
    <iframe name="historyFrame" id="historyFrame"></iframe> 
    </body>
    </html>

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    You may need a loop to stringify the object keys and values.

  3. #3
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think you need to call the toString() method. Than eval it.

    e.g.

    Code javascript:
    function jsonObject()
    {
    	var jsonData = 
    	{
    		"key1" : "value for key1",
    		"key2" : "value for key2"
    	}
     
    	displayJson( jsonData );
    	addToIframe( jsonData.toString() );
    }

  4. #4
    SitePoint Guru
    Join Date
    Nov 2005
    Location
    Midwest
    Posts
    777
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the posts but I had tried the toString and then use eval() like below, but then I get a JavaScript error in FireFox saying:

    missing ] after element list
    on Line 41
    [object Object]

    This error occurs on this line

    displayJson( eval( value ) );

    Here is the code I changed which is creating the error:

    Code JavaScript:
    function getJsonData()
    {
    	var value = document.getElementById( "historyFrame" ).contentWindow.document.getElementById( "remData" ).value;
    	displayJson( eval( value ) );
    }
     
    function jsonObject()
    {
    	var jsonData = 
    	{
    		"key1" : "value for key1",
    		"key2" : "value for key2"
    	}
     
    	displayJson( jsonData );
    	addToIframe( jsonData.toString() );
    }

  5. #5
    SitePoint Guru
    Join Date
    Nov 2005
    Location
    Midwest
    Posts
    777
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    After reading more about stringify and the post provided, I was able to get a solution working using the jsonStringify.js file. I find it odd that JavaScript provides a method called eval() that parses the formatted JSON data into an object but they do not provide a toString method which will reverse the process. If this is true, then stringify is the solution I will use and I do appreciate the post for this suggestion. If any one has any other ideas, I would appreciate the feedback.

    I did have to change the text box in the iframe to a text area since the make stringify function can add line breaks.

    Thanks.

    Here is my updated code.

    Code:
    <html>
    <head>
    
    <script type="text/javascript" src="jsonStringify.js"></script>
    
    <script language="JavaScript">
    function remember()
    {
    	addToIframe( document.getElementById( "inputText" ).value );
    }
    
    function addToIframe( newContent )
    {	
    	var tempHTML = "<html><body><textarea name='remData' id='remData'>" + newContent + "</textarea></body></html>"
    	
    	var iframe = document.getElementById( "historyFrame" );
        var doc = iframe.contentDocument;
        
    	if ( doc == undefined || doc == null )
    	{
            doc = iframe.contentWindow.document;
    	}
    	
        doc.open();
        doc.write( tempHTML );
        doc.close();
    }
    
    function displayPrevValue()
    {
    	document.getElementById( "historyFrame" ).contentWindow.history.back();
    }
    
    function getData()
    {
    	var value = document.getElementById( "historyFrame" ).contentWindow.document.getElementById( "remData" ).value;
    	alert( value );
    }
    
    function getJsonData()
    {
    	var value = document.getElementById( "historyFrame" ).contentWindow.document.getElementById( "remData" ).value;
    	var jsonData = JSONstring.toObject( value ); 
    	displayJson( jsonData );
    }
    
    function jsonObject()
    {
    	var jsonData = 
    	{
    		"key1" : "value for key1",
    		"key2" : "value for key2"
    	}
    	
    	displayJson( jsonData );
    	var jsonToString = JSONstring.make( jsonData ); 
    	alert( jsonToString );
    	addToIframe( jsonToString );
    }
    
    function displayJson( jsonData )
    {
    	alert( jsonData.key1 );
    	alert( jsonData.key2 );
    }
    </script>
    </head>
    <body onLoad="document.getElementById( 'inputText' ).focus();">
    <input type="text" id="inputText" />
    <input type="button" value="Remember" id="Remember" onClick="remember();" />
    <input type="button" value="Do Not Remember" id="NoRemember" />
    
    <br><br>
    
    <input type="button" value="Add JSON Object" id="jsonObject" onClick="jsonObject();" />
    
    <br><br><br>
    
    Iframe:
    <br>
    <input type="button" value="Previous Value" id="prevValue" onClick="displayPrevValue();" />
    <input type="button" value="Get Value" id="getValue" onClick="getData();" />
    <input type="button" value="Get JSON Value" id="getJsonValue" onClick="getJsonData();" />
    
    <br><br><br>
    
    <iframe name="historyFrame" id="historyFrame"></iframe> 
    </body>
    </html>

  6. #6
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah, I just realized that toString() wouldn't work.

    3kb, imo, is way to much for such a simple task. A simple for/in loop would solve this nicely.

  7. #7
    SitePoint Guru
    Join Date
    Nov 2005
    Location
    Midwest
    Posts
    777
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I am familiar with a for / in loop but I am obviously missing something because I am not sure how this loop would nicely solve the issue. Could you explain a little more?

  8. #8
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I recommend you using the following open source JSON code. The compressed version is only 2K big.

    About the for...in loop, check out Mozilla's documentation.

  9. #9
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here you go.

    Note, this is very simple. It isn't recursive (it doesn't traverse nested objects) and works as if the value is always a string (when actually it can by anything from a function to an array).

    Code javascript:
    function json2str(json){
    	var isAr = json instanceof Array;
    	var str = isAr ? '[' : '{';
    	var i = 0;
    	for (var name in json) {
    		str += i ? ',' : '';
    		str += isAr ? '\"'+json[name].toString()+'\"' : '\"'+name+'\" :' + ' \"'+json[name].toString()+'\"';
    		i++;
    	}
    	str += isAr ? ']' : '}';
    	return str;
    }

    It should fulfill your needs though.

  10. #10
    SitePoint Guru
    Join Date
    Nov 2005
    Location
    Midwest
    Posts
    777
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    M-M-J - I am following you. Thank you for the follow up and code.

    Pepejeria – thanks for the posting as well… it is always nice to have options.

  11. #11
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your welcome.


Bookmarks

Posting Permissions

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