No response being received from Ajax request

Having some trouble with an ajax function I developed for a small project. The issue lies in running the code inside the .done() function. This function is supposed to receive a json object from php (which I am obtaining a response via cURL), but it appears that no response is being returned. The project itself is built using SBAdmin 2 (Bootstrap) along with jQuery 3.5.1.

Here is the specific ajax snippet:

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

    <!-- Bootstrap core JavaScript-->
    <script src="../resources/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../resources/vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../resources/js/sb-admin-2.min.js"></script>

    <script>

        $(document).ready(function() {
            $("#btnLogin").click(function() {
                console.log('clicked');
                var uname = document.getElementById('inpUsername').value;
                var pwd = document.getElementById('inpPassword').value;  
    
                $.ajax({
                    type: 'POST',
                    url: 'resources/php/functions/main-functions.php?',      
                    data: "inpUsername="+uname+"&inpPassword="+pwd,
                    dataType: 'json'
                })
                .done(function(data, textStatus, jqXHR){
                    console.log('Response received:', data); // Log the entire response
                        if (data.status === 'success') {
                            console.log('Authentication successful:', data.message);
                        } else {
                            console.log('Authentication failed:', data.message);
                        }
                })
                .fail(function(jqXHR, textStatus, errorThrown){
                    console.log('AJAX Error:', textStatus); // Log the error status
                    console.log('Error details:', errorThrown); // Log the error details
                });
    
                $(location).prop('href', '/index.php?view=loggedin');
                location.reload();
            });
        });

And here is the corresponding php backend setup:

if(!empty($_POST['inpUsername']) && !empty($_POST['inpPassword'])){
    if(authUser()) {
        header('Content-Type: application/json');
        die(json_encode(['status' => 'success', 'message' => 'User authenticated']));
    } else {
        header('Content-Type: application/json');
        die(json_encode(['status' => 'error', 'message' => 'Invalid credentials']));
    }
}

When attempting to run the request in the browser, the .fail() section gets executed. Additionally, I'm seeing a status of "NS_BINDING_ABORTED."

If anyone has any insights on where my mistake might be, I'd appreciate the help!

Also, just a heads up - I'm still learning the ropes :)

I've already tried switching from success and error functions to done and fail without any changes in behavior. Manually testing the request through devtools seems to work fine with cURL, but not in the browser. I even experimented with the order of including jQuery but again, no luck.

Answer №1

Success! Issue Resolved

Appreciate the assistance provided! Moving location.reload() within $ajax.done() seemed to have solved the issue.

Moreover, I have integrated all other suggestions given which should enhance readability as well.

Updated Code:

$(document).ready(function() {
            $("#btnLogin").click(function() {
                var uname = document.getElementById('inpUsername').value;
                var pwd = document.getElementById('inpPassword').value;  
    
                $.ajax({
                    type: 'POST',
                    url: '../resources/php/functions/main-functions.php?',      
                    //data: "inpUsername="+uname+"&inpPassword="+pwd,
                    data : {
                        inpUsername: uname,
                        inpPassword: pwd
                    },
                    dataType: 'json'
                })
                .done(function(data, textStatus, jqXHR){
                    console.log('Response received:', data); // Log the entire response
                        if (data.status === 'success') {
                            console.log('Authentication successful:', data.message);
                        } else {
                            console.log('Authentication failed:', data.message);
                        }
                        location.reload();
                })
                .fail(function(jqXHR, textStatus, errorThrown){
                    console.log('AJAX Error:', textStatus); // Log the error status
                    console.log('Error details:', errorThrown); // Log the error details
                });
    
            });
        });

Answer №2

In addition to the feedback provided in the comments, it seems that there may be an error in the URL you are trying to access through AJAX. Your other resources have a path like this:

../resources/foldername etc

However, your AJAX call is targeting a different path:

 url: 'resources/php/functions/main-functions.php?',

Notice that the resources folder in the AJAX script does not include ".."(two dots) at the beginning.

Unless there is another resources folder in the root directory, it would be more appropriate to use the following URL:

url: '..resources/php/functions/main-functions.php?',

On a side note, considering you are making a POST request, it might be better practice to avoid using query parameters. A revised version of your code could look something like this:

