1

I am trying to execute PHP function(server-side) on button click in html (client-side). I want to pass a parameter to PHP function as name & in return I want output as Hello name. I tried, but it's not showing,

Server-side
The PHP file name is "name.php" having function greet() with parameter $name is as follows:

<?php
function greet($name)
{
   echo "hello $name";
}
?>

Client-side
The HTML file consists of a button "Click me" which should send the name John to PHP page, and the greet() function should execute and output should display at client side as "Hello John" is as follows:

<html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
  $("#button").click(function(){
    $.ajax({
      type: "POST",
      url: "name.php",
      data: { name: "John" }
    }).done(greet(data) 
    {
      alert( "Data Saved: " + data);
    }); 
 });
});
</script>

<input type="button" id="button" value="Click me">

</html>

I have used Ajax method for calling PHP function if any other POST method can give output, then please let me know.
Can someone please help to how to get output from PHP function to client-side on button click.

Qirel
  • 25,449
  • 7
  • 45
  • 62
David
  • 366
  • 3
  • 22
  • 1
    `done(greet(data)` - You can't call PHP functions directly from JS. When you make the ajax call to `name.php`. That file (the PHP file) needs to call that function and return the value to your ajax callback. Your ajax response will simply be the outputted data from the PHP file, nothing else. – M. Eriksson Mar 08 '19 at 06:16
  • First you need to call your ajax on button click move your ajax code to `$("#button").click(function(){ //yourajaxcode });` block – Saad Suri Mar 08 '19 at 06:16
  • 1
    If all you want to do is display "Hello John" (or "Hello + whatever $name equals") ... do you need to do ANYTHING client side? Why can't you just `` in-line (changing "greet()" so it just concatenates the string, instead of calling "echo")???? – paulsm4 Mar 08 '19 at 06:48

2 Answers2

1

You cannot call the PHP function from JavaScript, even from Ajax. What Ajax does, is ask for data that is outputted from a PHP file. So you will need to call the function in your name.php, which gives the output - which you can then print in PHP.

Ajax will only fetch the string that was printed from PHP.

Also note that you do not need to close PHP by doing ?> at the end of the file, unless there's some HTML or the likes coming after.

Server-side, you'll do something like this

<?php
// Define the function
function greet($name) {
   return "Hello $name";
}

// Call the function with the value sent from Ajax - this output is what Ajax fetches
echo greet($_POST['name']);

Client side you would do something like

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
    $("#button").on("click", function() {
      $.ajax({
        type: "POST",
        url: "name.php",
        data: { name: "John" }
      }).done(data) {
        alert("Data Saved: " + data);
      }); 
    });
</script>

<input type="button" id="button" value="Click me">

Then data will contain all the string that was printed from your PHP file. If you expect an array, you need to convert it into a JSON.

Qirel
  • 25,449
  • 7
  • 45
  • 62
  • Thanks Qirel, I used the same code, which you mentioned. I created PHP script on server side and on client-side the ajax code in html file. But it is not executing. – David Mar 08 '19 at 06:53
  • Check your console in your browser for client-side errors, and PHP error logs on your server for clues. – Qirel Mar 08 '19 at 07:09
  • Hey Qirel, as you said I checked on console and found this error, "_Access to XMLHttpRequest at 'file:///C:/Users/niranjan.rao/Documents/Ampps/www/name.php?name=John' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https._" On the Client side, on the click event of button, in the ajax apart, I'm passing the php file path as **url : "192.168.0.101:80/name.php"** in the url. – David Mar 08 '19 at 08:38
  • Just do `url: "/name.php",` no need to provide your (local) IP. – Qirel Mar 08 '19 at 10:01
  • Thanks Qirel, but is it possible that you copy the client side script (_mentioned in your answer_) & save it in **" .html "**, then on button clicked by you, the ajax code will try to hit **php** page which is on my machine, will execute the function and output will display on your machine in your HTML page. – David Mar 09 '19 at 07:54
0

First you need to bind your ajax call on your button click, so when the button click it will trigger the ajax call.

$(document).ready(function()
{
// when button click it will trigger ajax call
 $("#button").click(function(){
     $.ajax({
         type: "GET",
         url: "name.php",
         data: { name: "John" },
         success: function(data) {
            // on successfull return it will alert the data 
            alert("Data saved: " + data);
         }    
      });
  });
});

And in your name.php

 <?php
    // get your data you send from ajax 
   $name = $_GET['name'];
   // it will echo the "hello $name" and return it
   greet($name);

   function greet($name)
   {
     echo "hello $name";
   }
 ?>
Muhammad Shareyar
  • 772
  • 2
  • 7
  • 21