What is the best method for comparing the JSP page response with the AJAX page response?

I am experiencing issues when trying to compare the response received from a JSP page with Ajax. I am looking to execute an action in the success Ajax function if the out.print() method prints a success message. Despite comparing the data, it seems like it's not functioning correctly as it always redirects to the else section. Since I am new to Ajax, can someone please assist me in resolving this problem?


$.ajax({
    url: "login.jsp",
    type: "POST",

    data: datatopost,
    success: function(data){

        if(data.search("success") != -1){ 
            console.log(data.data);
            $('#loginmessage').html(data);
            $("#spinner").css("display", "none");
           
            $("#loginmessage").slideDown();
          
        } else {
           
            $("#spinner").css("display", "none");
            
            $("#loginmessage").slideDown();
        }
    },
    error: function(){
        $("#loginmessage").html("<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later.</div>");
        
        $("#spinner").css("display", "none");
       
        $("#loginmessage").slideDown();

    }

});

JSP code...

 <%@ include file="connection.jsp"%>
 <%
 String email=request.getParameter("loginemail");
 String loginpass=request.getParameter("loginpassword");
    ResultSet rs=st.executeQuery("select password from users where email='"+email+"'");
 if(rs.next())
 {
 String password1=rs.getString(1);
 if(password1.equals(loginpass))
  {
    session.setAttribute("email",email);
    out.print("success");

   }
    else
  {
    out.print("invalid combination of email and password");
    }
 } else
     {out.print("this account does not have information");
   }

   %>

Answer №1

It seems like the issue could be related to either the .search() method or the type of data being returned.

Before anything else, it's important to check the console and network tab to analyze the data being sent and received during the AJAX request. If the response is not as expected, then there might be a problem with your JavaScript code.

If you are receiving the expected response, then consider looking into the following code snippet:

$.ajax({
  url: "login.jsp",
  datatype: "text html",
  type: "POST",
  data: datatopost,
  success: function(data){
    console.log(data);
    if(data.search("success") > -1){ 
      console.log("Found 'success' in the AJAX response.");
      $('#loginmessage').html(data);
      $("#spinner").css("display", "none");
      // Display message
      $("#loginmessage").slideDown();  
    } else {
      $("#spinner").css("display", "none");
      // Display message
      $('#loginmessage').html("Login Failed. " + data);
      $("#loginmessage").slideDown();
    }
  },
  error: function(x, stat, err){
    $("#loginmessage").html("<div class='alert alert-danger'>There was an error with the Ajax. Please try again later. (" + stat +", " + err + ")</div>");
    // Hide spinner
    $("#spinner").css("display", "none");
    // Display message
    $("#loginmessage").slideDown();
  }
});

In most cases, the AJAX call will only trigger an error if there's an issue with the Web Server, such as a 401, 404, or 500 error. Therefore, it's crucial to handle most of the functionality within the success block, which indicates a successful response (status 200).

The response package may contain various messages like success,

invalid combination of email and password
, or
this account does not have information
. To verify this, log the response data using the console and test accordingly.

When dealing with AJAX requests, keeping tests straightforward is essential. Using > -1 instead of != -1 can help simplify the logic and avoid confusion.

Answer №2

Have you considered attempting a solution like this?

