1

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?

3
  • Is that all the code in testJSON? Commented Aug 7, 2012 at 22:26
  • You might want to set "dataType: 'json'" when setting up your ajax call. I know jQuery has an intelligent guess at the type, but who knows, maybe it's doing it wrong. Commented Aug 7, 2012 at 22:31
  • Yes, that's all -- it's just a function in the controller of my cake php app Commented Aug 7, 2012 at 23:39

3 Answers 3

3

it sounds like your /testJSON/ page is outputting more than just whats written in your public function. if you are using an mvc or any kind of framework, you must immediately exit or die after that echo json_encode, otherwise the other part of the page will still render, probably.

Sign up to request clarification or add additional context in comments.

1 Comment

I can't test right now but that sounds right. I'm using cake php.
2

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();

1 Comment

Thanks -- I'll try that when back at my computer.
0

Parse the message variable as json before trying to log message.name.

data = $.parseJSON(message);
console.log(data.name);

Also do an exit in the php script after the echo statement and check..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.