2

I am bringing some data from the database, and some of them have HTML tags such as "<p>Hello</ p>". However, when step data through to return it shows json_encode in "&lt;p&gt;Hello&lt;/p&gt;". What should I do to return the same data that was saved in the database?

PHP:

$retorna = array(
    'conteudo_programatico' => $conteudo_programatico,
    'investimento' => $investimento,
    'coordenacao' => $coordenacao,
    'importante' => $importante
);

echo json_encode($retorna);

AJAX:

$(function(){
    $("button").click(function(){
        var id = $(this).attr("id");
        $.ajax({  
            type: "POST",
            data: {id: id},
            url: "paginas/ajax/form.php",
            dataType: "json",
            success: function(data){
                $("#cursos").slideDown();
                $(".call-conteudo").text(data['conteudo_programatico']);
                $(".call-investimento").text(data['investimento']);
                $(".call-coordenacao").text(data['coordenacao']);
                $(".call-importante").text(data['importante']);
            },
        });
    });
});
1
  • 1
    json-encode doesn't do html encoding. if those chars are coming through as html entities, then something ELSE is doing the encoding, long before json_encode() ever got close to them. Commented Apr 16, 2015 at 18:38

1 Answer 1

3

The problem is your use of jQuery's .text():

$(".call-conteudo").text(data['conteudo_programatico']);
// etc.

According to the manual:

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), does not interpret the string as HTML

...

The code $( "div.demo-container" ).text( "<p>This is a test.</p>" ); will produce the following DOM output:

 1 <div class="demo-container">
 2   &lt;p&gt;This is a test.&lt;/p&gt;
 3 </div>

You need html():

$(".call-conteudo").html(data['conteudo_programatico']);
// etc.
Sign up to request clarification or add additional context in comments.

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.