Troubleshooting Problems with Ajax Servlets

When I perform a search, the results are returned and shortly after, the page redirects to a servlet displaying raw JSON data. It's a bit confusing for me.

This JSP form submission:

<form class="col-lg-12" action="./urllinks" method="GET" id="searchform">

                        <div class="input-group"
                            style="width: 340px; text-align: center; margin: 0 auto;">
                            <input class="form-control input-lg" title="Make a wish !."
                                placeholder="Go on and search ! Don't be shy :p" type="text" id="box"
                                name="query"> <span class="input-group-btn"><button
                                    class="btn btn-lg btn-primary" id="searchresult" type="submit">Search</button></span>
                        </div>

</form>

This is the Servlet GET method:

    String word = request.getParameter("query");
    List<Page> results = DynamoDbMethods.search(word);

    String reply = new Gson().toJson(results); 

    response.setContentType("text/json"); 
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write(reply);

This is the JavaScript AJAX:

$('#searchform').submit(function(){
            var query = $("#box").val();

        //  alert(query);
            $.ajax({
              target:"#map", 
                dataType: "json",
                type: 'GET',
                data:{query: query},
                url: 'http://localhost:8080/path/urllinks',
                success: function(response) {
                    successCallback(response);}

          });
        });

function successCallback(responseObj){
  #This function just prints the data on a table
  #e.g 
 $.each(responseObj, function(index, element){ alert(element.title);}

}

I attempted to remove action="./urllinks" method="GET but then no data was retrieved.

Answer №1

Seems like you forgot to stop the default non-ajax form submission from happening.

In your function, make sure to include an event parameter and use it to prevent the default action.

$(document).ready(
    function () {   
        $('#searchform').submit(   
            function(event) {
                event.preventDefault();
                //rest of the code
            }
        );
    }
); 

Alternatively, there is a jQuery plugin available that simplifies this process into just a few lines of JavaScript.

http://jquery.malsup.com/form/

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

The system displayed an 'Error' stating that the variable 'index' is defined in the code but is never actually utilized, resulting in the (no-unused-vars) warning

I have configured eslint and eslint-plugin-react for my project. Upon running ESLint, I am encountering no-unused-vars errors for every React component in the codebase. It seems like ESLint is not properly identifying JSX or React syntax. Any suggestions ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...

How to pass an item as a parameter to a computed property in Vue.js, and have it return a sorted child array within a

After spending some time searching on Google, I am still struggling to find a solution for this issue. I have a list of "Intents" that contain nested lists of "Entities" created using v-for loops. The Intents are already computed, but now I need to dynam ...

Experiencing difficulties coding SVGs

Struggling with manipulating SVGs in JavaScript and looking to extend a line by clicking a button? Check out this code snippet I've included in the head tag: <script type="text/javascript"> x=135; y=135; var container = document.getElementById( ...

What is the recommended approach for handling broken pipe errors in Flask when the client disconnects unexpectedly?

During development using Flask, I have set up a view for an AJAX request like so: @application.route('/xyz/<var>/', methods=['GET']) def getAjax(var): ... return render_template(...) In addition, I have enabled threaded= ...

Error in React .js: Unable to access property 'name' as it is undefined

I keep encountering this issue: Uncaught TypeError: Cannot read property 'name' of undefined In my code, I have a user object defined in the App.js file. However, when I attempt to access its properties within my Person component, it throws a ...

calculating the duration between successive PHP form submissions

I am trying to calculate the duration between when a user submits a PHP form and when they submit it again. The form reloads on the same page, essentially refreshing it. Additionally, the user may enter the same data again. I want the timer to start runnin ...

The MySQL error wreaks havoc on the Node.js server, causing it to

Whenever there is an error or exception coming from MySQL, my nodejs server ends up crashing. This is the code snippet from my backend where I tried using if-else in the query function to handle the response, but it still crashes the server. Even with try ...

Ajax facilitates the loading of multiple containers

My goal is to utilize Ajax to load dynamic content. The process starts with a list of countries. When a country is selected, the cities in that country are displayed, followed by suburbs, companies, branches, and eventually branch details: Countries --> ...

Combining objects using ES6 import/export with async/await functionality

I am facing a situation where I have two files named config.js and config.json and my goal is to combine them into one object and then export it: config.json { "c": 3 } config.js import fs from "fs"; import fse from "fs-extra& ...

Tips for utilizing the "Sign In with Apple" feature through Apple JS

For implementing "Sign In with Apple" on a web platform using Apple JS, you can refer to the code example available at this link. Now, the query arises: where can I find the Client ID required for this process? I have tried using the app id identifier fro ...

What is the best way to locate a div element with a specific style?

What is the method to locate a div element by its style? Upon inspecting the source code in IE6, here is what I find: ...an><div id="lga" style="height:231px;margin-top:-22px"><img alt="Google"... How can this be achieved using JavaScript? ...

Leveraging the power of jQuery's $.when and $.then methods for efficiently managing multiple AJAX requests that do not

My goal is to utilize jQuery to retrieve data from both an XML and JSON feed, and then only log the data when both requests are successful. When I comment out getRoomFeed() within the $.when, it returns the correct responseText object for the XML. However ...

Failure to retrieve data with ajax call in php script

I am a beginner in the world of JS and PHP. I am taking on the challenge of teaching myself. Following the guidance provided in this answer from Stack Overflow, I attempted to implement it in my project. Unfortunately, I am facing challenges and would gre ...

A guide to activating an input field based on the value of another input field in AngularJs

An AngularJs form requires the user to input the number of hours worked. If the value entered is 0, an additional question should be displayed for the reason why no work was done. <label>Hours worked:</label> <input ng-model="hours" type="n ...

Executing asynchronous Django AJAX calls on a single URL

I'm encountering an issue with submitting forms in Django. I have two forms, each needing to insert a specific number into the database. Form1: should insert value 1 Form2: should insert value 2 Both forms are located at the URL /kategorije/. When ...

Delay the execution of the function in AngularJS until the browser has finished rendering completely and the view-model synchronization cycle has ended

I'm uncertain about the appropriate title for this inquiry, so please correct me if I am mistaken. Suppose that upon page refresh (load), I require an animated scroll to an anchor based on the current location's hash (I am aware of ngAnchorScrol ...

Ways to show dynamic text according to slider adjustments

I am struggling with adding an if condition to my form that includes a horizontal slider. My goal is to display text based on the position of the slider. Can someone offer some guidance on this, please? Here's my HTML code snippet: <form method=" ...

The React Stripe API is functioning perfectly on local servers but encountering issues in the live environment

Just when I thought I was almost finished, reality hits me hard! My deadline is right around the corner! I finally got everything working on my local machine with a stripe payment form. However, when I pushed it live, I received an error message from my A ...

What is causing my React Query query function to be activated even though it is supposed to be disabled?

My goal is to dynamically set parameters and select a fetching function within a React Query function (useSpeciesCodes.js). The decision of which API endpoint to fetch from (using either getSpeciesCodesByRegion or getSpeciesCodesByAddress) should be based ...