Page 1 of 1

PHP AND JSON problem..

Posted: Sat Aug 20, 2011 8:32 am
by tanvirtonu
I am new to JSON and PHP. I cant get the data with JSON object using jquery. Cud anybody pls have a look at y code-

Code: Select all

<html>
<head>
<script type="text/javascript" src="jquery-1.6.1.js"> </script>
<script type="text/javascript"> 
$(document).ready( function () {
$("form").submit( function () {
$.post(
	"ajax.php",
	$("#myFrm").serialize(),
	function(result){
		alert(result.name);  // nothing showing here....
		//$("#ajaxDiv").html(result);
					} ,	"json"					
	  );
return false;
});
});
</script>
</head>
<body>
<div id="ajaxDiv"> AJAX REQUEST</div> <br>
<form id="myFrm" method="post">
<input type='text' name='a' value='TANVIR' /> 
<input type='text' name='b' value='EMRAN' /> 
<input type='submit' />
</form>
</P>
</body>
</html>
this is the ajax.php

Code: Select all

<?php
 $json = array(  
              'name' => 'HOSSAIN',  
              'age' => '22',  
              'location'  => 'DHAKA'  
          );  
 echo json_encode($json);

?>

Re: PHP AND JSON problem..

Posted: Sat Aug 20, 2011 8:56 am
by genix2011
Hi,

tried your code, and it works on my server.
Try using Firebug for debugging, there you could then do console.log(result);, and see all connections.

Greets.

Re: PHP AND JSON problem..

Posted: Sun Aug 21, 2011 5:49 pm
by tanvirtonu
I get an Error: SyntaxError: JSON.parse: unexpected character, IF I use any of the the first two //commented lines.
But if I remove them, it works. Whats the problem with these lines? What can / cant I use in file with JSON...

Code: Select all

<?php
//print_r($_POST);  - this line gives an error
//echo " HELLLOOOOOO WORLD - THIS IS AN AJAX TEST";    - this line gives an error

 $json = array(  
              'name' => 'HOSSAIN',  
              'age' => '22',  
              'location'  => 'DHAKA'  
          );  
 echo json_encode($json);

?>

Re: PHP AND JSON problem..

Posted: Mon Aug 22, 2011 7:12 am
by genix2011
Hi,

the two lines are outputting something, so that is not an valid json output anymore.
Your javascript ajax handler awaits an valid json response from the server.

Greets.

Re: PHP AND JSON problem..

Posted: Mon Aug 22, 2011 1:27 pm
by tanvirtonu
Thats wat I wanted to know....what are the things that are valid as output...?
What can / cant I use in file with JSON to have a valid output..

Re: PHP AND JSON problem..

Posted: Tue Aug 23, 2011 11:59 am
by genix2011
Hi,

look into the json specifications, normally json is something like that:

Code: Select all

{
    "key": "value",
    "array": ["el1","el2","el3"]
}

Re: PHP AND JSON problem..

Posted: Tue Aug 23, 2011 1:42 pm
by Weirdan
you can have anything you want in the php file, as long as it outputs valid json and nothing else.