Hi guys, I'm trying to make a registerscript with AJAX but ran into a problem. So I decided to go back to the basics and find out where the problem is. I created a small site to test some things. Now I can't get the JSON to work. HTML of callbacktest.html: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Callbacktest</title> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#form").submit(function() { var formData = $("#form").serialize(); $.get("callbacktest.php", formData, processData); function processData(data) { if (data.status=="pass") { $("#form").html("<h1>Success</h1>"); alert(data.name); } else { $("#form").html("<h1>Fail</h1>"); alert("fail"); }; }; return false; }); // end submit }); //end ready </script> </head> <body> <form name="form" id="form" action="callbacktest.php" method="post"> <input type="text" name="name" id="name" /> <input type="submit" name="submit" id="submit" /> </form> </body> </html> Code (markup): The code of register.php <?php $name=isset($_GET['name']) ? $_GET['name'] : $_POST['name']; $array = array ('name' => $name, 'status' => "pass"); echo json_encode($array); ?> Code (markup): This keeps giving me a 'fail'-message, while this is actually not possible as the status in the JSON-object is always equal to pass. Can anybody help me ?
You want to know what is actually parsed to data.status It could be empty, because you didn't do it properly.
Oh, I tried that but then I get an empty message. But I don't get an empty message when I first create a JSON-object in the callbacktest.html and then try alert(data.status). So I guess the callbackfunction doesn't receive the JSON or something like that.
Use $.getJSON instead of $.get... $.get would give you the result as string! $.getJSON would parse it as JSON so you can use it! <script type="text/javascript"> $(document).ready(function() { $("#form").submit(function() { var formData = $("#form").serialize(); $.getJSON("callbacktest.php", formData, processData); function processData(data) { if (data.status=="pass") { $("#form").html("<h1>Success</h1>"); alert(data.name); } else { $("#form").html("<h1>Fail</h1>"); alert("fail"); }; }; return false; }); // end submit }); //end ready </script> Code (markup): The above should work! and I have tested it as well... Find more about getJSON here http://api.jquery.com/jQuery.getJSON/