Using json_encode to send html returns “null” string at the end

I’m using this to load php functions and send them to javascript in a plugin, like:

function me_nav_query_submit() {

    $urlcall = nav_me_paises(); /* fetches a large html string */
    $response = json_encode($urlcall); /* encode to display using jQuery */

    //header( "Content-Type: application/json" );
    echo $response;

    exit;
}

I insert the html on the page, using

Read More
function(response) {
    jQuery('#navcontainer').html(response);
}

and everything works fine, except that i get a “null” string at the very end of the result.

json_encode() documentation talks about null strings on non-utf-8 chars, but this doesn’t seem to be the case. I’ve also tried using utf8_encode() with no success. I’ve read a bunch of other questions here on SO, but most of them either talk about one given value returned as null or bad UTF-8 encoding and in my case everthing just works, and then append “null” to the end.

note: Defining that header() call is recommended in the WP Codex, but i commented it because it was giving a “headers already sent” error.

Any ideas?

EDIT this is the function called:

function nav_me_paises() {
    ?>
   <ul class="navcategorias">
        <?php $tquery = $_POST['wasClicked']; ?>
        <?php $navligas = get_terms($tquery,'hide_empty=0') ?>
        <?php foreach ($navligas as $liga) : ?>
            <?php $link = get_term_link($liga); ?>
            <li class="liga"><a href="<?php echo $link; ?>" ><?php echo $liga->name; ?></a></li>
        <?php endforeach; ?>
    </ul>
    <?php
}

Related posts

Leave a Reply

3 comments

  1. nav_me_paises() is not returning anything. the html block is treated as output!

    function nav_me_paises() {
     $output = '<ul class="navcategorias">';
     $tquery = $_POST['wasClicked'];
     $navligas = get_terms($tquery,'hide_empty=0')
     foreach ($navligas as $liga) {
       $link = get_term_link($liga);
       $output .= '<li class="liga"><a href="'.$link.'" >'.$liga->name.'</a></li>';
      }
      $output .='</ul>';
      return $output;
    }
    
  2. nav_me_paises() doesn’t return anything. Passing this “nothing” to json_encode() gives "null". Convert the function so that it returns the HTML instead of outputting it

    function foo()
    {
    };
    
    var_dump(json_encode(foo()));
    
    string(4) "null"
    
  3. Also, if it’s just plain HTML, why json it? Just send it to JS, it will be a string stored in a variable, and you handle it normally.

    I presume all you wanna do is put that HTML inside some div, because you’d not parse it into a DOM and process its elements… because if u’d do that u’d not use HTML for it.