Parameterized query causing JavaScript error

As I struggle with this issue for more than a day now, a scenario unfolds where a user clicks on a link of a book name triggering me to read that book's name. Subsequently, an Ajax request is made to a Jersey resource within which a method in a POJO class interacts with the database to retrieve data for sending back to the Jersey resource. Despite encountering numerous errors along the way and resolving them one by one, I find myself currently stuck at a specific error:

The dreaded SQL syntax error looming over my query execution: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1

Let’s delve into my JavaScript code:

function dealWithData(nameOfBook){

    var bookName = encodeURI(nameOfBook);

    console.log("http://localhost:8080/library/rest/books/allBooks/"+bookName);

    var requestData = {

            "contentType":  "application/json",
            "dataType":     "text",
            "type":         "GET",
            "url":          "http://localhost:8080/library/rest/books/allBooks/"+bookName

**//beforeSend has been added as an edit to original code**

beforeSend: function (jqXHR, settings) {
              var theUrlBeingSent = settings.url;
              alert(theUrlBeingSent);
}
    };

    var request = $.ajax(requestData);

    request.success(function(data) {

        alert("Success!!");
    });

    request.fail(function(jqXHR, status, errorMessage) {
        if((errorMessage = $.trim(errorMessage)) === "") {
            alert("An unspecified error occurred.  Check the server error log for details.");
        }
        else {
            alert("An error occurred:  " + errorMessage);
        }
    });
}

In the aforementioned code snippet, the inconsistency between the url being shown in the console.log line—encoded with %20 for spaces—and the unencoded URL in the 'requestData' variable baffles me.

Moving on to the resource code:

@GET
    @Path("/allBooks/{bookName}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getBook(@PathParam("bookName") String bookName){

        System.out.println("Book name is: "+ bookName);
        BookInformation bookInfo = new BookInformation();
        String bookInformation =bookInfo.bookInformation(bookName);

        ResponseBuilder responseBuilder = Response.status(Status.OK);
        responseBuilder.entity(bookInformation);

        Response response = responseBuilder.build();
        return response;
    }

Lastly, the bookInformation method:

