简体   繁体   中英

Codeigniter ajax form submit unwanted post with jquery cookie for CSRF

So i have an issue that when I use the $.cookie jquery plugin my form seems to submit wrongly by submitting early I think.

So my form is:

<?php
    echo form_open($this->uri->uri_string(), 'class="ajax_email_submission"');
    ?>
    <div id="email_newsletter_signup" class="ajax_email_block_signup" >
        <h3>Sign up to the newsletter:</h3>
        <?php echo form_error('signup_email','<div id="email_error" class="error">','</div>');?>
        <h3>email: <input id="users_email_address" type="email" name="signup_email" value="<?php echo set_value('signup_email'); ?>" placeholder="Your email"/> </h3>

        <input id="email_submit" type="submit" name="submit"/>
    </div>
    <?php
    echo form_close();
?>

The JS is

$(document).ready(function()
{    
    $('#email_submit').click(function() 
    {
        alert('1');
        var form_data = 
        {
           users_email: $('#users_email_address').val(),
           csrf_test_name: $.cookie('csrf_cookie_name')
        };
        alert('2');
        $.ajax
        ({
            url: 'NewsLetter/submit',
            type: 'POST',
            data: form_data,
            success: function(msg)
            {
                alert('success');
            },
            error: function(msg)
            {
                alert('error');
            }
        });

        return false;
    });
});

The method exists and if i put in localhost/myzone/NewsLetter/submit the method submit works properly.

When I look in the codeigniter Router class I find that the $_POST variable contains:

$_POST  array[3]        
ci_csrf_token   string  "3dad64d9aaaaaaaaaaaaaad2082ae55c"  
signup_email    string  "mail@cheeeese.com" 
submit  string  "Submit"    

The URI that is submitted is localhost/myzone/NewsLetter as the submit is in the post and not the URI so I get sent to the index method instead of the submit method.

Also what happens in the JS you may notice the alert('1') and alert('2') . Only alert('1') shows which I have no clue why this happens!

All help is really appreciated

Thanks

You submit form not by ajax but by POST method. If you want to do smth BEFORE submiting, add

event.preventDefault()

to your click function. Like

$('#email_submit').click(function(event) 
{
    event.preventDefault();

    //all your calculations and ajax than
}

Than no form will be submited and you will push your ajax request

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