Jiung Song
Jiung Song

Reputation: 72

How to use ajax to display php code when button is clicked

So I have this code here,

<!-- Ajax!--><button type="button">Click Me</button>
        <p></p>
        <script type="text/javascript">
        $(document).ready(function(){
            $("button").click(function(){
                $.ajax({
                    type: 'POST',
                    url: 'random.php',
                    success: function(data) {
                        $(".mainContainer").text(data);

                    }
                });
            });
        });

but this script doesn't show the markup, just the text.

The php file echo's some HTML Markup such as

<img>
<p>

But the script I have is showing the text WITH the markup but I want the script to show the script WITHOUT the markup (using it).

I'm sure it has to do with the

$(".mainContainer").text(data);

What do I change the "text" to?

First time here at StackOverflow, go easy on me!

Upvotes: 2

Views: 736

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

You need to use html() or innerHTML for setting html content.

$(".mainContainer").html(data);

or

$(".mainContainer")[0].innerHTML=data;

text(text) : 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.( Taken from : http://api.jquery.com/text/#text-text )

Upvotes: 1

dotnetom
dotnetom

Reputation: 24916

Change it to html:

$(".mainContainer").html(data);

You can read more about html function in jQuery documentation

Upvotes: 2

Related Questions