简体   繁体   中英

How can I show codeigniter form validation messages in an alertbox

I am trying to adapt Ion auth to work with ajax, because my login form is a fixed size, i want to alert the error messages when a form is submitted with incorrect data.

The messages are returned from the controller like this:

$this->session->set_flashdata('message', $this->ion_auth->messages());

and picked up in the view like this:

<div id="infoMessage"><?php echo $message;?></div>

I am trying to display them as follows:

<?php   if((isset($message))&&($message!='')){
            echo '<script> alert("'.$message.'"); </script>';
        }
?>

This isn't working, the alert is not being displayed, I have removed the message delimiters but this didn't help. My only thought is it must be something to do with the way codeigniter is creating a new line in the middle of my javascript as it is coming out like this:

<script>
alert('The Identity field is required.
The Password field is required.');
</script>

How can I get rid of this newline and replace it in a way that wont break my js?

Try

<?php   
    if((isset($message))&&($message!='')){
        echo '<script> alert("'.str_replace(array("\r","\n"), '', $message).'"); </script>';
    }
?>

In config/routes.php add string:

$route["action"] = "mycontroller/validation";

where mycontroller is the classname of your controller, where you process ajax queries, and validation is the name of method of this controller.

When you pass data through jQuery method .ajax() or it alias .post() , you can use results of server response as it described in documentation :

$.post( "validation",
{
    username: $( '#username' ).val(),
    password: $( '#password' ).val()
},
function( data )
{
    alert( 'message: ' + data );
});

or

$.ajax({ 
    url: "validation",
    username: $( '#username' ).val(),
    password: $( '#password' ).val()
}).done( function( data )
{
    alert( 'message: ' + data );
});

or

$.ajax({
    url: 'validation',
    data: { username: $( '#username' ).val(), password: $( '#password' ).val() }
    success: function( data ) 
    {
        alert( 'message: ' + data );
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM