0

I want to call a php function after an event listener within the same document. So I have PHP, HTML and all in the same file. I looked in this thread: using jquery $.ajax to call a PHP function. However in the url it is a separate file.

document.getElementById("categoryone").addEventListener("change", function(event)
{
    $.ajax({ url: 'pageTwo.php',
      data: {action: 'test'},
      type: 'post',
      success: function(output) {
                 alert(output);
               }
    });
});

And my PHP looks like this:

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'test' : test();break;
    }
}
Asur
  • 3,727
  • 1
  • 26
  • 34
hanbri
  • 9
  • 1
  • 1
    So what is the error? – Rotimi Mar 25 '18 at 16:14
  • 1
    it should be a separate file. Otherwise your HTML will be output and mess up your response. `However in the url it is a separate file.` If it's in the same file, you will get the html from that file, anything that is output is returned in the response from the server. – ArtisticPhoenix Mar 25 '18 at 16:14
  • Side note - as you are using jquery, why not shorten to `$("#categoryone").on("change", function(event) { ...` or `$("#categoryone").change( function(event) { ...`? – Sean Mar 25 '18 at 16:22
  • It don't work as I have it. Can you have the php in the same file? Or are you forced to have it in a seperate file? What should I put I the url to call the php function – hanbri Mar 25 '18 at 16:26
  • Do you understand that PHP always runs on the server, before the page is sent to the client? If you "call a PHP function" that call runs the full page (not just that function) *on the server* and sends the results back as a response. Using F12 in the browser and watching the Network tab might make this more clear. – Dave S Mar 25 '18 at 20:25

0 Answers0