public String bookInformation(String bookName){

        String infoQuery = "Select * from bookinfo where name = ?";
        ResultSet result = null;
        conn = newConnection.dbConnection();    
        try
        {   
            preparedStatement = conn.prepareStatement(infoQuery);
            preparedStatement.setString(1, bookName);
            result = preparedStatement.executeQuery(infoQuery);
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        try
        {
            if(result != null){

                while(result.next()){

                    availability = result.getString("availability");
                    isbn = result.getInt("isbn");
                    hardback = result.getString("hardback");
                    paperback = result.getString("paperback");
                    name = result.getString("name");

                }
            }
            else{
                System.out.println("No result set obtained");
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        //Constructing the final output using StringBuilder
String finalBookInformation = information.toString();
                    return finalBookInformation;
    }

I had initially set dataType to json resulting in a different error until I realized JSON construction was incomplete hence changed it to text, remedying the issue. While querying with parameters remains unsuccessful, hardcoding database values works flawlessly but prepared statements thwart success. Eventually aiming for JSON output, I seek help primarily to make the current setup functional. Any insights are welcomed. Appreciation extended for any assistance provided thus far in tackling potential encoding or Ajax-related complications. Thank you.

Answer №1

It appears that the problem lies in how your database query is being executed. To resolve this, please update the following code:

preparedStatement = conn.prepareStatement(infoQuery);
preparedStatement.setString(1, bookName);
result = preparedStatement.executeQuery(infoQuery);

to

preparedStatement = conn.prepareStatement(infoQuery);
preparedStatement.setString(1, bookName);
result = preparedStatement.executeQuery();

Answer №2

When utilizing the HTTP GET method, keep in mind that it automatically converts spaces in the URL to %20.

If you switch your method type to POST, everything should function smoothly for you.

Answer №3

If you're looking to utilize HTTP GET, keep in mind that it will involve encoding the URL. To decode the URL on the server-side, you can refer to this resource: Learn how to perform URL decoding in Java.

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

JavaScript watermark with alternating/dual mode

In the following code snippet, I have implemented a function to make window.status switch between displaying "a" and "b." function alternateViaIntrvl() { setInterval('alterStatus()', 500); } var altrCounter = 0; function alerted() { var ...

A guide on converting the http response body into a json format in the Go programming language

When I receive a response body, the format of the body is like this: [ { "id":1, "name":"111" }, { "id":2, "name":"222" } ] I am trying to parse ...

Tips for resolving the issue: SyntaxError - Unexpected token import

I've encountered this error in the past and have looked at other solutions, but none of them seem to work for my specific issue. My package.json file includes the following dependencies: "dependencies": { "axios": "^0.15.2", "babel": "^6.5. ...

Create a function that triggers a fade-out effect on one button when another button is clicked

Hello everyone! I'm still getting the hang of things around here so please be kind. I need some assistance with my weather app project. Specifically, I've created two buttons and I want to make it so that when one is clicked, the other fades to g ...

What is the process for adding my JSON data to a select dropdown list?

Looking to populate a selectlist in HTML with options retrieved from an API. Below is the HTML code : <div id="example" role="application"> <div class="demo-section k-header"> <select id="FeaturesSelec ...

Tips for ensuring proper dependency regulations in javascript/typescript/webpack

In essence, I am in search of a method to limit dependencies, similar to how one would manage different projects (libraries) in Java or C#. Think of it as friend or internal access modifiers. I'm considering various approaches to accomplish this (suc ...

Trimming Picture on User's Device

Currently, I am utilizing the jQuery ImgAreaSelect 0.9.10 plugin to crop images that are uploaded by users. The data input format being used is "multipart/form-data". Upon cropping an image with the plugin, it provides me with coordinates in pixels. Howev ...

What is the process for adding JSON data to a dropdown menu using PHP AJAX?

I am trying to populate a select html element with data from a list of JSON results. Here is the code I have attempted: JSON output: jquery loop on Json data using $.each {"Eua":"Eua","Ha'apai":"Ha'apai",& ...

Adjust the DOM based on the output of the function

I'm currently working on creating a list where only one element can be active at a time. The state is updating correctly, but I'm facing an issue with the isActive function. It only activates initially and doesn't trigger when the state chan ...

Python is having trouble processing the JSON file due to its unique format, making it impossible to load and read

I'm struggling to properly process the JSON data in the following format. Whenever I try to load the JSON file, I encounter an error indicating extra data present in the file. Any assistance with this issue would be greatly appreciated. {"From":{"$ty ...

Execute the eslint loader within the node_modules of a specific directory that is npm linked and has not been compiled

One of the benefits of using webpack 4 is the ability to run eslint across the entire project folder with a specific configuration. { enforce: 'pre', test: /\.js|ts$/, exclude: /node_modules/, loader: 'eslin ...

Best way to create a 3D array in PHP

I am trying to structure an array in PHP that resembles the following format: _________________________________________ |time | event | childEvents | |_____|_______|__________________________| |9:00 |Event1 | String[]{subE11, subE12} | |_____ ...

Transferring data from a CSV file stored in AWS S3 to an AWS RDS Mysql

I am trying to find a command that is similar to Redshift's "copy" command that will enable me to directly load CSV data from an S3 bucket into a MySQL table on AWS RDS (not Aurora). Can anyone help me with this? ...

Using AngularJS to refresh information stored in an array

My objective is to create a basic application that allows users to adjust their availability on weekdays. The code is functioning correctly as it retrieves data from the select box. However, I encounter an issue when trying to update Monday's data and ...

A guide on incorporating router links within a list component in a React project

In one of my projects, I've implemented a navbar with a profile icon that expands to show four different options: "Log in", "Register", "Edit", and "Admin". However, I'm facing an issue where clicking on these links doesn't always redirect m ...

The drop-down does not move above the subsequent div when focused

I have implemented a dropdown feature on focus of an <input type='text'> box in the following manner http://jsfiddle.net/Newtt/7ffdF/ The issue I am facing is with the positioning of the dropdown box. It currently displaces the content of ...

What is the best way to present these values with spaces in between each word?

When I use console.log(JSON.stringify(selected["1"]?.others)), the output is: ["Cars","Books","Necklaces"] On the screen, however, when displaying this data, all the words appear together without spaces. It looks li ...

JavaScript implementation of Ancient Egyptian Multiplication using PHP code

Let's dive into the algorithm. If we have two integers, A and B (remember, only integers), that need to be multiplied, here is how it works: we continuously multiply A by 2 and divide B by 2 until B cannot be divided any further, or in other words, un ...

What steps should I follow to successfully incorporate Zurb Foundation 4 Sections (tabs) into my Javascript Ajax functionality?

I am currently incorporating Zurb Foundation 4.1.5 into my application and I am faced with the challenge of implementing Zurb Section Javascript to handle "tabs" on the page. The content within these tabs is dynamic and fetched via Ajax calls. I am seeking ...

discord.js fails to provide a response

const fs = require('node:fs'); const path = require('node:path'); const { Client, Collection, Events, GatewayIntentBits } = require('discord.js'); const { token } = require('./config.json'); const client = new Clien ...