Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 254
Jamesypoo Avatar asked Jan 17 '15 19:01

Jamesypoo


People also ask

How do I return a response from AJAX?

What you need to do is pass a callback function to the somefunction as a parameter. This function will be called when the process is done working (ie, onComplete): somefunction: function(callback){ var result = ""; myAjax = new Ajax.

Does AJAX return anything?

ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.

Does AJAX return a promise?

ajax returns a promise object, so that we don't have to pass a callback function.

Can we use AJAX in JavaScript?

AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)


1 Answers

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> ";
?>
like image 91
Cliff Burton Avatar answered Oct 21 '22 04:10

Cliff Burton