0

This is my modals view

<div id="edit_numbers" class="modal">
    <?php $attrs = array('id' => 'user_form'); ?>
    <?= form_open_multipart('users/editnumber', $attrs) ?>
        <div class="modal-content row">
            <h4 class="modal-title">Add/Edit User Number</h4>
            <div class="row">
                <div class="col s12">
                    <p>
                        <input class="with-gap" name="method" type="radio" id="method_manual_input" value="manual" checked>
                        <label for="method_manual_input">Manual Input</label>
                    </p>
                    <input type="hidden" id="numberCount" name="numberCount" value="1">
                    <div id="numberForm" class="row">
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <input type="hidden" id="username" name="username" value="">
            <input type="hidden" id="user_id" name="id" value="">
            <button type="submit" class=" modal-action waves-effect waves-green btn-flat">Submit</button>
            <a href="#!" class=" modal-action modal-close waves-effect waves-green btn-flat">Cancel</a>
        </div>
    </form>
</div>

And this is my ajax

$("#edit_numbers").on('click', '.add-number', function() {

$('#numberCount').val( function(i, oldval) {
    return ++oldval;
});
var x = $(this).attr('data-number-id');
console.log(x);
var user_id = $("#number_" + x).val();
var user_username = $("#edit_numbers #username").val();

console.log(user_id + " " + user_username);
// do AJAX
$.ajax({
    url: base_url + "/number/add_number",
    data: {
        format: 'json',
        id: user_id,
        username: user_username
    },
    context: {
        id: $("#number_" + x).val()
    },
    dataType: 'json',
    error: function(err) {
        alert('An error occurred. Please try again later.');
        console.log(err);
    },
    success: function(data) {
        // body...
        console.log(data);
        if (data.status == 0) {
            alert(data.message);
        } else {
            var id = data.id;
            var new_x = parseInt(x) + 1;
            var inputGroupWrapper = numberAddBuilder(new_x, "");
            $("#numberForm").append(inputGroupWrapper);

            alert(data.message);
        }
    },
    type: 'POST'
});

return false; });

and this is my controller

public function add_number()
{
    $json = array(
        'status'  => 1,
        'message' => 'success',
    );

    $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
    $this->form_validation->set_rules('id', 'Account', 'trim|required|xss_clean');

    if (!$this->form_validation->run()) {
        $json['status'] = 0;
        $json['message'] = 'validation error';
    } else {
        $username = $this->input->post("username");
        $id = $this->input->post("id");

        $account_res = json_decode($this->number->add_number_to_user($username, $id, $this->session->userdata('logged_in')['token']), true);
        if (!isset($account_res)) {
            $json['status'] = -1;
            $json['message'] = 'server error';
        }
    }

    // set response
    echo json_encode($json);
}

This my form_helper, there's anything to with it or not?

function form_open($action = '', $attributes = array(), $hidden = array())
{
    $CI =& get_instance();

    // If no action is provided then set to the current url
    if ( ! $action)
    {
        $action = $CI->config->site_url($CI->uri->uri_string());
    }
    // If an action is not a full URL then turn it into one
    elseif (strpos($action, '://') === FALSE)
    {
        $action = $CI->config->site_url($action);
    }

    $attributes = _attributes_to_string($attributes);

    if (stripos($attributes, 'method=') === FALSE)
    {
        $attributes .= ' method="post"';
    }

    if (stripos($attributes, 'accept-charset=') === FALSE)
    {
        $attributes .= ' accept-charset="'.strtolower(config_item('charset')).'"';
    }

    $form = '<form action="'.$action.'"'.$attributes.">\n";

    // Add CSRF field if enabled, but leave it out for GET requests and requests to external websites
    if ($CI->config->item('csrf_protection') === TRUE && strpos($action, $CI->config->base_url()) !== FALSE && ! stripos($form, 'method="get"'))
    {
        $hidden[$CI->security->get_csrf_token_name()] = $CI->security->get_csrf_hash();
    }

    if (is_array($hidden))
    {
        foreach ($hidden as $name => $value)
        {
            $form .= '<input type="hidden" name="'.$name.'" value="'.html_escape($value).'" style="display:none;" />'."\n";
        }
    }

    return $form;
}

This is the view and the "+" button that i click When i click the button "+" i get An error occurred. Please try again later. and it says 403 forbidden. I just passing csrf token but nothing happen. When it come to success i get new bug after sumbit the data, it says "an error was encountered the action you have requested is not allowed." And getting anonymous in $..ajax line. I don't know what to do with that.

  • is this access valid? you accessing some api?, check url or address is correct and also access – Ahmed Sunny Jan 28 '20 at 09:40
  • and in your image you tried to hide the link in console, but in your alert the link is visible :P – Ahmed Sunny Jan 28 '20 at 09:41
  • `I just passing csrf token` - how? Your code does not show that? Do you have a route set up for that POST? Inspect the network request, are your variables (`id`, `username`) being sent correctly? Also, consider trying to make a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve), for example your question is about the 403 error, so your AJAX `success` callback is completely irrelevant, we don't need to see that. – Don't Panic Jan 28 '20 at 10:26
  • @AhmedSunny no, the url is ok. But when i change the csrf protection in config to false it works – anky aditya Jan 29 '20 at 03:13
  • @Don'tPanic sorry this is my original code, i've been tried so many ways to passing the csrf token, but it not works well. It works when i change the csrf protection to false in config. This way works on me https://arjunphp.com/ajax-csrf-protection-in-codeigniter/ , but i get new error when submitting the form "an error was encountered the action you have requested is not allowed." – anky aditya Jan 29 '20 at 03:15
  • @ankyaditya try check this link https://stackoverflow.com/questions/38502548/codeigniter-csrf-valid-for-only-one-time-ajax-request – K.B Jan 29 '20 at 08:57
  • @B.K i've been try that, but it not works :( – anky aditya Jan 29 '20 at 09:09

0 Answers0