Yawz Yawz - 3 months ago 10
Ajax Question

Execute javascript in a file called through post request

I have a php file(index.php) that contains a button, wherein if that button is clicked, it will trigger a javascript function that will post request on a php file(login.php). Now on that login.php if a condition is true, I will be redirected to a url, using javascript. For this example, I will not ask how to redirect but just to perform a simple

alert()
on that login.php;

I found an answer saying I should so this:

<?php // some php code
// php condition is true {
echo "<script type="text/javascript">
alert('Alert worked.');
</script>";
// }
// more php code
?>


It performs the
echo
but never executes the script.

How could I execute javascript in a file(that is called through post request).

Answer

To make this works using AJAX you should add this response to DOM page. For example:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
    $.get('/test.php', function (script) { 
        $('body').append(script);
    })
</script>
Comments