Delaying navigation to the next URL until a distinct category name is identified

Within this section of JSP code, I am implementing JavaScript and AJAX to validate the uniqueness of a category name. When the submit button is pressed for the first time, it prompts the user to enter a category name. Subsequently, an AJAX call is made to check if the entered category name is unique. If the submit button is pressed again, it redirects to the main URL.

<form name="frm" action="createnewcatgoryBean.jsp" method="post">
    <table style="padding: 5px 0px 0px 8px;">
    <tr>
    <th colspan="2">
    <div style="width: width:271px; color:red;" id="validate"></div>
    </th>
    </tr>
    <tr>
    <th>Category Name<span>:</span></th><td><input id="cat"  onblur="return validatenewcat()" type="text" name="category">
    </td>
    </tr>
    <tr>
    <th>Quotations form<span>:</span></th><td><input type="checkbox" name="quotations"></td>
    </tr>
    <tr>
    <th>Agreement form<span>:</span></th><td><input type="checkbox" name="agreement"></td>
    </tr>
    <tr>
    <th>Payment form<span>:</span></th><td><input type="checkbox" name="payment"></td>
    </tr>
    <tr>
    <th>ETI<span>:</span></th><td><input type="checkbox" name="eti"></td>
    </tr>
    <tr>
    <td colspan="2" style="float:right; padding-top:15px">
    <input type="submit" value="Submit" onclick="return validatenewcat()" style="width: 60px;">
    </td>
    </tr>
    </table>
    </form>

Below is my ajax call script and JavaScript:

function validatenewcat()
{
    var category = document.getElementById("cat").value;
    if(category=="")
    {
        setTimeout(document.getElementById("validate").innerHTML="!PLz Enter The Category Name", 2000);
        return false;
    }   
    else
    {
    var url="catnamecheck.do?id="+category;
     xmlhttp.open("post", url,true);
     xmlhttp.send(null);
     xmlhttp.onreadystatechange=function()
     {
      if(xmlhttp.readyState==4)
      {       
             if(xmlhttp.status==200)
              { 
                 var temp = xmlhttp.responseText;
              if(temp!="")
                 {
                     document.getElementById("validate").innerHTML="!PLz Enter The Unique Category Name";
                     document.getElementById("cat").focus();
                    return false; 
                 }

              }
      }

    }
}


}

This section showcases my Java code:

public Map<String, String> catuniqecheck(String id) {

Connection c = null;
PreparedStatement ps1 = null;
ResultSet rs1 = null;
String sql=null;
try{
    c = JDBCHelper.getConnection();
    if(c!=null)
    {
        Map<String, String> map = new HashMap<String, String>();
        sql="select * from catgory where catgoryname=?";
        ps1=c.prepareStatement(sql);
        ps1.setString(1, id);
        ps1.execute();
        rs1=ps1.getResultSet();
        if(rs1.next())
        {
            System.out.println("insdide of the catuniqecheck");
            map.put("catgoryname",rs1.getString("catgoryname"));
            JSONObject json = new JSONObject();
            json.accumulateAll(map);
        }
        return map;
    }   
   else
     {  
           System.out.println("DB connection Established");
           return null  ;
     }
    }
    catch (Exception e) {
        // TODO: handle exception
           return null  ;
    }
finally{
        JDBCHelper.close(rs1);
        JDBCHelper.close(ps1);
        JDBCHelper.close(c);
   }
}

The following segment pertains to my servlet code:

System.out.println("inside success");
                JSONObject json = new JSONObject();
                json.accumulateAll(result);
                response.setContentType("application/json");
                response.getWriter().write(json.toString());

If you encounter a redirection to another URL when pressing the submit button for the second time, kindly provide guidance. Thank you.

Answer №1

It appears that this is the issue you're currently facing

<form name="frm" action="createnewcatgoryBean.jsp" method="post" onsubmit="return validatenewcat()">
    <table style="padding: 5px 0px 0px 8px;">
    <tr>
    <th colspan="2">
    <div style="width:271px; color:red;" id="validate"></div>
    </th>
    </tr>
    <tr>
    <th>Category Name<span>:</span></th><td><input id="cat" onblur="return validatenewcat()" type="text" name="category">
    </td>
    </tr>
    <tr>
    <th>Quotations form<span>:</span></th><td><input type="checkbox" name="quotations"></td>
    </tr>
    <tr>
    <th>Agreement form<span>:</span></th><td><input type="checkbox" name="agreement"></td>
    </tr>
    <tr>
    <th>Payment form<span>:</span></th><td><input type="checkbox" name="payment"></td>
    </tr>
    <tr>
    <th>ETI<span>:</span></th><td><input type="checkbox" name="eti"></td>
    </tr>
    <tr>
    <td colspan="2" style="float:right; padding-top:15px">
    <input type="submit" value="Submit" style="width: 60px;">
    </td>
    </tr>
    </table>
    </form>

Remember to use on submit in the form tag and not on click in submit type

Answer №2

let arrayOfCats = new Array();
    let i = 0;
