Get json data from ajax call

my question is: how can my php script send data like json and return to success or full function?

I tried to get this chat function to work on my site. Since it didn’t work, I created a rolled-up part of the code to check if this has anything to do with the json method.

I only tested if I could get the session name after phpscript was processed. What I get is "undefined" instead of "johndoe".

I have no idea what could be the problem. Obviously, the script works great for others if you see comments on the creators page.

this is my test code

<?php session_start(); $_SESSION['username'] = "johndoe" ;// Must be already set ?> <script type="text/javascript" src="includes/jquery.js"></script> <script language="JavaScript"> $(document).ready(function(){ $("#testjson").click(function(e){ startJsonSession(); return false; }); function startJsonSession(){ $.ajax({ url: "jsontest.php?action=startjson", cache: false, dataType: "json", complete: function(data) { username = data.username; alert(username); } }); } }); </script> <?php //the PHP  if ($_GET['action'] == "startjson") { startjsonSession(); } function startjsonSession() { $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); } ?> 

thanks Richard

0
json jquery ajax php
source share
1 answer

Richard, you should look into the json_encode () function in PHP. It will quickly convert your array to JSON and will not allow you to deal with smaller nuances of JSON syntax with large amounts of data.


Update: changed code

 <?php session_start(); $_SESSION['username'] = "johndoe" ;// Must be already set ?> <script type="text/javascript" src="includes/jquery.js"></script> <script language="JavaScript"> $(document).ready(function(){ $("#testjson").click(function(e){ startJsonSession(); return false; }); function startJsonSession(){ $.ajax({ url: "jsontest.php?action=startjson", cache: false, dataType: "json", complete: function(data) { username = data.username; alert(username); } }); } }); </script> <?php if ($_GET['action'] == "startjson") { startjsonSession(); } function startjsonSession() { $items = ''; print json_encode(array( "username" => "bob", "items" => array( "item1" => "sandwich", "item2" => "applejuice" ) )); } ?> 
+1
source share

All Articles