0

I am developing a web app but running into a few small snags. I'm using CodeIgniter.

I want to have 2 buttons that will do execute 2 different functions that do different things to the database. I have these functions made in the proper Controller file.

What is the best way to go about making the buttons execute their respective functions? If it requires javascript, I have no problem making it, just need some pointers as I'm a little bit confused here!

1 Answer 1

1

If they're making changes to records in the database, you should probably implement them as part of a form (or two). Potentially destructive actions should not be executable just using a simple GET request.

The form(s) can contain a hidden input type to specify what you want to in the controller.

HTML page:

<form action="controller/myfunction" method="POST">
    <input type="hidden" name="action" value="one">
    <input type="submit" value="Do action one">
</form>

<form action="controller/myfunction">
    <input type="hidden" name="action" value="two">
    <input type="submit" value="Do action two">
</form>

Controller:

function myfunction()
{
    // Your form would be submitted to this method...
    // Get action from submitted form ('one' or 'two')
    $action = $this->input->post('action');
    // Decide what to do
    switch ($action)
    {
        case 'one': $this->my_first_action(); break;
        case 'two': $this->my_second_action(); break;
    }
}

function my_first_action()
{
    // Do stuff...
}

It would be good practise to redirect to another page once the form has been submitted - use the 'Post/Redirect/Get' pattern.

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

2 Comments

This is definitely what I'm looking for. The problem now is that even with the function defined in my Controller and it being properly called in form action="" I get a 404 error?
It sounds like you need to enter the full URL in the form's action tag. Use the URL helper (e.g. <?php echo site_url('controller/method') ?>) or the form helper (<?php echo form_open('controller/method') ?>). Also make sure the method is set to POST.

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.