0

Ok so I know how to get an external php file and display it after the button is clicked. However now I want to try and pick a certain function from that php file, is this possible?

This is my index.php

<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("POST","test.php",true;
xmlhttp.send(null);
}
</script>

<button type="button" onclick="loadXMLDoc()">Load results</button>
<div id="myDiv"></div>

and this is my external php page. test.php

<?php
function show() {
}
?>

<?php
function update() {
}
?>

<?php
function delete() {
}
?>

1 Answer 1

1

with jQuery you can solve your problem easily. This will be the ajax request:

function DoRequest(){
    $.get('test.php', {'action': 'save'}, function(response){
        document.getElementById("myDiv").innerHTML = response;
    });
}

$.get receive some parameters. The first one is the URL of the target file of the request, the second one is the parameters or data that you want to send to that file and the third one is a callback (or just function) that will be called when the request is done.

Your button:

<button type="button" onclick="DoRequest()">Load results</button>
<div id="myDiv"></div>

In your php file you will receive the 'action' parameter of your ajax request:

<?php
    $action = $_GET['action'];

    switch($action){
       case 'save':
                   echo Save();
                   break;
       case 'update':
                   echo Update();
                   break;
       case 'delete':
                   echo Delete();
                   break;
    }

    function Save(){
       return "Save function.....";
    }

    function Update(){
       return "Update function.....";
    }

    function Delete(){
       return "Delete function.....";
    }

?>

I think you can solve your problem with that. Hope it works for you.

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

2 Comments

Thank you. That works lovely. Just curious would it be the same even if the functions are in a class??
Hi. Of course, you can do the same if you have a PHP class. You only have to create an object (instantiate) of your class and just call the function of your class in each case of the switch.

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.