-4

Possible Duplicate:
Creating jQuery AJAX requests to a PHP function

I am trying to run a really simple formula,

Call a web page, and every few seconds or so Ajax calls a php function to echo "Hello World"

<?php
function test(){
     echo "Hello World";
}
?>
<script type="text/javascript">

function testingTimer()
{
    //CALL PHP FUNCTION CALLED TEST
}

setInterval('testingTimer()',5000);
</script>

All I need is the code that calls the already declared php function.

Community
  • 1
  • 1
Laura Smith
  • 35
  • 1
  • 4

6 Answers6

2

You cannot call that directly. Write code of AJAX and call URL like myfile.php?action=test and in file myfile.php write if action GET variable is equal to test then call that function and don't forget to exit code to prevent any other output.

Riz
  • 9,703
  • 8
  • 38
  • 54
0

AJAX does not have the ability to call an arbitrary php function on its own. AJAX allows you to connect to a given page and request data. That being said, you can use AJAX to load a given page and all that page does is call your test function:

NullUserException
  • 83,810
  • 28
  • 209
  • 234
CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
0

Google on how to do ajax calls. It's basic knowledge explained in too many tutorials, and varies depending on if you are using a framework or not, and which.

Sven
  • 69,403
  • 10
  • 107
  • 109
0

You can post something for example :

function testingTimer()
{
     $.post(URL,
            {
            foo : 'foo'
            }
     );
}

and in php check post:

if (isset($_POST['foo']))
    test();
0

You should use jQuery to use the ajax function.

You should not use a setInterval, but a setTimeout after the response of server because if the server take more than 5000 seconds to respond, then you'll have two requests at the same time. If you want to put a timeout, you can always see the abort function on the jqXHR Object.

For example, you could do:

function refresh() {
    $.ajax({
        type: 'GET',    // can be POST or GET
        url: 'page.php' // php script to call
    // when the server responds
    }).done(function(response) {
        console.log(response);
        // call your function automatically
        setTimeout(refresh, 5000);
    });
}
SuperSkunk
  • 1,268
  • 12
  • 24
0

Based on your example code I assume you're trying to do this all within a single file. The issue you have is that PHP is run server side before/as the page loads. Once loaded it cannot be re-executed without a refresh.

You need to have your PHP in a separate file so that it can be called over HTTP by AJAX and return a response.

So something like this (if using jQuery):

$.ajax('helloworld.php', function(data){
    alert(data);
}, 'html');

Should popup with hello world if implemented correctly.

diggersworld
  • 12,770
  • 24
  • 84
  • 119