$.ajax({
    type: 'POST',
    url: '..resources/php/functions/main-functions.php',
    data: {
        inpUsername: uname,
        inpPassword: pwd
    },
    dataType: 'json'
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to assign values to textarea and checkbox in MVC5

I am currently facing an issue with setting values in JavaScript + jQuery in MVC 5 for textareas and checkboxes. Here is the JavaScript code I am using: document.getElementById("UpdatetxtDescription").value = "abc"; document.getElementById("Upda ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

I am trying to figure out how to properly utilize server-only functions within Next.js middleware

In my current project, I am utilizing Next.js 13 along with the App Router feature. While attempting to include a server-specific fetch function in middleware.js, an error message is encountered: Error: Unable to import this module from a Client Compone ...

The node server is experiencing difficulties connecting to the mysql database, resulting in a timed out connection error at Connection._handleConnectTimeout

Having trouble establishing a connection with the mysql database. Every time I attempt to start the node server, it keeps throwing a database connection error. The specific error message is as follows: connect ETIMEDOUT at Connection._handleConnectTimeou ...

Transform JSON time data from Coordinated Universal Time (UTC) to Indian Standard

Hello, I consider myself an amateur in the world of online javascript learning. Currently, I have come across a challenge that has left me stuck. I am working with a JSON time data provided in UTC format (e.g. 16:00:00Z) and my goal is to convert it to IS ...

What could be causing my middleware to run twice?

A custom middleware was created in express.js/node.js to handle session checking. If a user ID is found in the session, it displays the user's menu; otherwise, it shows the default menu. For every page request, an ID check is performed and the user d ...

What are the steps to connect to, fetch, save, and remove files from a remote file server using Node.js?

Currently working on a project in node.js that requires saving an uploaded file from a client onto a remote file server for later retrieval. While I'm familiar with accessing and storing files on the local file system using 'fs', I am unsure ...

Why is the current Menu Item highlight feature not functioning properly?

Why isn't the highlight current Menu Item feature working? I've checked my code, but it doesn't seem to be functioning as expected. Could you lend me a hand? Html: <section id="menu-container"> <div id="bar"><img src="b ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

Encountering an undefined error while attempting to retrieve an object from an array by index in Angular

Once the page is loaded, it retrieves data on countries from my rest api. When a user selects a country, it then loads the corresponding cities for that country. Everything is functioning properly up to this point, however, upon opening the page, the city ...

Tips for updating content (wishlist) without the need to refresh the page

Currently experimenting with the TMDb API to enhance my PHP skills. I've successfully created a wishlist feature and now looking to optimize the script. A function is implemented on each movie page for adding movies to the wishlist. function getButt ...

Achieving repetitive progress bar filling determined by the variable's value

JSFiddle Here's a code snippet for an HTML progress bar that fills up when the "battle" button is clicked. I'm trying to assign a value to a variable so that the progress bar fills up and battles the monster multiple times based on that value. ...

Eliminate the mandatory asterisk from the website field on the comment form

In order to achieve this, we must delve into the code and carefully modify the necessary sections within comments.php: <?php // Ensuring that essential lines are preserved if (!empty($_SERVER['SCRIPT_FILENAME']) && 'comments.ph ...

JavaScript-powered horizontal sliderFeel free to use this unique text

I'm new to JS and trying to create a horizontal slider. Here's the current JS code I have: var slideIndex = 0; slider(); function slider() { var i; var x = document.getElementsByClassName("part"); for (i = 0; i < x.length; i++) { x[i].styl ...

When working with Nuxt 3, the referrer header may sometimes return as undefined

I am looking to capture the referrer header and store it in a cookie so that I can later use it to populate an axios request during the user's journey on my website. In my app.vue, I currently have the following code snippet: const headers = useReque ...

Working with scrollIntoView in useEffect (Encountering an error trying to access 'scrollIntoView' property of null)

Starting from scratch, I'm working on setting up my webpage and crafting some code. function BasicDetails() { React.useEffect(()=>{ scrollView(); }, []); function scrollView() { document.getElementById('main-root& ...

Is Angular capable of displaying a date within a specific timeframe using ng-show?

So I have a button that, when clicked, displays a list of data. I am adding a unique font awesome icon in there if the JSON key value exists. However, here lies the issue. The particular key happens to be a date. I need my ng-show function to check whether ...

Form a column containing both row object data and html code elements

I am in the process of creating a unique column within my table, allowing me to execute specific actions and generating HTML code based on the object defining the row. Being new to Angular, I believe I should utilize $compile, but I am unsure of how to pr ...

How can I input data into cells in an Excel spreadsheet and retrieve information from a particular cell?

Is there a way to send values to specific cells in an Excel file stored on my webserver and then extract the result from another specific cell using PHP? ...

Updating API calls with form submission in React.js

Currently working on a weather application and attempting to update my API call upon submitting a form. This project marks my initial attempt at developing my own program, and I've encountered an obstacle. The plan is for the user to input a city, cli ...