12

Before someone has a go at me or marks this down, I have looked all over the internet to find out how to do this (including the same question on stackoverflow). I'm new, and I am finding it very hard to learn new concepts so please be easy on me.

What I want to do is call a php script/function on a button click. I have this running in WAMP if that helps. Here's my code:

<?php include 'the_script.php'; ?>

<button type="button" onclick="the_function()">Click Me</button>

the_script.php has this in it:

the_function() {
    echo "You win";
}

Why isn't this working? I've heard about the button being client side etc. and PHP being server-side, which means that you cannot link the two together. I know that you have to use AJAX to make this work, however I legitimately have absolutely no clue how to do it. I've tried googling it etc., however I can't find anything. I know how to use AJAX and call events with it, however I still have no idea how to make it call a PHP script.

Can you please make your answers as clear and simple as possible, I'm new to this

Thanks for the help :)

EDIT ***

For some reason wherever I go everyone's code is different. The way I have been taught AJAX looks completely different. Can you please write it this way so I can understand? Thanks, here's an example:

var request;

if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
} else {
    request = new ActiveXObject("Microsoft.XMLHTTP");
}

request.open('GET', 'file.php', true);

request.onreadystatechange = function() {

    if (request.readyState===4 && request.status===200) {
        do stuff
    }
}

request.send();
Daniel
  • 3,115
  • 5
  • 28
  • 39
  • is the_function() surrounded by ? – bart2puck Dec 31 '14 at 05:21
  • Like @bart2puck asked, is `the_function` is `Javascript` function? If yes then only you can call it. But like you shown in your question it seems `PHP` function so you can't call it in `HTML` button's click event. – Smile Dec 31 '14 at 05:24
  • Php runs on server While js runs on client side, you can not just call php through js. For this you need to make an ajax call – Muhammad Bilal Dec 31 '14 at 05:25
  • I have described [here](http://stackoverflow.com/questions/20738329/how-to-call-a-php-function-on-the-click-of-a-button/34524697#34524697) please check i hope you will be happy. – Mahfuz Ahmed Dec 30 '15 at 07:17

7 Answers7

39

Just try this:

<button type="button">Click Me</button>
<p></p>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){

            $.ajax({
                type: 'POST',
                url: 'script.php',
                success: function(data) {
                    alert(data);
                    $("p").text(data);

                }
            });
   });
});
</script>

In script.php

<?php 
  echo "You win";
 ?>
Community
  • 1
  • 1
Priyank
  • 3,778
  • 3
  • 29
  • 48
  • why do you pass in "data" into the function, I understand everything else except that – Daniel Dec 31 '14 at 05:55
  • @DanielSpajic : when the ajax return with text "You win",it will appear in

    tag,the tag which i wrritten after button

    – Priyank Dec 31 '14 at 05:58
  • @DanielSpajic : you can try once then you understand thoroughly – Priyank Dec 31 '14 at 06:00
  • what am i supposed to pass in as "data" – Daniel Dec 31 '14 at 06:02
  • @DanielSpajic : mo need to pass any things.you just put my first code in index.php and second code in your script.php thats it.and then click the button.it 'll automatically work.just try once. – Priyank Dec 31 '14 at 06:04
  • I did but it didn't work, im pretty sure you have to pass something as "data" – Daniel Dec 31 '14 at 06:08
  • @DanielSpajic can you give your email id.i'll send you my file and explain you.it's very easy concept but very important** – Priyank Dec 31 '14 at 06:09
  • @DanielSpajic : hi i sent you my file.just put this two files in your localhost and run – Priyank Dec 31 '14 at 06:20
  • Thanks it worked, however I don't understand how it worked. you used 'url: 'script.php'' to link the file which contained 'echo "You win";' however how does this affect the jquery code? All you did was link a file, how did you actually get the echoed string from script.php – Daniel Dec 31 '14 at 06:26
  • @DanielSpajic : hmm now i'll explain you – Priyank Dec 31 '14 at 06:28
  • I see that no matter what you pass in it still works, you just used "data". Why is that? I tried removing the text in there, and it didn't return anything – Daniel Dec 31 '14 at 06:30
  • @DanielSpajic : see in line no.9 in index.php,you click the button.which call your ajax with the help of this "$("button").click(function()" which redirect you to script.php with the help of url in ajax.then in script.php we echo and return to our "success: function(data) {" in ajax where you write the return text i.e. "you win" in

    tag with the help of "$("p").text(data);"

    – Priyank Dec 31 '14 at 06:34
  • @DanielSpajic : "data" is just a kind of variable you can give any name – Priyank Dec 31 '14 at 06:36
  • @DanielSpajic Hey did you understand my explanation? – Priyank Dec 31 '14 at 06:48
  • Yes I did, I just dont get how "data" even applies to anything since you never even used it. Normally when you put an argument into a function, you pass it in later. E.g : function the_function (argument) { } the_function(stuff); – Daniel Dec 31 '14 at 06:58
  • Also how do you control the returned data from script.php? at the moment theres only an echoed string, however how do you specify what you want to return from there. For example if i echo 2 strings, how do i return one of them instead of the other – Daniel Dec 31 '14 at 07:00
  • @DanielSpajic : concept is function accept the argument which is return from your script.php by echo.if you have two echo string,it will return both string. – Priyank Dec 31 '14 at 07:07
  • is there a way to choose which returned data you want to accept? – Daniel Dec 31 '14 at 07:21
  • @DanielSpajic : just put echo before string you want to return. for example: "You win"; echo "You loss"; so now you get only "You loss" – Priyank Dec 31 '14 at 07:23
  • Yes but for complex scripts you want to be able to dynamically select your output, so whats a way to access that returned data and select which one you want to use? – Daniel Dec 31 '14 at 07:40
  • @DanielSpajic : then you try my another answer, which is post in same – Priyank Dec 31 '14 at 07:41
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/68050/discussion-between-mightyspaj-and-priyank). – Daniel Jan 02 '15 at 02:20
13

