hyphen
hyphen

Reputation: 967

Problems with multiple PHP functions in the same file

I want to make an AJAX call to a php file called functions.php, where I have mutliple related functions (all making database changes to accounts, ie. add, edit, delete). I've been struggling with this, because the AJAX call seems to work fine, but the response that comes back from the server is empty (content-lenght: 0). I went back to square one and just used AJAX to send data to a php file that only contained the php code to handle that one call (ie. no functions), and it works fine. As soon as I wrap that simple statement into a function, it fails again. So something I'm doing causing the php not to send a respone when I'm wrapping it in a function.

Do you have to call a specific php function somehow from your ajax script, or somewhere in your form element? How does the php file know which function you're requesting in your ajax call if there are multiple functions? Or does it just sort it out by matching the $_POST element with the data being sent over, regardless of which function that $_POST element is in?

I suspect that my PHP code is to blame:

function delete_account(){
require(ROOT_PATH . "/inc/database.php");

$deleteAccount = $_POST['accountName'];

try {
    $results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
    $results->bindValue(1, $deleteAccount);
    $results->execute();
} catch(Exception $e) {
    echo "ERROR: Data could not be removed from the database. " . $e;
    exit;
}
return;
}

Also, when I press the submit button and my ajax call is fired off, it immediately returns the success message in the browser, and as I'm watching the Network tab on my google dev tools window, the success message is displayed seemingly before the php file is even loaded. I've tried setting async: false.

Adding AJAX code:

function deleteAccount(){
    event.preventDefault();

    var accountName = $('.account_name').filter(":selected").attr("name");

    $.ajax({
        type: "POST",
        url: 'inc/functions.php', 
        data: {accountName:accountName}, 
        async: false,
        success: function(response){
        $('#results').html(response + " has been deleted.");
        }
    });
};

Upvotes: 0

Views: 1596

Answers (1)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

If you have multiple functions in your PHP file, then you can do something like:: pass in extra parameter in you jQuery ajax, like:

$.ajax({
    url: "some_file.php?action=get_accounts"
}).done(function() {
    $( this ).addClass( "done" );
});

and in your PHP file use switch to call appropriate function depending on value of action variable in your ajax, like:

//in PHP
.....
$action = $_GET['action'];
switch ($action) {
    case "get_accounts":
        //call the function
        get_accounts();
        break;
    case "otherFunction":
        ....
        break;
}

Upvotes: 3

Related Questions