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¶m2=ayyylmao></script>
In this example dynamic-script.php would use the parameters passed to it to generate the required javascript.
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.
ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.
ajax returns a promise object, so that we don't have to pass a callback function.
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)
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> ";
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With