Ashish Srivastava
Ashish Srivastava

Reputation: 11

Call PHP function using javascript ajax

I want call a PHP function using Javascript(No Jquery)

MY php function is

<?php

function helloworld() {
    echo 'Hello Ashish Srivastava';
}
?>

in hello.php file and my JavaScript is

 <script type="text/javascript">
            function getRoute() {
                var hr = new XMLHttpRequest();
                var url = "hello.php";

            hr.open("helloworld", url, true)
                hr.setRequestHeader("Content-type", "application/x-www-from-urlencoded");
                hr.onreadystatechange = function()
                {
                    if (hr.readyState === 4 && hr.status === 200)
                    {
                        var return_data = hr.responseText;
                        alert(return_data);

                    }
                }
                hr.send();
            }
        </script>

and HTMl is

  <input type="button" value="Hello" onclick="getRoute()"/>

bt when i am calling this function i get nothing from server plz help

Upvotes: 1

Views: 2831

Answers (2)

Theodore Enderby
Theodore Enderby

Reputation: 642

My advice would be to pass a query parameter.

Tell Javascript to use a url like

host.local/my-script.php?callFunction=helloWorld

and tell php to process the request object

<?php
    //fetch query parameter
    $callFunction = $_REQUEST['callFunction'];

    //define hello world function
    function helloWorld() {
        echo 'Hello Ashish Srivastava';
    }

    //test the query parameter and call helloWorld
    if($callFunction == "helloWorld")
       helloWorld();

Upvotes: 1

Colin vH
Colin vH

Reputation: 537

AJAX doesn't call PHP functions, it calls pages. E.g., hello.php:

<?php
echo 'Hello Ashish Srivastava';
?>

Upvotes: 1

Related Questions