Redirect of the codelgniter

Asked

Viewed 441 times

1

I’m willing to put one alert simple of Javascript in the Codelgniter, I’m trying to put this alert with a function of Codelgniter that is redirect. I put to redirect the page, but the alert not work.

What can it be?

$data['categoria'] = $this->input->post('categoria');
$data['slug_categoria'] = $this->input->post('slug_categoria');
$this->db->insert('categorias', $data);
redirect('administracao/categorias');
echo "<script>alert('Inseridos!')</script>";

How do I make this warning message work with redirect? this way and another way that I’ve tried does not work.

  • 1

    It worked perfect, thank you

1 answer

1

Explanation:

1) Regardless of the technology used in programming, do not mix PHP code with Javascript;

2) The redirect which is a helper of Codeigniter, has the function of redirecting to the specified address, and internally would be a header("Location: /administracao/categorias"); then, it won’t even run the last line that is a Javascript code (follow recommendation item 1). ). See code below:

function redirect($uri = '', $method = 'location', $http_response_code = 302)
{
    if ( ! preg_match('#^https?://#i', $uri))
    {
        $uri = site_url($uri);
    }
    switch($method)
    {
        case 'refresh': 
            header("Refresh:0;url=".$uri);
            break;
        default: 
            header("Location: ".$uri, TRUE, $http_response_code);
            break;
    }
    exit;
}

3) Solution:

In your method before the redirect, use a $this->session with the method flashdata, which is intended to be active only until the next server request and immediately after it is automatically deleted.

Method:

$data['categoria'] = $this->input->post('categoria');
$data['slug_categoria'] = $this->input->post('slug_categoria');
$this->db->insert('categorias', $data);
$this->session->set_flashdata('acaoform', 'Inseridos !!!.');
redirect('administracao/categorias');

View

<?php
    $acaoflash = $this->session->flashdata('acaoform');    
    if (isset($acaoflash) && $acaoflash!=''){
        echo "<script>alert('".$acaoflash."')</script>";
    }
?>

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.