Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems with loadJSON / JSON 2

Status
Not open for further replies.

1DMF

Programmer
Jan 18, 2005
8,795
GB
Hi,

I'm trying to build a JSON app, so the data passed between the server and the client is just JSON.

I have a perl script that spits out some JSON to the template
Code:
$template->param( 'JSON' => encode_json(\@data) );

I have in my template
Code:
    <script type="text/javascript">
        // <![CDATA[
        $(document).ready(function(){
            var myJSON = $.parseJSON(<tmpl_var name='JSON'>);
            $('#json_test').loadJSON(myJSON);
        });
        // ]]>     
    </script>

But that errors with
[13:10:40.569] TypeError: obj is null @ jquery.loadJSON.js:156

And If I check myJSON I get blank? (I should get object object)

the JSON from the above template output is
Code:
var myJSON = $.parseJSON([{"FirstName":"Test FName","LastName":"Test LName","CompanyName":"My Test Company","Prod_Type":"Decreasing Term Life","Prod_Provider":"Legal & General"}]);

So why is obj null?

Thanks,

Craig.


"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music
 
Hi

[tt]$.parseJSON()[/tt] expects a [tt]String[/tt] parameter while you are passing [tt]Array[/tt]. ( Or the absence of surrounding single quotes is just a typo in the posted code ? )

Anyway, that code seems to be just plain JavaScript, so should work without a parser function too :
Code:
var myJSON = <tmpl_var name='JSON'>;

Feherke.
feherke.ga
 
It's OK all I needed was to pass the JSON direct to loadJSON...

Code:
$('#json_test').loadJSON(<tmpl_var name='JSON'>);

But I now don't have a JS object of my JSON data?

Is there a way of turning a JS object back to JSON?

so I can pass the JSON object?

Code:
$('#json_test').loadJSON(myJSON_Object);
?

Thanks,
1DMF

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music
 
OK I seemed to have got it to work with this..

Code:
    <script type="text/javascript">
        // <![CDATA[
        $(document).ready(function(){
            var myJSON = <tmpl_var name='JSON'>;         
            $('#json_test').loadJSON(myJSON);
        });
        // ]]>     
    </script>

I don't understand why when I am providing JSON output, I can't use $.parseJSON on it?

Is there a problem with parseJSON, or am I missing something?

Thanks,
1DMF.

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music
 
Hi

1DMF said:
I don't understand why when I am providing JSON output, I can't use $.parseJSON on it?
As I see, there the JSON-stringified output is inserted in a HTML document's [tt]script[/tt] section. That part is already automatically interpreted as JavaScript code by the browser.

Functions like [tt]$.parseJSON()[/tt] and [tt]JSON.parse()[/tt] are necessary when the JSON-stringified output is received in a way in which the browser no expects to receive JavaScript code. Typically AJAX responses in plain/text format.


Feherke.
feherke.ga
 
@1DMF
let's assume (for the sake only of exemplifying) that
1. you want to transfer some html to the client and to insert that html in two different nodes.
2. you are using php as the server (because i don't know enough about perl)

on your server you have this code in a script called ajaxServer.php

Code:
<?php
$string1 = '<div>First text</div>';
$string2 = '<div>Second text</div>';
?>

to 'serve' these string to the client you would do this

Code:
<?php
$string1 = '<div>First text</div>';
$string2 = '<div>Second text</div>';
echo json_encode(array('string1'=>$string1, 'string2'=>$string2));
?>

so there we are transmitting an array (structured data) encoded as json. This needs to be interpreted as a javascript object (as it uses non-numeric keys) on the client side.

on our client we have this (assuming an ajax 'getter' but it could equally be an include in a static file)

Code:
var myJSONObject;
$.ajax({ url: 'ajaxServer.php',
         type: 'get',
         dataType: 'json',
         success: function(data){
              $('#myNode1').append(data.string1);
              $('#myNode2').append(data.string2);
              //store the object just in case it is useful later
              myJSONObject = data;
         }
        });

if you are wanting to use a server side include instead it would look more like this

Code:
var myObj = <?php include ajaxServer.php; ?>;
in rendered form (i.e. unescaped) this would look something like this
Code:
var myObj = {"string1":"<div>First text</div>","string2":"<div>Second text</div>"};

you don't need to parse that string to make it a javascript object (json). It is _already_ in valid object notation.

I'm unaware of the loadJSON method but if this is the method of the plugin found here then all you need to ensure is that your keys match the ids of the elements inside the node into which you load your json object.

e.g
Code:
<div #myDiv>
<div id="string1"></div>
<div id="string2"></div>
</div>
<script type="text/javascript">
var myObj = {"string1":"<div>First text</div>","string2":"<div>Second text</div>"};
$('#myDiv).loadJSON(myObj);
</script>

if you want to reverse this and take an arbitrary piece of html and encode it as a javascript object (quite why I have no idea) you could just do this

[code]
var myObj2 = {idOfObject: $('#idOfObject').html()};

more normally one would want to get the values of form controls and compile them to be sent to a server as json. the way I do this is

Code:
$('#myForm').on('submit', function(e){
 e.preventDefault();
 var formData = $(this).serialize(); //json encode data
 $.ajax({url: url, type:'POST',dataType:'json', data: formData, success: function(result){//do something}});
});
 
jPadie -> so does serialise, JSON encode a form? I thought it just converted it to query string value pairs?

If I just post a serialised form via AJAX to my app I can access it through the normal CGI->param method , not treating it as JSON?

Yes that is the plugin I am playing with, and it's working great : , well now I got my JSON / Object correctly assigned :)



"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music
 
No. Serialize doesn't json encode form data but it does encode it in such a way that it is receivable as an object (associative array) on server side platforms. To json encode a string or object or whatever you can use JSON.stringify Which should be native to modern browsers

I should not have typed "as json". I really meant "in parsable structure". My bad.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top