Effective ways to resolve the ajax problem of not appearing in the console

I am facing an issue with my simple ajax call in a Java spring boot application. The call is made to a controller method and the returned value should be displayed in the front-end console. However, after running the code, it shows a status of 400 but nothing is appearing in the console. I'm unsure if I missed something or if there is a setup error causing this lack of data being passed back.

JQuery:

$(".modalPathContentBtn").on("click", function(event) {

                getSecondQuery();

            });

            function getSecondQuery() {

                var search2 = {
                    "dtoTiername" : "Test"

                }

                $.ajax({
                    type : "POST",
                    contentType : 'application/json; charset=utf-8',
                    dataType : 'json',
                    url : "/ajax/mqlGetSecondQuery",
                    data : JSON.stringify(search2),
                    success : function(result) {

                        console.log("It works: " + result);

                    }

                });
            }

Java:

@RequestMapping(value = "/ajax/mqlGetSecondQuery", method = RequestMethod.POST)
    public @ResponseBody String sendSecondQuery(@RequestBody TestApp mTestApp, HttpServletRequest request) {
        String pathVal = mTestApp.getDtoTiername();

        System.out.println("Test of if it is getting to this part of the code");

return "randomString";


    }

Answer №1

If your request fails with a status code of 400, it means that the Ajax call is not successful and the 'success' function will not be triggered. To handle this situation, you should include a 'fail' handler in your code. Here's an example:

$.ajax({
  type: "POST",
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  url: "/ajax/mqlGetSecondQuery",
  data: JSON.stringify(search2),
  success: function(result) {
    console.log("It works: " + result);
  },
  fail: function(err) {
    console.log(err)
  }
});

This code snippet may not be exact syntax, but the concept is to ensure you have a fail handler for handling unsuccessful Ajax requests.

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

Is there a way for me to monitor the ngSrc attribute of an image element and retrieve the updated width and height within my personalized directive?

Here is a snippet from index.html: <img ng-src="{{ImageURL}}" my-image/> This is from app.js: var app = angular.module('plunker', []); app.controller('MyCtl', function($scope) { $scope.ImageURL = ""; $scope.ImgWidth = 0; ...

Focus Google Map on Selected Option using AngularJS

I'm attempting to center the map based on a selection in a drop-down select option box. Despite trying various examples, I haven't been successful in getting the map to recenter to the new latitude and longitude coordinates. I'd like to ach ...

Unable to display Boostrap modal upon clicking href link

Can someone help me troubleshoot why my pop modal is not displaying after a user clicks on a specific link on my webpage? I have attempted the following: <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></s ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

Merge arrays with identical names within the same object into one cohesive object containing all elements

I just started using Vue and I'm not entirely sure if it's possible to achieve what I have in mind. Here is the structure I have: { "items":[ { "total":1287, "currency":"USD", "name":"string", "itemID":"", "pro ...

Is there a way to prevent the text in my text boxes from staying there when I refresh the page?

Currently working on an HTML5 project with Javascript, here is a snippet of my code: Your inquiry <textarea type="text" name="phrase" id="phrase" cols="50" rows="5" placeholder="Write your text here. . ."></textarea> I am looking for a way ...

Show me a list of either only development or production dependencies in npm

When attempting to list only the production dependencies from package.json according to the npm docs, I tried: npm list -depth 0 -prod or npm list -depth 0 -only prod However, npm continues to list both dependencies and devDependencies. Can anyone sugg ...

Switch the selected option in JQuery UI dropdown using a clickable button

I have a code snippet that is almost working. My goal is to change the selection of a JQuery dropdown select combobox using a separate button named "next". What I want is for the JQuery dropdown to automatically switch to the next selection every time I c ...

Issue with reactivity in Laravel and Inertia.js using Vue3

Is it possible that the reactivity of Vue is being blocked by Inertia.js page components? Within my Page component, there is a single file component. I have a function that adds items to the ItemsManager.items object. When I run this function, the single ...

Oops! Hardhat Test Error "Error: Virtual Machine Exception occurred while processing transaction: reverted with reason 'Please deposit additional funds'."

Encountering an issue with the following error message: Error: VM Exception while processing transaction: reverted with reason string 'deposit more' in the Hardhat Test.js file Test.js -> it("should be able to withdraw if no one appl ...

The number range filter in ng-table is malfunctioning

what I am trying to accomplish My goal is to create a column that can accommodate two numbers in order to filter numeric data within a specific range for that column. While sorting, pagination, and filtering by 'contain text' are working correct ...

Using JavaScript, create a function that accepts an HTML element as a parameter

I have a script with two functions. One function generates a lengthy HTML string, and the other function processes this string as a parameter. function myFirstFunction() { // Generate HTML content return myHTML; } var myHTML = myFirstFunction(); ...

Discover the secrets to replicating the mesmerizing horizontal scrolling menu akin to the

What is the most effective way to create a horizontal menu similar to the innovative Google picture menu? Could someone kindly share their knowledge and provide the code for achieving the same outcome? ...

Check for duplicate in AngularJS and replace with larger duplicate

I have this piece of code where I am currently checking for duplicates using the isDuplicate boolean. However, I now want to enhance my code by comparing another property called colorId and then setting the isBigger property for the larger one :) Do you ha ...

Organize a collection of items in AngularJS

Consider the following array: var members = [ {name: "john", team: 1}, {name: "kevin", team: 1}, {name: "rob", team: 2}, {name: "matt", team: 2}, {name: "clint", team: 3}, {name: "will", team: 3} ]; I want to create an unordered list for each ...

Having trouble inputting text into a numerical field with Selenium in Java

I am facing a challenge while testing an input field on a form using Selenium. The form input is of type number with the following attributes: <input required type="number" class="form-control" id="number" name="number" placeholder="Number" step="1" mi ...

Executing a method in an applet using JavaScript

I am trying to print some information using an applet. The applet is located in the signed qds-client.jar file and has the following code: public class PrintText extends Applet implements Printable { private ClientAccount clientAccount; public Client ...

The issue in AngularJS 1.4 where the select element value is not binding due to a type mismatch

My ng-model has a value assigned to it, but it is not binding with the selected element. <select data-ng-model="myval"> <option value="? number:2 ?"></option> <option value="2" class="ng-binding">Value 1</option> <op ...

Leveraging AJAX for database variable checks and PHP and JavaScript to redirect to specific pages based on the results

I am currently exploring the use of AJAX to validate variables in a database. The goal is to redirect to a specific page if the validation is successful. However, during this testing phase, I am not actually checking any variables. My focus is on verifying ...

Container holding a Material-UI drawer

Is it possible to set the material-ui drawer inside a container in reactjs? I have wrapped my app page in a container with a maximum width of 600px. I want the drawer to start within that container instead of on the body page (picture). The app bar positi ...