CodeIgniter Forums
Controller ajax request - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: Controller ajax request (/showthread.php?tid=82575)



Controller ajax request - jameslatajan1233 - 07-25-2022

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?


RE: Controller ajax request - includebeer - 07-26-2022

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.


RE: Controller ajax request - ozornick - 09-23-2022

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


RE: Controller ajax request - HumeleJotesane - 09-26-2022

The idea behind MVC is that you separate the various components of your application so they can operate on a "need to know" basis.

Your models should be concerned with data, like say, a "Customer" record. A database should not give two shits about the type of <div> the customer's first name is going to be wrapped in. (Side note: Seeing HTML in a DB table is one of those things that is just wrong.)

Controllers do the dispatch to the models, and extract relevant data from the models, and forward it out to your Views.

A View takes some set of expected data and transforms it into a something that would make sense in the context of the view. If you're sending a confirmation email, you might forward to an "Email" view with data like "email address" and "message body".

'm in the middle of a web development learning project. I'm working on implementing the MVC pattern using PHP+Smarty templates for the "framework." So far, I have implemented the basics of the app (base classes for models, views, and controllers as well as test cases for each and example db queries etc.), and am planning to integrate JavaScript (+jQuery) and AJAX to submit things like comments and feedback so I don't have to redirect the user anywhere.

Thus far, MVC has been a dream. Aside from learning the basics, I never really jumped on the Rails bandwagon but I wholly appreciate the clean and separated approach to development (my education is in C programming).

My question is where/how should I integrate ajax support into my framework? My file structure looks like:

app

controllers

helpers

models

views

config

include

basecontroller.php

basemodel.php

baseview.php


RE: Controller ajax request - MatrickEganlan - 11-13-2022

I found issue in your ajax. I have fixed it. I have corrected url of ajax and remove data.

$( document ).ready(function() {
$( ".ri-remote-control-line" ).click(function() {
var lockID = this.id; //I am getting value here

$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/unlock/'+lockID,
type: "GET",
dataType: "JSON",
processData: false,
contentType: false,
success: function (data, status)
{
console.log(data);
},
error: function (xhr, desc, err)
{
console.log(xhr);
}
});
});
});


RE: Controller ajax request - InsiteFX - 11-13-2022

Makitweb - How to Send AJAX request with CSRF token in CodeIgniter 4