Of course AJAX is the solution,

To perform an AJAX request (for easiness we can use jQuery library).

Step1.

Include jQuery library in your web page

a. you can download jQuery library from jquery.com and keep it locally.

b. or simply paste the following code,

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

Step 2.

Call a javascript function on button click

<button type="button" onclick="foo()">Click Me</button>

Step 3.

and finally the function

 function foo () {
      $.ajax({
        url:"test.php", //the page containing php script
        type: "POST", //request type
        success:function(result){
         alert(result);
       }
     });
 }

it will make an AJAX request to test.php when ever you clicks the button and alert the response.

For example your code in test.php is,

<?php echo 'hello'; ?>

then it will alert "hello" when ever you clicks the button.

akhil.cs
  • 691
  • 1
  • 5
  • 12
  • what does success:function(result) mean? and why do you pass in 'result' as one of the arguments? I don't understand – Daniel Dec 31 '14 at 05:44
  • 1
    result is the variable of what is returned by test.php in his example. in this case it would be the word hello. so alert(result) actuall means alert('hello'). if you put echo "Happy new Year" in test.php alert(result) would show Happy New Year. – bart2puck Dec 31 '14 at 05:47
  • "success" is a callback function, and it will invoked immediately after we got a success full response. the "result" parameter contains the result of test.php (so in this case "hello") – akhil.cs Dec 31 '14 at 06:38
  • @akhil.cs could this be done to output the result in the webpage instead of in an alert? All the answers on this page suggests an alert which I find being a strange choice. – Streching my competence Jan 14 '18 at 09:12
6

You can also use

   $(document).ready(function() {

    //some even that will run ajax request - for example click on a button

    var uname = $('#username').val();
    $.ajax({
    type: 'POST',
    url: 'func.php', //this should be url to your PHP file
    dataType: 'html',
    data: {func: 'toptable', user_id: uname},
    beforeSend: function() {
        $('#right').html('checking');
    },
    complete: function() {},
    success: function(html) {
        $('#right').html(html);
    }
    });

    });
And your func.php:

  function toptable()
 {
  echo 'something happens in here';
 }

Hope it helps somebody

Kumar
  • 1,187
  • 18
  • 31
2

Use jQuery.In the HTML page -

<button type="button">Click Me</button>

<script>
$(document).ready(function() {
$("button").click(function(){
  $.ajax({
    url:"php_page.php", //the page containing php script
    type: "POST", //request type
    success:function(result){
    alert(result);
    }
  });
});
})
</script>

Php page -

echo "Hello";
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
1
First understand that you have three languages working together.

PHP: Is only run by the server and responds to requests like clicking on a link (GET) or submitting a form (POST). HTML & Javascript: Is only run in someone's browser (excluding NodeJS) I'm assuming your file looks something like:

<?php
function the_function() {
echo 'I just ran a php function';
 }

 if (isset($_GET['hello'])) {
  the_function();
  }
   ?>
  <html>
 <a href='the_script.php?hello=true'>Run PHP Function</a>
 </html>

Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST) this is how you have to run a php function even though their in the same file. This gives you a level of security, "Should I run this script for this user or not?".

If you don't want to refresh the page you can make a request to PHP without refreshing via a method called Asynchronous Javascript and XML (AJAX).

Priyank
  • 3,778
  • 3
  • 29
  • 48
0
the_function() {

$.ajax({url:"demo_test.php",success:function(result){

   alert(result); // will alert 1

 }});

}

// demo_test.php

<?php echo 1; ?>

Notes

  1. Include jquery library for using the jquery Ajax
  2. Keep the demo_test.php file in the same folder where your javascript file resides
Kiren S
  • 3,037
  • 7
  • 41
  • 69
  • Sorry but I can't understand what you wrote, everywhere I go everyone writes code differently so it's incredibly confusing. The way I have been taught AJAX is completely different, I'll include an example so that people can see how to write it so I can understand – Daniel Dec 31 '14 at 05:40
  • You can call Ajax using javascript and jquery. Simpler is jquery ajax. Jquery is javascript library for making the things easy. You are using javascript conventional Ajax. Any way the code is different concept is same. – Kiren S Dec 31 '14 at 06:02
0

Modify the_script.php like this.

<script>
the_function() {
    alert("You win");
}
</script>
Mansoorkhan Cherupuzha
  • 1,761
  • 1
  • 24
  • 45