I have a jquery script in my file that says this:
<script type="text/javascript">
$(document).ready(function(e){
$('#myButton').click(function(e){
var formdata = {name: 'Alan', hobby: 'boxing'};
var submiturl = 'http://localhost/cake/gronsters/testJSON/';
$.ajax({
type: "POST",
url: submiturl,
data: formdata,
success: function(message){
console.log(message);
}
});
e.preventDefault();
})
});
Then I have a php script at testJSON that says this:
public function testJSON(){
$name = $this->request->data['name'] . '-Sue';
$hobby = $this->request->data['hobby'] . ' for donuts';
$data = array( 'name' => $name, 'hobby' => $hobby);
echo json_encode($data);
}
The place where console.log looks for message gives me {“name”:”Alan-Sue”,”hobby”:”boxing for donuts”}, which seems correct, except that it’s immediately followed by the full html of my web page. And if I try console.log(message.name) it says ‘undefined.’
What’s going on here?
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;ordie();after the JSON is echo’ed as the following example shows…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
dataTypeoption to the AJAX call like in the following example…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
$.ajaxfunction 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$.postand accomplish the same as your original example with less code.More options and usage information about
$.ajaxjQuery.ajax();More information about
$.postjQuery.post();