Viewing 5 replies - 1 through 5 (of 5 total)
  • catacaustic

    (@catacaustic)

    You’d need to set up your function to return the correct HTTP headers for browsers to know that the text is JSON code an dnot HTML or plain text. Next thing to do is output the JSON as plain text. The final step is to call die(); when it’s all done so that you don’t output the rest of the WordPress page templates.

    Thread Starter 9tontruck

    (@9tontruck)

    Thanks for reply. die() in my page kills side bar and footer but it does not kill header. I think die() should be called before header is drawn but writing “die()” in my page does not seem to be drawn earlier than the header..

    catacaustic

    (@catacaustic)

    Then you are not sending the JSON at the right spot. You can’t just add JSON as page content and have it displayed. You have to use either an admin or public-facing AJAX call for that:

    http://codex.wordpress.org/AJAX

    JSON and anything AJAX or JavaScript doesn’t follow the same template method that a standard HTML page does.

    Thread Starter 9tontruck

    (@9tontruck)

    Thanks for the links. I learned a lot. I actually tweaked the sample code little bit so that php can make a http post call like this:

    in function.php

    class AjaxTools{
        static function callAjax($url, $data) {
            $options = array(
                'http' => array(
                    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                    'method'  => 'POST',
                    'content' => http_build_query($data),
                ),
            );
            $context  = stream_context_create($options);
            $result = file_get_contents($url, false, $context);
    
            var_dump($result);
        }
    }

    in main-page

    [php]
    
    $data = array('action' => 'my_action', 'whatever' => '100');
    AjaxTools::callAjax('http://localhost/wp/connect-update', $data);
    
    [/php]

    in connect-update page

    [php]
    
    add_action( 'wp_ajax_my_action', 'my_action_callback' );
    
    function my_action_callback() {
    	global $wpdb; // this is how you get access to the database
    
    	$whatever = intval( $_POST['whatever'] );
    
    	$whatever += 10;
    
            echo $whatever;
    
    	die(); // this is required to return a proper result
    }
    
    do_action('wp_ajax_my_action');
    
    [/php]

    But the returned data from the post call still contains all contents before the page which is header and $whatever. How can kill header print?

    Thread Starter 9tontruck

    (@9tontruck)

    nevermind. I got it 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Returning JSON only page’ is closed to new replies.