0

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.

6
  • You need a HTTP server which executes PHP scripts. Commented Sep 19, 2016 at 16:12
  • How can i run my index.html and php script with apache on localhost? Commented Sep 19, 2016 at 16:28
  • There are numerous tutorials on this. Just google it. Commented Sep 19, 2016 at 16:33
  • Just done but i get the same error. @gre_gor Commented Sep 19, 2016 at 17:26
  • If you are running it from a server, AJAX wouldn't try to access file:///Users/Antonio/Desktop/script/action.php but http://localhost/action.php. Commented Sep 19, 2016 at 17:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.