6

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.

4
  • I think this is what you're looking for. solutoire.com/2008/06/12/sending-javascript-functions-over-json Commented Jan 17, 2015 at 19:45
  • Doesn't seem to be what I need. I want to know how to execute the javascript that is returned. Commented Jan 17, 2015 at 20:21
  • 1
    No need for ajax. Just dynamically create a <script> element pointing to your PHP script and insert it in your DOM. Commented Jan 17, 2015 at 20:33
  • What is the value of the server sending the client javascript functions? Commented Jan 17, 2015 at 21:27

1 Answer 1

2

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> ";
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.