0
votes

I am trying to integrate ajax into a web application with the Django framework. I am however having a hard time trying to make a simple ajax call to work.

I want to make a DB connection using a form (where users input the DB credentials), call the API, then return the output (whether successful or not).

Here's my views.py that is used to handle the API:

# -- START from HERE !
class TestConnectionAPI(views.APIView):
    '''
    Test DB Connection from TARGET DB
    '''  
    def post(self, request):
        dbs = (request.data['host'],
                request.data['port'],
                request.data['dbname'],
                request.data['user'],
                request.data['password'],
                request.data['schema_name'])

        try:
            x = dc.DbConnection(*dbs)
            x.create_conn()
            data = x.check_conn()           
            
            result = {
                'message' : 'Success',
                'server' : f'Connection established from {data}',
                'results':{
                    'host':dbs[0],
                    'port':dbs[1],
                    'dbname':dbs[2]
                    },
            }
            return Response(result, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'Message':str(e)}, status=status.HTTP_400_BAD_REQUEST)

This is my connection.html to display the form (complete code: here) :

...
<form method="post">
                                    <div class="modal-body">
                                        <div class="form-group">
                                            <label for="host">Hostname</label>
                                            <input type="text" class="form-control" id="host" name="host" aria-describedby="host">
                                        </div>
                                        <div class="form-group">
                                            <label for="port">Port</label>
                                            <input type="number" class="form-control" id="port" name="port" placeholder="e.g., 5432">
                                        </div>
                                        <div class="form-group">
                                            <label for="database">Database name</label>
                                            <input type="text" class="form-control" id="dbname" name="dbname" placeholder="Enter database name">
                                        </div>
                                        <div class="form-group">
                                            <label for="username">Username</label>
                                            <input type="text" class="form-control" id="user" name="user" placeholder="Enter username">
                                        </div>
                                        <div class="form-group">
                                            <label for="password">Password</label>
                                            <input type="password" class="form-control" id="password" name="password">
                                        </div>
                                        <div class="form-group">
                                            <label for="schema">Schema</label>
                                            <input type="text" class="form-control" id="schema_name" name="schema_name">
                                        </div>
                                    </div>
                                    <div class="modal-footer border-top-0 d-flex justify-content-center">
                                        <a href="#form2" class="btn btn-primary" data-toggle="modal" type="submit" id="btnSubmit">Test</a>
                                        <button type="submit" class="btn btn-success">Save</button>
                                    </div>
                                </form>
...

And, here's the AJAX function for calling the API (POST request):

$('#btnSubmit').click(function () {

        let _host = $('#host').val();
        let _port = $('#port').val();
        let _dbname = $('#dbname').val();
        let _user = $('#user').val();
        let _password = $('#password').val();
        let _schema_name = $('#schema_name').val();

        var $crf_token = $('[name="csrfmiddlewaretoken"]').attr('value');

        $.ajax({
            type: 'POST',
            dataType: 'JSON',
            headers:{"X-CSRFToken": $crf_token},
            data:{
                "host" : _host,
                "port" : _port,
                "dbname" : _dbname,
                "user" : _user,
                "password" : _password,
                "schema_name": _schema_name,
            },

            url:"http://127.0.0.1:8000/api/v1/test/",
            error: function (xhr, status, error) {
                var err_msg = ''
                for (var prop in xhr.responseJSON) {
                    err_msg += prop + ': ' + xhr.responseJSON[prop] + '\n';
                }

                alert(err_msg);
                },
            
            success: function (result) {
                console.log(result);
            }
        });
    });

This is my error: enter image description here

However, I have a hard time fixing the error. I tried to follow some discussion in the StackOverflow forum, but I still have this error. The error is related to the CSRF token, where it is difficult for me to follow the Django documentation.

At least I want to display this API response on the console log.

{
    "message": "Success",
    "server": "Connection established from ('PostgreSQL 12.7, compiled by Visual C++ build 1914, 64-bit',)",
    "results": {
        "host": "localhost",
        "port": 5432,
        "dbname": "dvdrental"
    }
}

Added-1: POST request header enter image description here

Could you please help me to solve the problem? Thanks.

Check the POST request using the browser inspector. Does it send the correct value in X-CSRFToken header? - Selcuk
@Selcuk, Excuse me, thank you for your response. I checked using the browser inspector. Unfortunately, I cannot find the X-CSRFToken. Is this another problem also? I added the result to the question. - furanzup
Looks like that's your issue. I see that some requests are going to test while others are for test/. Is there a redirect from one to the other? That might cause the browser to drop your header. - Selcuk