Djave
Djave

Reputation: 9349

AJAX request only retrieves JavaScript output

I have the following JavaScript AJAX call

$.ajax({
    type: "POST",
    url: "ajax.php",
    data: { "ajax" : "true" },
    success: function(data){
        $("#careers-content").html(data);
    }
});

This works great, when ajax.php is

<h3>Candidate Profile</h3>
<ul>
    <li><?php echo $role; ?></li>
</ul>

Then I get back

Candidate profile

  • Some role

However if ajax.php is:

<h3>Candidate Profile</h3>
<script type="text/javascript">document.write("This file is running JavaScript!");</script>
<ul>
    <li><?php echo $role; ?></li>
</ul>

Then the total output I get is:

This file is running JavaScript!

With none of the other h3, ul or li tags. Is there an argument that I currently can't find in jQuery's ajax function to stop this happening? How can I AJAX in the following:

Candidate profile

This file is running JavaScript!

  • Some role

i.e. import the page and javascript and run the javascript in the ajax.php page

Upvotes: 0

Views: 45

Answers (1)

Razvan B.
Razvan B.

Reputation: 6771

This is because document.write overwrites everything you have in that file, leaving the only output to This file is running JavaScript!

You can do something like this or similar:

$(document).find("h3").after("This file is running JavaScript!")

And you will have this output

Candidate profile

This file is running JavaScript!

  • Some role

Here is a demo

Upvotes: 3

Related Questions