pythonsimplehttpserver

Why do I get a 501 error when submitting an AJAX POST request to a SimpleHTTPServer?


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


Solution

  • 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/