You're on the right path, although as others have mentioned, it seems like you are using a MVC framework for your website and it is including the content of your webpage after displaying the JSON string. jQuery/JavaScript cannot parse JSON if there are other random text or characters in the response. You will need to use exit; or die(); after the JSON is echo'ed as the following example shows...
public function testJSON(){
$name = $this->request->data['name'] . '-Sue';
$hobby = $this->request->data['hobby'] . ' for donuts';
$data = array( 'name' => $name, 'hobby' => $hobby);
// Will halt the script and echo the json-encoded data.
die(json_encode($data));
}
Also, you will want to make sure that jQuery is parsing the response as JSON. By default it will attempt to make an intelligent guess of which type of data is being returned, but you cannot always rely on that. You should add the dataType option to the AJAX call like in the following example...
<script type="text/javascript">
$(document).ready(function(e){
$('#myButton').click(function(e){
// It is best practice to "preventDefault" before any code is executed.
// It will not cause the ajax call to halt.
e.preventDefault();
var formdata = {name: 'Alan', hobby: 'boxing'};
var submiturl = 'http://localhost/cake/gronsters/testJSON/';
$.ajax({
type: "POST",
url: submiturl,
data: formdata,
// This is the proper data type for JSON strings.
dataType: 'json',
success: function(message){
// JSON is parsed into an object, so you cannot just output
// "message" as it will just show "[object Object]".
console.log(message.name);
}
});
});
});
</script>
I've included some comments in the code to help better explain. Hopefully this will help you out a bit more. You also do not need to using the full $.ajax function unless you plan on using error handlers or any other of the more advanced options within that function. Alternatively, you can shorten your code by using $.post and accomplish the same as your original example with less code.
<script type="text/javascript">
$(document).ready(function() {
$('#myButton').click(function(e){
e.preventDefault();
var formdata = {name: 'Alan', hobby: 'boxing'};
var submiturl = 'http://localhost/cake/gronsters/testJSON/';
$.post(submiturl, formdata, function(message) {
console.log(message.name);
});
});
});
</script>
More options and usage information about $.ajax jQuery.ajax();
More information about $.post jQuery.post();