views:

502

answers:

4

Hello,

my problem is that I can not solve this problem

If I call the php script, all I get is an undefined error

this is the code I use for testing AND

this is the original code from the creator that is giving me a headache

function startJsonSession(){     
    $.ajax({        url: "jsontest.php?action=startjson",       
     cache: false,     
        dataType: "json",   
         complete: function(data) {             
          username = data.username;               
        alert(username);      
      }    
    });
}

//phpscript

if ($_GET['action'] == "startjson") { startJson(); } 


    function startJson() {   

header('Content-type: application/json'); 
    $items = '';     
echo json_encode(array(          
     "username" => "bob",    
    "items" => array( "item1" => "sandwich",   
    "item2" => "applejuice"  
    )     
    )); 


 }

thanks, Richard

edited my question because:
this function returns the json data in a different way and therefore the solution presented below, does not have the same outcome.

function startChatSession() {
    $items = '';
    if (!empty($_SESSION['openChatBoxes'])) {
     foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
      $items .= chatBoxSession($chatbox);
     }
    }


    if ($items != '') {
     $items = substr($items, 0, -1);
    }

header('Content-type: application/json');
?>
{
     "username": "<?php echo $_SESSION['username'];?>",
     "items": [
      <?php echo $items;?>
        ]
}

<?php


    exit(0);
}
A: 

Is username a global variable? If not you should prepend the "var" keyword.

username = data.username -> var username = data.username;

SleepyCod
username is only used inside the completion function, so this shouldn't be a problem?
David Archer
This could lead to "undefined" errors in IE and break the current page.
SleepyCod
+1  A: 

I recreated with your code and figured it out. The object being returned is of type XMLHttpRequest. Its got a property called responseText holding a json string with the data.

so this works..

var decodedData = eval("(" + data.responseText + ")");
              username = decodedData.username;               
                   alert(username);

A bit messy but it does the trick :-)

p.s If it helps, I figured it out using firebug in firefox and sticking a breakpoint in the js code

Edited below: Without wanting to do the eval, you could use this and it works:

$.getJSON("json.php?action=startjson",       

         function(data) {             
              username = data.username;               
                   alert(username);      
          }    
     );

Edited to show what I did with the success function:

    $.ajax({        url: "json.php?action=startjson",       
         cache: false,     
         dataType: "json",   
          success: function(data) {             

              username = data.username;               
                   alert(username);      
          }    
     });
David Archer
Thanks, but isn't that like a bad workaround. I read eval is not always relyable with json. I will try your solution to see if I can get the whole chatcode to work. If you are interested. I put the link to the original code from the creator in my question. I hope I don't have to change a lot in the original code.
eval() is not safe, i.e if you don't trust the source. if you look at json.org then you can find some parsers, like http://code.google.com/p/json-sans-eval/
David Archer
see my edited answer
David Archer
I looked at the original and the difference is instead of specifying a "complete" function, it specifies a "success". That seems to do any eval'ing or whatever beforehand, then the "data" is already a js object
David Archer
Ok, but that one returns undefined also
hmm, then I'm stuck. I just tried that and it worked fine on mine with only that change to your original post :-(
David Archer
Did you used eval with the original function and it worked or without eval, but with the success function??
See edited answer above
David Archer
I commented on your other similar post. Essentially your php response is empty for some reason :-(
David Archer
Yes, and I really want to find out why
you could modify the php code as an experiment to call the function regardless and see what happens...
David Archer
@Dave jquery uses eval() internally when the dataType is set to json
redsquare
that's all the function does anywayIt executes right after document ready.All it has to do, is give back the session variableSo, it must be in the syntax
@redsquare thanks for the info, I wasn't sure how it did it exactly
David Archer
One other thing I can think off is that my hoster is not supporting something. I am just saying something because other people have got it working with no problems at all. Maybe it's the heredoc in the php??
might have broken on the call to json_encode if its php version < 5.2 (I think)
David Archer
no, that one worked, that was the sample code
oh yeah, doh!!!!
David Archer
A: 

also what I don't understand is that it breaks out off php mode, instead of echoing it back like it's done with xml

?>
{
     "username": "<?php echo $_SESSION['username'];?>",
     "items": [
      <?php echo $items;?>
        ]
}

<?php

is this the same as above (object array containing literal array)?

echo json_encode(array(
"username" => "bob",
"items" => $items )
));
}

i think thats just the same as e.g spitting out literal chars same as with html. Just a different style of doing the same thing
David Archer
edited my last post
yes thats manually doing what the json_encode function does. Obviously safer to use json_encode since handwriting can caws errurs :-)
David Archer
A: 

At the end I got it working.

I installed firebug and saw that the php script was returning html headers instead off json.

All off the sudden it started working, I really would like to know what the problem was, but I can't tell you.

Anyway, thanks for sticking so long, David

glad you got it :-)
David Archer