pl0u
pl0u

Reputation: 375

Problems calling PHP function from Javascript

[Solved] check out the link by Jonathan M

Reason: SimpleHTTPServer doesn't handle POST

Other tips: I ran into another issue where the server was returning the entire .php file, instead of the value. This is because python server doesn't handle php by default. An easy get-around was to spin up a php server via php -S youraddress:port


I'm having problems calling php functions from javascript. I have tried some of the suggestions on stackoverflow without any success. I'm not sure what I'm missing here...

I'm writing to submit a simple POST request to my php file, but I get this error in my browser console:

POST http://localhost:8000/myphp.php 501 (Unsupported method ('POST')) 

I'm writing a single page web app that is currently running on my local machine with a simple server running at /projecthome/

 python -m SimpleHTTPServer

My files are laid out like this:

/projecthome/index.html
/projecthome/myphp.php
/projecthome/js/myjs.js

index.html:

...
<script src="js/myjs.js" type="text/javascript"></script>
<script>
    $(function() {
        run();
    });
</script>
...

myjs.js:

function schemaCreationTool() {
var id='someID';

$.ajax({
    url: 'myphp.php',
    type: 'POST',
    data: {id:id},
    success: function(data) {
        console.log(data);
    }
});
}

myphp.php:

<?php

if (isset($_POST['id'])) {
    select($_POST['id']);
}

function select($x) {
    echo "The select function is called.";
}
}

I followed solutions from these posts:

calling a php function in javascript

Call php function from javascript and send parameter

Upvotes: 2

Views: 689

Answers (1)

Jonathan M
Jonathan M

Reputation: 17441

Python's SimpleHTTPServer doesn't natively support POSTs. You can extended it to do so with this little handler:

http://georgik.sinusgear.com/2011/01/07/how-to-dump-post-request-with-python/

Upvotes: 5

Related Questions