slash89mf
slash89mf

Reputation: 1067

Execute php file in ajax

I have this php file:

<?

function bb(){
system( 'python my_script.py');
echo "done";
}

bb();
?>

I would like to execute this, using ajax. I do it this way:

<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
          data : { },
          url  : 'action.php',              // <=== CALL THE PHP FUNCTION HERE.
          success: function ( data ) {
            alert( data );               // <=== VALUE RETURNED FROM FUNCTION.
          },
          error: function ( xhr ) {
            alert( "error" );
          }
        });
}
    </script>

This is executed when a button is clicked:

<button type="button" class="btn btn-outline-danger" onclick="myAjax()">Primary</button>

The problem is that i get always error case. Even if my php file should execute only echo (i.e. deleting system). How can i solve that?

Using Chrome inspector, under Network tab i get this error:

jquery.js:4 XMLHttpRequest cannot load file:///Users/Antonio/Desktop/script/action.php.Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

but the file is accessible using this path.

Upvotes: 0

Views: 1627

Answers (1)

gre_gor
gre_gor

Reputation: 6805

Seeing file:///Users/Antonio/Desktop/script/action.php, I assume you are running your HTML file directly from the local file system.

In this case the, for security reasons, browser doesn't allow access to your local files.
Even if it did, the PHP file wouldn't be executed.

To fix those two issues, you need to run your own local HTTP server, which would execute your PHP files and be accessed through the HTTP protocol.

Either have something like Apache configured to execute PHP or you could just run

php -S localhost:8080

to start a server that servers files from the current directory and executes PHP files.

Upvotes: 1

Related Questions