What is the best way to transfer data from JavaScript to servlet?

My JavaScript code sends coordinates to a Servlet for processing.

The JavaScript function retrieves coordinates from a JSP page like this:

 function main1() {
  $.ajax({
    url: 'ServeltConnection',
    type: "GET",
    dataType: "json",
    data: {
       latitude: pos.lat,
       longitude: pos.lng,

     },
    success: function(data){

    //call of functions
    }
});
}     

I then pass these coordinates to my Servlet in order to receive a JSON response.

In my Servlet:

 public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
        response.setContentType("application/json");
        PrintWriter out = new PrintWriter(response.getWriter(), true);
    List<Shop> shops;

    try{

    //code for connecting with database
            shops=getShops(request.getParameter("latitude"),request.getParameter("longitude"));

        String json = new Gson().toJson(shops);
        response.getWriter().write(shops);
        db.close();

} catch (Exception ex) {
  out.println("Exception: " + ex.getMessage());

While I can successfully retrieve a JSON response using specific coordinates, I encounter issues when trying to obtain coordinates from the JS. I suspect that the problem lies in how I parse longitude and latitude values from the JS. I have looked into parsing JSON but have been unsuccessful so far. Can anyone provide guidance on how to resolve this issue?

Answer №1

Ensure to include parameters in GET requests within the URL, similar to this format:

url: 'ServeltConnection?latitude="+pos.lat+"&longitude="+pos.lng+"'

Also remember to exclude the 'data' parameter

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

Experiencing difficulty with deserializing JSON in C# language

I'm encountering some errors while trying to deserialize the data example below. My goal is to extract the id value, but I am facing difficulties in achieving that. {"object":"payments","entry":[{"id":"546787862118679","time":1417135022,"changed_fiel ...

Array of class properties in Typescript

Is there a way to iterate through the properties of a class or a new object instance of that class when none of the properties are set? When I use Object.keys(), it returns an empty array because no properties have been initialized. How can I achieve this ...

Create a customized MUI select component with a label, all without the need for assigning an

One issue I am facing is with the Material UI React select component being used multiple times on a page. In the examples, all labeled selects use InputLabel with htmlFor that must match the id of the select. The challenge is that I cannot assign an id t ...

Utilizing AJAX requests in PHP's MVC framework

I am currently working on a game site using a combination of php and javascript. All my classes and data are stored in php and then encoded into json format. The view calls a javascript file which, through an ajax request, retrieves the php data encoded in ...

Discovering all jQuery functions employed in a JavaScript file can be accomplished through the utilization of regular expressions

I have a somewhat unconventional idea that I want to share. The project I'm currently working on has an old front-end codebase that is causing the website to run slowly, with jQuery being a major factor. My plan is to develop a tool that can analyze a ...

The function is trying to access a property that has not been defined, resulting in

Here is a sample code that illustrates the concept I'm working on. Click here to run this code. An error occurred: "Cannot read property 'myValue' of undefined" class Foo { myValue = 'test123'; boo: Boo; constructor(b ...

Navigating through JSON object using Angular 2's ngFor iterator

I want to test the front end with some dummy JSON before I write a service to get real JSON data. What is the correct way to iterate through JSON using ngFor? In my component.ts file (ngOnInit()), I tried the following code with a simple interface: var js ...

Discovering the color of a locator (Button/Label) through a CSS locator in Selenium: What's the method?

I have a set of automation scripts in place that handle the downloading and saving of files from a server. These scripts also involve moving the downloaded files from the downloads folder to a user-specific location. When this process is complete, the co ...

Leverage information from graphql API response to enhance functionality in React components

Hey there, I'm facing a little challenge that's been keeping me stuck for a while now, so any advice or guidance would be greatly appreciated! Currently working on a react app where I'm making a call to a GraphQL api using apollo. Within an ...

Explore the power of accessing XML data using JavaScript

Currently, I am dealing with an XML file and attempting to extract data from it. The structure of the XML file is as follows: <doc> <str name="name">Rocky</str> <str name="Last_name">balboa</str> <str name="age ...

Include JSON information in the middleware request

I have recently started working with express and node, and I am currently working on a task that involves adding JSON data to middleware request. Here is the approach I have devised: Within my middleware, I need to include certain details in the request s ...

Extract the data from a JSON object

I am working with a Json string that looks like this: var Result= [{"CompanyID":32,"Roles":["Admin"]}] My goal is to extract the value of CompanyID from this data. One method I attempted was: var obj = JObject.Parse(Result); int Id=obj["CompanyID"]; ...

Converting a JSON object to an array with the help of JavaScript

Looking for help with converting and pushing data from a jQuery ajax request in json format into an array. Thanks in advance. [{"Day":"Nov 03","Saavor Kitchen":null,"Home Kitchen":2,"Restaurant":null}, {"Day":"Nov 06","Saavor Kitchen":null,"Home Kitchen": ...

Employing forward slashes as the template delimiter in JavaScript for HTML

let a = 1.10; let html = '<div>'\ '<strong>' + a + '</strong>\ //error here </div>'; console.log(html) Can you identify the issue in the code above? The intention is to insert a variab ...

Ways to extract a variable from a JSON URL

I'm having trouble extracting a specific variable from a URL parameter. The URL in question is: .com/?asset=[{"AssetId":524,"DerivativeDefinitionId":6,"DerivativeId":816,"FileSizeInBytes":57131}] Below is the code I've been using to retrieve t ...

AngularJS custom directive with isolated scope and controller binding

I am looking to create a directive that includes both scope parameters and ng-controller. Here is the desired structure for this directive: <csm-dir name="scopeParam" ng-controller="RegisteredController"> <!-- Content goes here--> {{na ...

Image uploading in Angular is not compatible with Internet Explorer, however, it functions correctly in Google Chrome

As of now, my implementation has been successful in all browsers except for Internet Explorer 11. Despite being able to successfully upload .jpeg, .jpg, and .png images in Google Chrome, I am facing issues when trying to upload them in IE 11. The code wo ...

Updating the database with values dynamically using ajax without the need to refresh or change the current page

My current challenge involves adding records to a database table without the need to reload the page. I've implemented ajax for this purpose, but have been receiving an unexpected response (201) from the server (alert("Error occurred !")). Despite spe ...

Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is th ...

Identical code exhibiting varying behavior between localhost:3000 and the production server at localhost:5000 on the web

I'm currently in the process of learning React Js, but I've been encountering a persistent error that has me stumped. A specific component functions perfectly when running on my local server (localhost:3000), but as soon as I try to deploy it to ...