Adrian
Adrian

Reputation: 2291

How to call a single function from a group of functions with ajax?

I am trying to call only one function per ajax request, but somehow all the functions from he php file are being called.

ajax.php

require_once "../lib/common-functions.php"; // here are the functions located.
subscribe();
subscribed();
unsubscribe();
delete_history();
deactivate_account();

and ajax script:

$('#delete-history').on('submit', function (e) {
    $.ajax({
        type: 'post',
        url: '../lib/ajax.html',
        data: {
            action: 'delete_history'
        },
        success: function (data) {
            $("#message").html(data);
        }
    });
    e.preventDefault();
});

If I would like to call only the function delete_history() then I get messages from other functions like subscribe() or all the other functions at once. Why? Where am I mistaking. Can I do this without putting each function in a file.

Upvotes: 1

Views: 81

Answers (2)

Don
Don

Reputation: 110

$('#delete-history').on('submit', function (e) {
    $.ajax({
        type: 'post',
        url: '../lib/ajax.html',
        data: {
            action: 'function=delete'
        },
        success: function (data) {
            $("#message").html(data);
        }
    });
    e.preventDefault();
});

PHP which contains all function

if($_POST['function'] == 'delete')
{
   delete_history();

}

Upvotes: 1

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

You are posting to index.html, so I guess not only the expected function is not called, but none is.

You should call the appropriate .php file, where the functions are declared or at least included.

the funcName() syntax calls the function, so if you have after declaration these rows:

subscribe();
subscribed();
unsubscribe();
delete_history();
deactivate_account();

You will call all of them. You'd need a condition dependant on what the user posts. E.g.:

if (isset($_POST['action']) && $_POST['action'] == 'subscribe') {
    subscribe();
}

In your case you sending $_POST['action'] = 'delete_history', but you cannot expect it magically to map the post param with the relevant function. I'm really surprised you had these expectation. Who has told you that sending an action param will be magically understood by the backend? You should follow the pattern above.

if (isset($_POST['action']) && $_POST['action'] == 'delete_history') {
    delete_history();
}

Upvotes: 3

Related Questions