function crudPost(e) {
    e.preventDefault();
    let name = document.querySelector('#name').value;
    let email = document.querySelector('#email').value;
    let parameters = "name=" + name + "&email=" + email;
    let xhr = new XMLHttpRequest();
    xhr.open('POST', 'process.php', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    xhr.onload = function () {
        if (this.status == 200) {
            console.log(this.responseText)//get response from ur jsp
            
     // do stuff
        }

        let params = "name=" + name + "&email=" + email; //pass values when sending
    }
    xhr.send(parameters)
    form.reset();
}

I may not fully grasp the issue you are encountering with your code, but trying this approach could potentially be helpful.

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 stylize a date using Bootstrap-datepicker?

While this topic is well-known, I have a slightly more complex question regarding it. I have gone through the documentation here. My goal is to display the date in French format (dd/mm/yyyy) and save the value in US format (yyyy-mm-dd). Additionally, I nee ...

Using the onreadystatechange method is the preferred way to activate a XMLHttpRequest, as I am unable to trigger it using other methods

I have a table in my HTML that contains names, and I want to implement a feature where clicking on a name will trigger an 'Alert' popup with additional details about the person. To achieve this, I am planning to use XMLHttpRequest to send the nam ...

i am trying to execute a function in an angularjs controller through html, but the scope variable that i am

Being new to angularjs, I'm looking to understand the process of calling a function defined in a controller from HTML within angularjs. I have written the following code in my HTML: First.html <input type="text" ng-model="model.name" name="name ...

The text geometry remains consistent despite adjustments to the height and size parameters

I am facing a unique issue with text loading in my react three fiber project. The text does render, but it remains extremely small and unreadable, even though I can see a tiny pixel of the text color in the correct position. Strangely, I have not been able ...

AJAX requests the server for information before halting the PHP function's execution

When using jQuery AJAX to send data to the server and then print that data on the server, I encountered a challenge: Here is the PHP code snippet: function someFunc () echo json_encode("some"); } In order to obtain this data in JavaScript: $.ajax( ...

How to convert two arrays into JSON strings and store them in variables using JavaScript

After receiving an ajax response in JSON format, my JavaScript code (within the ajax response success function) stringifies two arrays. Now, I need to assign the data from one curly bracket to two variables, and the data from the other curly bracket to ano ...

Updating a deeply nested JSON structure in PHP, regardless of its complexity, in real time

Seeking to modify a json file with PHP $Folder = $_REQUEST['Folder']; // "wwwroot/JSON/" $File = $_REQUEST['File']; // "JSONOriginalFile.json" $NewJSONValue = $_REQUEST['JsonValue']; // "NewValue" $JsonObject = json_decode($_R ...

Initiating, halting, and rejuvenating a timer in JavaScript

Here is a simple code snippet where I'm experimenting with starting, stopping, and resetting a JavaScript timer. The goal is to have a timer running on a page that sends a message once it reaches the end of its countdown before restarting. The stop b ...

Is there a way to import an image from a different webpage using HTML?

Is it possible to load an image from another page using the load method? Here's an example: $("#result").load(url, 'tag.attribute') However, I am facing a challenge where I need to retrieve the path of the first image from a list on anothe ...

Error occurred while retrieving JSON array using Jquery

var groupMembers = $.parseJSON(members); $.each(groupMembers, function (index, item) { $.ajax({ type: "POST", url: "'.base_url(" / panel / listNotifications ").'/'.$id.'/" + valueSelected, d ...

Is there a more efficient way to handle post data without increasing its size when encoding JSON within a URI

I have a significant amount of data to post, and it needs to be minimized for performance reasons. Initially, my data consists of JavaScript objects which I then convert to JSON format before sending it via POST request. The issue is that my data include ...

Tips for locating the :before element's position with Javascript

I am currently working on an animation where I need to change the color of an element in the center once a small circle touches it. Despite trying to use the position() method, it does not work as intended because I am using a :before for animating the div ...

Eliminate elements from an array within a promise

I am facing an issue with the currentBillCyclePath parameter in the following function. I need to use this parameter to filter out certain elements after executing the query. However, inside the while loop, the value of currentBillCyclePath is undefined. ...

Angular 2, the change event is not triggering when a bootstrap checkbox is clicked

Encountering an issue, the (change) function is not triggering in a specific checkbox. <input [(ngModel)]="driver.glasses" name="glasses" type="checkbox" class="make-switch" (change)="changeFunction()" data-on-color="primary" data-off-color="info"&g ...

The variable remains unchanged after the API call, despite using useState

Despite my efforts to find a solution, I still find myself puzzled by this question that has seemingly been answered before. The issue lies in the synchronization of my code when making a request to the what3words API. The data retrieved is assigned to a ...

When the enter key is pressed in Spring and Vue.js, the request method 'POST' is not supported

One issue I am encountering is that when I click on the search button, everything works perfectly fine. However, if I try to press enter instead, an HttpRequestMethodNotSupportedException error is thrown. The strange thing is that I do not have a POST co ...

The process of authenticating route parameters in Nuxt

I'm having trouble validating route parameters in my page component using the following code: async validate({ params, store }) { await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id) } And here's the corresponding code in the store: ...

Struggling to iterate over key-value pairs in a JSON object?

I am currently working with AngularJS and have successfully retrieved exchange rates from fixer.io. However, I am facing difficulties in extracting both the country and rate data by looping through the key-value pairs. At the moment, I can only access the ...

Using JSX in components versus utilizing dangerouslySetInnerHTML

As I've been digging into React examples and building components, I've hit a wall when it comes to component structure and nesting. It feels like my brain is just not cooperating at the moment. What I'm Looking For: An Input component with ...

Issue with displaying Youtube search API results on EJS template file

I'm currently trying to integrate the YouTube Search API into my website. However, when I make the API call from my route, the results are returned but the page is rendered before the results finish processing - likely due to the asynchronous behavior ...