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

Locate all inputs containing a special attribute name, wherein a portion of the name corresponds to a JavaScript variable

$("td[id^='td' + myvar + '_']") Can someone help me with a solution to substitute the static value of 0 in this code snippet with the dynamic variable myvar? Thanks! ...

Enhance your website with interactive AJAX callback animations using jQuery

I've encountered an issue while using a basic AJAX script in jQuery. I want to implement an easeInOut effect for the AJAX callback to change the HTML smoothly, but I'm not sure how to achieve this. Currently, when the response is received, the co ...

Tips for reducing image file size using ImageMinimizerWebpackPlugin in Next.js (webpack 5)

When attempting to use this plugin for image compression, I am encountering an issue where the build process completes successfully, but the images remain uncompressed. As a beginner with webpack, I'm unsure of what might be causing this problem. Cou ...

`The ng-binding directive seems to be malfunctioning while ng-model is functioning properly

Currently, I am in the process of learning how to utilize Angular (1.3.10). My objective is to create two input fields that will specify the suit and value for a hand of playing cards. In my attempts to achieve this, I have encountered an issue. When I man ...

The placement of the React.js/Next.js Loader is incorrect on the page

While I was trying to display a Loader over everything during data fetching from my API, I encountered a situation where the Loader was not appearing at the expected top level but inside the page itself. Even though the HTML tree showed it at the top level ...

What is the best way to send this JavaScript array to my MVC 3 controller?

When I try to access the controller, I am encountering null values. I can't seem to figure out what's causing this issue. In my grid, there is a list of guests with names and emails, from which users can select guests using checkboxes. I then e ...

Modifying `msg.sender` in Solidity and Ether.js

I have a Smart Contract written in Solidity. Within this contract, there is a function called makeMarketItem. function makeMarketItem( address nftContract, uint256 tokenId, uint256 price ) public payable nonReentrant { IERC721(nftContract). ...

What could be the reason for the Nextjs fetch request returning undefined data?

Here is the code snippet for my GET request in the API section: export default async (req, res) => { const { query: { className }, method } = req; switch (method) { case "GET": try { const classDetail = await Class.findO ...

A curated collection saved in LocalStorage using React JS

I have implemented a LocalStorage feature to create a favorite list, but it only adds one item each time the page is reloaded. The items are retrieved from a JSON file. For a demonstration of how my code functions, check out this link: const [ storageIte ...

Performing a jQuery AJAX POST request to a non-SSL page from a secure SSL page

Here's the scenario: An HTTPS / SSL page Using jQuery A form being submitted via Ajax to a non-SSL page I'm not receiving any useful response. The same situation, but from non-SSL to non-SSL works perfectly. I can see my console log, but I&a ...

What could be causing the Vue.js image component to malfunction?

I am having an issue. I want to create a Vue.js Component. This component displays an image, similar to the <img> tag. If you are familiar with the <img> tag, this question should be easy for you to understand. Here is the code I have: props ...

Avoiding server requests in Firefox by refraining from using ajax

I've implemented the following jquery code: $("#tasksViewType").selectBox().change( function (){ var userId = $('#hiddenUserId').val(); var viewTypeId = $("#tasksViewType").val(); $.post('updateViewType& ...

Utilizing Angular routing in HTML5 mode within a Node.js environment

While I've come across other solutions to this problem, they all seem to have drawbacks. One option leads to a redirect, which could be disastrous for my front-end application that relies on Mixpanel. A double-load of Mixpanel results in a Maximum Ca ...

Having trouble exporting a variable from one Node.js file to another and finding that the value remains unchanged?

Hey there, I've been working on exporting a variable to another file within my nodejs application. I have successfully exported the variable, however, I need it to update whenever a user logs in. Will the export automatically pick up on this change an ...

When the command `scrapy crawl MySpider -o items.json` is run, it generates a separate json

Here is the output as of now (which is not a valid json object): {"id": 1, "name": John} {"id": 2, "name": Tom} This is how I would like the data to be formatted (as a valid json object): [{"id": 1, "name": John}, {"id": 2, "name": Tom}] I am looking f ...

When accessing req.user in code not within a router's get or post method

Is there a way for me to access the data in the User schema outside of a post or get request? I am asking this because I would like to use this information elsewhere. The user schema is defined as follows: const mongoose = require('mongoose'); c ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

PHP not receiving values when making an AJAX POST request

My AJAX file below is where I pass all the values from my text boxes and post them to edu.php. In edu.php, I intend to update two tables - details and test. However, nothing seems to be updating in my database. When I checked the values with var_dump, the ...

Issues with HTML marquee not functioning properly post fadeIn()

I am attempting to create a progress bar using the HTML marquee element. When the user clicks submit, I want to fadeIn the HTML marquee and fadeOut with AJAX success. However, when I click the submit button, the marquee does not fadeIn as expected. Here is ...

Issues encountered with returning a JSON object while utilizing a webservice (.asmx) in ASP.NET

I am currently utilizing an asp.net web service .asmx for the transportation of JSON data. However, I seem to be encountering issues with the following code: $.ajax({ type: "POST", url: "../../App_Code/jsonWebService/getValue", ...