function validateNewCategory()
    {
        let isDuplicateCat = false;
        let category = document.getElementById("cat").value;
      if(arrayOfCats.length >= 1){
       for(let j=0; j < arrayOfCats.length; j++){
       if(arrayOfCats[j] == category ){
       isDuplicateCat = true;
         }
         }
       }


        if(category == "" || isDuplicateCat)
        {
            setTimeout(document.getElementById("validate").innerHTML = "!Please Enter The Category Name", 2000);
            return false;
        }   
        else
        {
        arrayOfCats[i++] = category ;
        let url = "checkcategoryname.do?id=" + category;
         xmlhttp.open("post", url, true);
         xmlhttp.send(null);
         xmlhttp.onreadystatechange = function()
         {
          if(xmlhttp.readyState == 4)
          {       
                 if(xmlhttp.status == 200)
                  { 
                     let tempResponse = xmlhttp.responseText;
                  if(tempResponse != "")
                     {
                         document.getElementById("validate").innerHTML = "!Please Enter a Unique Category Name";
                         document.getElementById("cat").focus();
                        return false; 
                     }

                  }
          }

        }
    }


    }

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

What is the best way to extract text using Selenium in Java?

My goal is to extract the text $1.00 from the HTML code snippet below (I already have the xpath, so no need to worry about that). Let's assume the xpath is //*[@id="price-string"] <strong id="price-string">$1.00</strong> ...

aws-lambda Module Not Found

I am encountering an issue in the aws-lambda console every time I try to upload code from a zip file. Oddly, other zip files seem to work fine. The .js file within the problematic zip is named "CreateThumbnail.js" and I have confirmed that the handler is ...

Retrieving information from incoming JSON within a Java servlet

I have a client sending me a JSON file via HTTP PUT. Here is the content of the file: { "nomPers": "Testworking", "prenomPers": "WorkingTest", "loginPers": "Work", "pwdPers": "Ing", "active": true }, For my WebService framewo ...

Is there a way to calculate the distance in kilometers between two sets of longitude and latitude in an Android application?

Explanation: This question may sound repetitive, but I have encountered some confusion while working on a live application. The JSON data contains longitude and latitude values which I need to compare with the current coordinates. Despite attem ...

Is it possible to update parent data using a child component?

What is the correct way to update parent data using a child component? In the child component, I am directly modifying parent data through props. I'm unsure if this is the right approach. According to the Vue documentation: When the parent proper ...

What is the method to receive a JSON response rather than an HTML response following a curl request with Express?

I am developing a simple application with basic CRUD functionality using technologies like Express, Mongoose, and MongoDB. The app allows users to submit a form with Owner, Caption, and ImageURL. Everything works fine when testing locally, but I encountere ...

Construct a new table by extracting information from a JSON-formatted column in another table

Currently, I am using a Postgres server and here is the structure of my table: The genres of each movie are stored in a column in the following JSON array format: [ {'id': 18, 'name': 'Drama'}, {'id': 36, 'nam ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

What is the best way to access multiple superclass objects in various methods within a single subclass?

Currently, I am working on writing automated tests using Java + Selenium WebDriver. While my test is functioning correctly at the moment, I believe there is a quality issue with the code - particularly with the frequent calls to objects of the superclass i ...

Preventing undesired form submissions in HTML and JavaScript

My question might be simple, but it's what I have in mind. When working with two buttons in HTML - one for form submission and the other to trigger a JavaScript event - both buttons end up submitting the form. How can I make sure the second button onl ...

Update the page when the React route changes

I am facing an issue with a function in a component that is supposed to load certain variables when the page is fully loaded. Interestingly, it works perfectly fine when manually reloading the page. However, if I use a NavLink to navigate to the page, the ...

Automatically integrating Nivo Lightbox into your website

I incorporated Nivo Lightbox into my website, seamlessly integrating all images with the plugin using the following code: <div class="portfolio-item"> <div class="portfolio-thumb "> <a class="lightbox" data-lightbox-type="ajax" title="Strat ...

Tips on implementing Dynamic arrays in the useEffect hook within React applications

Does anyone have experience with using a dynamic array as input in the dependency array of the useEffect hook? I'm encountering an issue where the array is being passed as a string and therefore not triggering the hook correctly. const [formData,setFo ...

Instructions on merging elements in an array with identical property values

Consider the array below: [{a:1,b:1},{a:5,b:2},{a:10,b:2},{a:20,b:3}] Is there a way to create a new array that merges elements with the same b value, while adding up the corresponding a values? The desired output should be as follows: [{a:1,b:1},{a:(5+10 ...

Syncing the local database with the remote database and back again

Currently working on a web application project using PHP where I need to ensure that the local MySQL database stays in sync with a Java desktop version of the same application. Additionally, I also require the local database to be synchronized with a rem ...

Searching for a document using the $eq operator in MongoDB within the context of Next.js - what is

In my Next.js code, I am fetching a document from MongoDB using a unique slug. Here is the code snippet: export async function getStaticProps(context) { const postSlug = context.params.postPage; const { db } = await connectToDatabase(); const posts ...

What is the best way to ensure the height and width of a Next.js image matches the dimensions of the original image?

Currently, I am working on setting up an image gallery with a layout similar to Masonry. This layout involves multiple columns, all with the same width, adjusting based on the viewport width. The height of each item in the gallery is flexible, depending on ...

Enhancing Rails: Tailoring the flash message to suit individual needs

I am embarking on my journey with ruby on rails and could use some guidance with the following scenario. In the application.html.erb file, flash messages are configured to fade out after a few seconds by default. <div id="message" class="modal alert a ...

What is the best way to create ng-options that only display unique values?

I am trying to modify my ng-options element so that it only displays unique values. Currently, it looks like this: https://i.sstatic.net/5CtSk.png However, I want it to display one value at a time. For example: <select class="form-control" ng-model=" ...

Steps to Transform String Array into Prisma Query Select Statement

I have a requirement to dynamically select Prisma columns based on client input: ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'] The desired format for selection ...