Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JavaScript from PHP file through AJAX?

How to do this?

  1. We have button with onclick event, that sends a query using AJAX to PHP file.
  2. PHP file has this JavaScript: echo '<script>alert("hello");</script>';
  3. When pushing onclick event button, JavaScript doesn't work. I don't see a "hello" message.

Does anybody knows how to execute JavaScript from PHP? I need exactly this one. I know that all JavaScript should be executed on the AJAX level. But the situation demands to execute a JavaScript, that PHP returns as response.

Best regards

like image 267
ilnur777 Avatar asked Sep 18 '26 05:09

ilnur777


1 Answers

You cannot execute Javascript from PHP since PHP executes on the server side while JS on the client side. You need to eval the returned Javascript code on the client side.

You can do this in your AJAX callback function:

$('#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);
        }
    })
});
like image 55
xbonez Avatar answered Sep 19 '26 19:09

xbonez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!