开发者

Call and implement PHP+javascript code by using ajax

开发者 https://www.devze.com 2023-03-11 01:34 出处:网络
I have Mixed Code php + (vanilla javascript) Inside php file . I called the code inside this file by ajax .

I have Mixed Code php + (vanilla javascript) Inside php file . I called the code inside this file by ajax .

Example of the php code

echo "<script type='text/javascript'>
  alert('Hello')
</script>";

The problem is that PHP code is executed, but the JavaScript code is not executed .

Is there a solution for the implementation the two codes PHP + JS using ajax reque开发者_如何学运维st

Please i want vanilla javascript example not any javascript framework


You haven't shown how you are calling this PHP script with AJAX. When you receive the response of the server you need to inject it somewhere into the DOM in order for the script to get included and executed.

For example if you are using jQuery you could use the $.ajax() method like this:

$.ajax({
    url: '/foo.php',
    success: function(result) {
        $('body').append(result);
    }
});

or you could directly have your PHP script return javascript (without the <script> tags):

echo "alert('Hello')";

and then use the $.getScript() method:

$.getScript('/foo.php');


PHP is server-side and JavaScript is client-side. If you execute an AJAX request to a PHP page, that page will render its PHP and send the result back as text (or XML or ...). It's up to the script receiving that output to figure out what to do with it.

In your case, most likely, you're getting a page like this from AJAX:

<script type='text/javascript'>
alert('Hello')
</script>

This is stored as plain text and passed to the callback in your AJAX function. To deal with it, I would recommend some framework implementation of AJAX like jQuery.ajax():

$.ajax({
  url: "test.php",
  success: function(data) {
    alert(data);
    // Expected output - User alert saying
    // <script type='text/javascript'>
    // alert('Hello')
    // </script>
  }
});


You should show the code of ajax call.

Are you using jquery?

This example may help you for javascript ajax

http://www.switchonthecode.com/tutorials/simple-ajax-php-and-javascript

http://www.tizag.com/ajaxTutorial/ajax-javascript.php

jquery ajax

http://api.jquery.com/jQuery.post/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号