1

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

1
  • because you are calling a page not function.to do that i think you need to have some MVC architecture. Commented Nov 29, 2014 at 5:37

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

2 Comments

So is there any way of call function using ajax
You could have a page that calls the function, but there's no direct way to call PHP functions from JavaScript.

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.