Sjenkie
Sjenkie

Reputation: 237

Javascript not working when echo'd by php

I have the problem when i echo this:

echo "Logged in! <script> alert('hello'); </script>";

The message "Logged in!" appears, but not the alert. How can i fix it so i get the alert? I can't use header(); because i already echod things out!

I also tried multiple thing like:

echo "Test message <script> window.location.href = 'index.php';"

Same thing again, Test message was echo'd, but the script wasn't run.

I hope someone can help me!

Edit:

NOTE: All of this code is in a xml file that i get that response of and put that in a div. So the script is in a message that i get with responseXML and output the data in a div.

Question i have in 1 sentence: How can you run a javascript function in a ajax call without jquery?

Upvotes: 0

Views: 1138

Answers (3)

Chris
Chris

Reputation: 3338

Your PHP looks fine, but you might need to change the way that you collect the JavaScript.

Consider this example: http://jsfiddle.net/0vcewvkc/1/

If you are collecting JavaScript only, you can wrap the response in a jQuery tag ($()), and then append it to your document.

$("#go").click(function() {  // call the function here
    // your ajax code would go here, but either way you will end up with a string of JavaScript
    var response = '<script>alert("hi");</' + 'script>';

    // use jQuery to append this script to your document's body, like so:
    $(response).appendTo(document.body)        
});

Update

To do this without jQuery, the end of your AJAX call would have this code:

    var response = 'alert("hi");';  // note that we have removed the <script> tag
    var s = document.createElement("script"); 
    s.innerHTML = response;
    document.getElementsByTagName('body')[0].appendChild(s);

Upvotes: 0

Gil
Gil

Reputation: 1804

I'm guessing you call this script through ajax after the page is already loaded. In this case it's not surprising the script isn't running because the browser runs the scripts as it reads them and isn't on standby for another script tag to appear.

If this is the case, you can solve this by adding some event listener or even better, call a desired function in the end of the ajax response.

Upvotes: 1

Dev Man
Dev Man

Reputation: 2137

try the following this should work

<?php 
echo 'Logged in ';
?>
<script> alert("hello")</script>;
<?php
  // the rest of your php code
?>

Upvotes: 0

Related Questions