Welcome Guest, Not a member yet? Register   Sign In
Controller ajax request
#1

(This post was last modified: 07-25-2022, 09:41 PM by jameslatajan1233.)

Hi guys im new to codeigniter im still figuring out things here. So i have a problem about the ajax request it seem that the controller is not accepting the ajax request. I`m codeigniter 4.0 by the way.  I have search a lot of material in the internet and youtube but still nothing works.


So heres the code in the view folder named layout.php

Code:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="{csrf_header}" content="{csrf_hash}">
    <title>Ajax test</title>
</head>

<body>

    <!-- <form method="post" action="ajaxtest"> -->
    <div>
        <button type="submit" id="test">test Ajax</button>
    </div>
    <!-- </form> -->

    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

    <script type='text/javascript'>
        $(document).ready(function() {
            //var tokenName = $('#token').attr("name");
            //var tokenVal = $("#token").val();
            // alert(tokenName)
            // alert(tokenVal)

            $('#test').on('click', function() {
                // alert('ok');
                $.ajax({
                    url: "<?php echo base_url(); ?>/ajaxtest",
                    data: {
                        [tokenName]: tokenVal
                    },
                    method: "post",
                    success: function(response) {
                        alert('ok')
                    },
                    error: function(xhr, status, error) {
                        var err = eval("(" + xhr.responseText + ")");
                        alert(err.Message);
                    }
                });
            });
        });
    </script>
</body>

</html>
And heres the code in controller

PHP Code:
<?php

namespace App\Controllers;

// defined('BASEPATH') or exit('No direct script access allowed');


class AjaxController extends BaseController
{
    public function index()
    {
        if ($this->request->getMethod() == 'post') {
            echo 'post request done, ';


            if ($this->request->isAJAX()) {
                return 'the request is ajax';
            } else {
                return 'the request is not ajax';
            }
        }

        echo view('layout');
    }
}

The routes 
Code:
$routes->get('/', 'Home::index');

$routes->match(['get', 'post'], 'ajaxtest', 'AjaxController::index');


Now what I`m doing here is just trying to test if ajax works and return something. If  I uncomment the form tag in the layout file the request works fine but I need the request given by ajax not in the form tag so I wont use it but if  I use the ajax it wont respond anything and there is no error like in ci4 and the jquery. But the weird thing is that when I use post man and send ajax request it works perfectly fine. Can someone point out what I`m missing here?
Reply
#2

There is bugs in your JavaScript. code. You send tokenName and tokenVal but the variables doesn't exists. They are in comments. Look in the browser console, you will have an error message.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

In Config/Filters.php enabled csrf?
If enabled - must send csrf token for POST request
Reply




Theme © iAndrew 2016 - Forum software by © MyBB