Jamesypoo
Jamesypoo

Reputation: 110

Return javascript with AJAX

A developer recently told me I could make ajax requests to php pages, have them return javascript methods and then have the client execute those methods. How is this done? A link to a relevant resources would be great too.

Edit

5 years wiser, I would now try pretty hard never to do this. Any mechanism of this kind opens too much risk of cross-site scripting attacks. It's far safer to disable all inline javascript using appropriate headers, and find another way to achieve the desired functionality. If dynamically generated scripts are really required, they can be assembled on the server and included as external scripts:

<script src=/dynamic-script.php?param1=blah&param2=ayyylmao></script>

In this example dynamic-script.php would use the parameters passed to it to generate the required javascript.

Upvotes: 6

Views: 87

Answers (1)

Cliff Burton
Cliff Burton

Reputation: 3744

An example could be done with jQuery (a javascript library).
If you call an ajax request:

$.ajax({
    url:"phpfile.php",
    type:"post",
    data: {id: 4},
    async:true,
    success: function(data) {
        $("div").html(data);
    },
    error: function() {
        alert("Error");
    }
});

and in the phpfile.php you echo some javascript code it can be executed:

<?php
echo "
<script>
jQuery(document).ready(function() {
    $(\"#someDiv\").click(function() {
        alert(\"#someDiv clicked\");
    });
});
</script> ";
?>

Upvotes: 2

Related Questions