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?

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.