slash89mf slash89mf - 10 months ago 44
Ajax Question

Execute php file in ajax

I have this php file:


function bb(){
system( 'python');
echo "done";


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" );

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.

Answer Source

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.