Jump to content

How return json object, not string to ajax?


someguy321

Recommended Posts

I have the following code and it always says it's a string! How do I make it see it as a json object?

 

<?php
    //We'll return a json object from post request
    if ( !empty( $_POST ) )
    {
        $arr = array ('status'=>1,'message'=>'Some message');
        
        echo json_encode($arr);
    }
    else
    {
        ?>
        <input type="button" value="submit" id="submit" />
        <script type="text/javascript" src="/scripts/jquery-1.4.2.js"></script>
        <script>
            var submit = document.getElementById( "submit" );
            
            submit.onclick = function()
            {
                $.post( "test.php", 
                    function(data)
                    {
                        /*
                         * This always prints as:
                         *    {"status":1,"message":"Some message"}
                         *    string
                         *    Code: undefined
                         *    Message: undefined
                         */
                        alert( data + "\n" + typeof( data ) + "\nCode: " + data.status + "\nMessage: " + data.message );
                    }
                );
            }
        </script>
        <?
    }
?>

 

What do I do to make it a json object?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.