0

i have two php files home.php and ajax.php. i have two buttons on home.php. when they are clicked the according php functions in ajax.php should get called.

home.php

<html>
    <head>
        <script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
        <script type='text/javascript'>
        $(document).ready(function(){
            $('.button').click(function(){
                var clickBtnValue = $(this).val();    
                var ajaxurl = 'ajax.php';
                data =  {'action': clickBtnValue};

                $.post(ajaxurl, data, function (response) {
                    // Response div goes here.
                    alert("action performed successfully");
                });

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

    <body>
        <form action='ajax.php' method="POST">
            <input type="submit" class="button" name="insert" value="insert" />
            <input type="submit" class="button" name="select" value="select" />
        </form>
    </body>
</html>

ajax.php

<?php
echo 'this was called';
echo $_POST['action']; //THROWS AN ERROR undefined index 'action'

if ( isset( $_POST['action'] ) ) {

    switch ($_POST['action']) {
        case 'insert':
            insert();
            break;
        case 'select':
            select();
            break;
    }
}

function select() {
    echo "The select function is called.";
    exit;
}

function insert() {
    echo "The insert function is called.";
    exit;
}
?>

the problem is the json data i assign to data property in jquery code will not get passed to the ajax.php. Is there any reason why it doesn't not pass it?

here is my youtube video on the error video

Phill Greggan
  • 2,234
  • 3
  • 20
  • 33
  • Both buttons are submit buttons? – Varun Sep 05 '15 at 14:19
  • Just dumped your js into a fiddle as is and your data is submitting fine. You sure you sending it to the right url? – kurt Sep 05 '15 at 14:19
  • This has nothing to do with `json`, but the data should get send and received as expected. The code looks fine to me in that aspect. – arkascha Sep 05 '15 at 14:19
  • @Varun yes both buttons are submit! – Phill Greggan Sep 05 '15 at 14:20
  • @kurt both files resides in teh same folder – Phill Greggan Sep 05 '15 at 14:21
  • @PhillGreggan Then how will it work,you have a action to your form and also you are doing a post request from the script. – Varun Sep 05 '15 at 14:21
  • Then I've got nothing. Only thing I can say is check your network request on dev tool tools and try doing a dump of all your post data on ajax.php – kurt Sep 05 '15 at 14:22
  • I guess your plain html-form is fired before you even reach the ajax-post. Try inserting an `event.preventDefault()` – Jeff Sep 05 '15 at 14:23
  • @Varun even when i commet out one, still same prob! – Phill Greggan Sep 05 '15 at 14:23
  • @PhillGreggan Can you make one as `input type="button"` and other as submit? – Varun Sep 05 '15 at 14:24
  • and/or change the buttons to non-submit buttons. (`txt`) – Jeff Sep 05 '15 at 14:24
  • The submit button must be refreshing the page before the ajax works. – Varun Sep 05 '15 at 14:25
  • @Varun okay guys, im still new to jquery i was experimenting this code 'http://stackoverflow.com/questions/20738329/how-to-call-a-php-function-on-the-click-of-a-button' some how it does not seems to work with me :( – Phill Greggan Sep 05 '15 at 14:26
  • @Jeff none works the code was modified from the origianl post 'http://stackoverflow.com/questions/20738329/how-to-call-a-php-function-on-the-click-of-a-button' – Phill Greggan Sep 05 '15 at 14:31
  • in `ajax.php` do a var_dump of `$_POST`. I suppose it'll show which button you've clicked. If it does so, it means your form gets submitted, what you (in your case) don't want to. right? In case you don't need it for anything else you can totally get rid of the `
    ` at all, and change the ``s to `
    – Jeff Sep 05 '15 at 14:34
  • Do you see the response of ajax.php in the browserwindow or do you check in console? – Jeff Sep 05 '15 at 14:38
  • @Jeff null was printed – Phill Greggan Sep 05 '15 at 14:40
  • you mean when doing `var_dump($_POST)` you get `NULL`? or nothing? In your browser window or in devtools->network->response? – Jeff Sep 05 '15 at 14:47
  • @Jeff yes it was a var_dump it : ( – Phill Greggan Sep 05 '15 at 14:48
  • @Jeff if you can give me a minute i can post it on youtube as a screen – Phill Greggan Sep 05 '15 at 14:49
  • @Jeff sorry took sometime, i could not access my youtube account. anyway i have updated my post with the link – Phill Greggan Sep 05 '15 at 15:05
  • I'm not sure but since you are submitting the formdata to ajax.php via submit buttons I'd guess the formdata is send before your click handler actually does anything. Try and add `event.preventDefault()` to the first line of your click handler and dont forget to pass `event` to the function. – TobiasJ Sep 05 '15 at 15:20
  • @Phill Greggan Thanks for the video. As I (and others) have said before: you are sending the form and NEVER send the ajax-post. This is why var_dump($_POST['action']) will always be `NULL`. if you `var_dump($_POST)` as I suggested before, you'll see, that you get smthg like `...insert=insert..`. So, remove the html-form, make buttons out of your input-submits and there you go. – Jeff Sep 05 '15 at 15:54

4 Answers4

2

There are two possibilities, depending of what you want to achieve afterwards.

Eighter you stick on doing a backgroud ajax-call to ajax.php and then do with the response whatever you want (that's what I'd suggest):

<html>
<head>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
    <script type='text/javascript'>
    $(document).ready(function(){
        $('.button').click(function(){
            var clickBtnValue = $(this).id(); // changed to id here!
            var ajaxurl = 'ajax.php';
            data =  {'action': clickBtnValue};

            $.post(ajaxurl, data, function (response) {
                // Response div goes here.
                console.log(response); // log what the response is
                alert("action performed successfully and the resonse is: \n"+response);
                // do with that data whatever you need
            });

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

<body>
    <!-- changed to buttons, removed the form -->
    <button class="button" id="insert">insert</button>
    <button class="button" id="select">select</button>
</body>
</html>

or you submit the form and output on screen the response from ajax.php:

<html>
<head>
    <!--script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script-->
    <script type='text/javascript'>
    // no need for any javascript then
    </script>
</head>

<body>
    <form action='ajax.php' method="POST">
        <input type="submit" class="button" name="insert" value="insert" />
        <input type="submit" class="button" name="select" value="select" />
    </form>
</body>

and in ajax.php:

<?php
echo 'this was called';


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

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

function select() {
  echo "The select function is called.";
  exit;
}

function insert() {
  echo "The insert function is called.";
  exit;
}
?>
Jeff
  • 6,895
  • 1
  • 15
  • 33
0

try

$.post(ajaxurl, data)
  .done(function( r ) {
   alert("action performed successfully");
});
hyn
  • 11
  • 1
0

I like to use the jQuery on() and to be sure post has worked, I moved in your variables as such. Also you can try to do console.log(clickBtnValue) after the click to be sure you are able to see the value itself. After confirming, the post() should send that value into action post param.

<script type='text/javascript'>
$(document).ready(function(){
    $('.button').on('click',function(){
        var clickBtnValue = $(this).val();    
        var ajaxurl = 'ajax.php';

        $.post(ajaxurl, {action:clickBtnValue}, function (response) {
          alert("action performed successfully");
        });
    });
});
</script>
tmarois
  • 2,424
  • 2
  • 31
  • 43
0

If you need to do a ajax call, remove the following part from the home.php

<form action='ajax.php' method="POST">
</form>

I think you are messed up with Ajax technology and the form post mechanism.

lmanohara
  • 77
  • 8