How to return JavaScript from a PHP file via AJAX?

How to do it?

  • We have an onclick event button that sends a request using an AJAX file in PHP.
  • The PHP file has this JavaScript: echo '<script>alert("hello");</script>';
  • When you click the event button onclick JavaScript does not work. I do not see the message "hello."

Does anyone know how to execute JavaScript with PHP? I need this one. I know that all JavaScript has to be executed at the AJAX level. But the situation requires JavaScript to execute, that PHP is returning as an answer.

Regards

+3
source share
3 answers

Javascript PHP, PHP , JS - . eval Javascript .

AJAX:

$('#yourButton').onclick(function(){
    //make your ajax request
    $.ajax({
        url : "url",
        success : function(resp){
            //resp is the javascript code sent back from PHP
            //eval it
            eval(resp);
        }
    })
});
+3

javascript :

"alert(\"hello\");"

:

var js = ajax.r;

:

eval(js);

, .

0

Eval will work, but be careful.

If custom content can get into your eval statement, someone can use it to create a malicious script for your site.

Just a head.

0
source

All Articles