3

I am trying to call a php function when an HTML button is clicked.i have done some searching and found that its impossible to do this directly and i should use ajax. so this is my attempt so far which is not working.this is my test.php and the function is also in this page.

   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('.NextPage').on('click', function() {
                $.ajax({
                    url: 'test.php',
                    data: {x: 1},
                    type: 'POST',
                    dataType: 'JSON',
                    success: function(response) {
                        alert(response);
                    }
                });

            });
        });
    </script>
     </head>
     <body>

    <button type="button" class="NextPage">go to nextpage</button> 

    <?php
    if (isset($_POST['x'])) {
        if ($_POST['x'] == 1) {
            $data = function1();
            echo json_encode($data);
            exit;
        }
    }

    function function1() {
        return 'Hi user! im function #1';
    }

    function function2() {
        return 'Hi user! im function #2';
    }
    ?>

2
  • 1
    Your function will never get called because the value of $x is always 0 when you're doing the comparison. Your code isn't syntactically correct either. It should look like: $('.NextPage').click(function() { $.ajax({. Commented May 18, 2014 at 7:55
  • thank you for the quick response.i edited my code as you said but now i get the error of "Undefined index: x" in this line :$x = $_POST['x']; Commented May 18, 2014 at 8:04

4 Answers 4

2

get the value of the x from ajax call.

$x = $_POST['x'];

then use it.

EDIT

First you have to check weather your variable is set or not..

if(isset($_POST[x]))
{
$x = $_POST['x'];
}

try this

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the quick response.i edited my code as you said but now i get the error of "Undefined index: x" in this line :$x = $_POST['x'];
1

I've practically used your code and got it working. Your PHP is just fine, as for your AJAX call, it must have success or done to benefit the returned data.

The code for reference is here

HTML

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="mobile-web-app-capable" content="yes">
        <link rel="shortcut icon" sizes="196x196" href="">

        <link rel="stylesheet" type="text/css" href="" />
    </head>
    <body>
        <div id="abc"></div>
        <button type="submit" class="NextPage">go to nextpage</button>
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </body>
</html>

JavaScript

$(document).ready(function() {
    $('.NextPage').click(function() {
        $.ajax({
            type:'post',
            url:'service.php',
            data:{x:1}
        }).done(function(data) {
            $("#abc").text(data);
        });
    });
});

PHP

<?php
    $x = $_POST['x'];

    if ($x == 1) {
        function1();
    }

    function function1() {
        echo "This is function 1";
    }

    function function2() {
        echo "This is function 2";
    }

1 Comment

thank you for your answer.i edited my code and still nothing happens when the button is clicked
1

First off, you need to set your button to type="button", then, make an AJAX request, then the missing part on your code is the backend part which processes the request. Then the backend responds to that call. After that you can just do what you please on that response. Consider this example:

<?php

// this part handles the AJAX request
if(isset($_POST['x'])) {
    if($_POST['x'] == 1) {
        $data = function1();
        // a call has made, then give a response
        echo json_encode($data);
        exit;
    }
}

function function1() {
    // do some processing
    return 'Hi user! im function #1';
}

function function2() {
    return 'Hi user! im function #2';
}

?>

<!-- make its type "button" -->
<button type="button" class="NextPage">go to nextpage</button>
<div id="notification"></div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('.NextPage').click(function(){
        $.ajax({
            url: 'test.php',
            data: {x: 1},
            type: 'POST',
            dataType: 'JSON',
            success: function(response) {
                $('#notification').html('Your ajax call has been successful<br/> and this is a notification').css({background: 'yellow'});
            }
        });

    });
});
</script>

8 Comments

thank you for your answer,i edited my code.still not working ! nothing happens when i click the button
@user3622910 on my example earlier, i used index.php on url on ajax, try to edit it and match the filename of the php that will handle that ajax call
@user3622910: Instead of complaining "not working", please actually try to debug the issue. Use your browser's console to see if the POST request is being fired and whether you're getting any response back. View the page source. Keep trying — that's how you solve problems :)
@kevinabelita i changed the url to test.php which is the same page of the function.
@user3622910 okay you could check the edit now, we are now using the same jquery cdn (and check the js scripts).
|
-2

What makes you think it is impossible to call a php function directly. This is exactly what is done in CodeIgniter PHP MVC framework. You can call a php function with arguments inside a php class directly in CodeIgniter and that is actually what is done always.

Comments

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.