niko619
niko619

Reputation: 453

Get a function from an external php page using Ajax/Javascript

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() {
}
?>

Upvotes: 0

Views: 832

Answers (1)

law.vzmk
law.vzmk

Reputation: 144

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.

Upvotes: 1

Related Questions