Trouble arises when attempting to use JavaScript, JSP, and JSON in conjunction with

I am in the process of creating a client-server application where I send a request from the client to the server using a JSON object for registration. However, despite receiving a JSON response with an "OK" field as expected, the client keeps triggering the .fail function instead of the .done one (I apologize if my terminology is not entirely accurate, as I am new to this).

Below is the code I have written for reference:

Client-side JavaScript:

define(['ojs/ojcore', 'knockout', 'jquery', 'appController', 'jquery', 'ojs/ojknockout', 'ojs/ojinputtext'],
 function(oj, ko, $, app) {

    function RegistrarseViewModel() {
        var self = this;
        this.email = ko.observable();
        this.pwd1 = ko.observable();
        this.pwd2 = ko.observable();
        this.registrar = function(){
            alert("Registration request sent");
            var p = {tipo:"Registrarse", email: this.email(), pwd1:this.pwd1(), pwd2:this.pwd2()};
            $.ajax({
                type: "POST",
                url: "http://localhost:8080/ServidorWeb/Registrarse.jsp",
                data: "p=" + JSON.stringify(p)
            }).done(function(data, textStatus, jqXHR){
                alert("Checking type");
                if (data.tipo == "OK"){
                    sessionStorage.jugador = self.email();
                    app.router.go("login");
                    alert("Registration successful");
                } else {
                    alert(respuesta.texto);
                }
            }).fail(function() {
                alert("Sorry. Server unavailable.");
            });
        }

        this.cancelar = function(){
            app.router.go("login");
        }
    }
    return new RegistrarseViewModel();
  }
);

Server-side JSP:

<%@ page language="java" contentType="application/json ; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import= "org.json.*,dominio.Manager"%>
<%
String p = request.getParameter("p");
JSONObject resultado=new JSONObject();
try{

 JSONObject jso= new JSONObject(p);
 if(!jso.getString("tipo").equals("Registrarse")){
  resultado.put("tipo","NOK");
  resultado.put("texto","Unexpected message");
 }else{
  String email=jso.getString("email");
  String pwd1=jso.getString("pwd1");
  String pwd2=jso.getString("pwd2");
  Manager.get().registrarse(email,pwd1,pwd2);
  resultado.put("tipo","OK");
  resultado.put("texto","You have registered with the email " + email);
 }
}
catch(Exception e){
 resultado.put("tipo","NOK");
 resultado.put("texto","Unexpected message");
}
%>

<%=resultado.toString()%>

After executing Manager.get().registrarse(email,pwd1,pwd2); (which handles the registration logic in MongoDB), it proceeds with the resultado.put("tipo","OK"); line, indicating that the issue does not lie within this area.

In addition, when I make a request like http://localhost:8080/ServidorWeb/Registrarse.jsp?p=%7Btipo:%22Registrarse%22,email:%2233%22,pwd1:%2220%22,pwd2:%2220%22%7D from a browser such as Google Chrome, it returns {"texto":"You have registered with the email 33","tipo":"OK"}, but for some reason, the .done function is not triggered on the actual client side.

I sincerely hope someone can offer assistance on this matter.

Thank you in advance.

EDIT 1: Added the server response from the browser console IMAGE

Answer №1

After much perseverance, I was able to resolve this issue.

I discovered that adding a specific line at the beginning of the .jsp file was necessary. It turns out TomCat has a security feature that restricts communication between different machines, and without this line, it was blocking access.

response.setHeader("Access-Control-Allow-Origin", "*");

Answer №2

To utilize jQuery correctly, it is recommended to use the serialize function from jQuery. https://api.jquery.com/serialize/

Start by assigning an id to your form, for example:

`

$("#myform form").submit(function(event){
      event.preventDefault();
    
        var sendData = $("#myform form").serialize(); 
        $.post("your-PHP-handler.php", sendData);
   });
<form id="myform" method="post" action="your-PHP-handler.php">
<input type="name" placeholder="name">
<input type="name" placeholder="age">
<input type="name" placeholder="address">
<button type="submit">send</button>
</form>

`

Keep in mind, when submitting your form using JavaScript, jQuery's serialization captures all inputs in your post and sends them together. You can handle the PHP response inside the $.post() function and refer to the jQuery documentation for more options. In essence, the key concept is to gather all form data and send it to your PHP script.

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

Effortlessly apply mapping, filtering, reducing, and more in JavaScript

Array#map and Array#filter both create a new array, effectively iterating over the original array each time. In languages like rust, python, java, c#, etc., such expression chains only iterate once, making them more efficient in certain cases. While this ...

Ensuring proper alignment within anchor links and buttons

button, a { height: 30px; display: inline-block; border: 1px solid black; vertical-align: middle; } button > div, a > div { width: 30px; height: 10px; background-color: red; } <button> <div class="buttonDiv"></div> ...

Challenges with splitting asynchronous code in NPM modules

Earlier, I posted a query on Stack Overflow I have recently established a local package within the main app's package.json: "contact-page": "file:local_modules/contact-page" The package.jsonmain and scripts sections for the contact module are confi ...

Connecting CSS auto-complete with JSP content within Eclipse

Is there a way to connect the CSS autocomplete with the content of a JSP page? For instance, if I have an element like <div id="myid"> in the JSP file, can Eclipse auto-complete "myid" when typing "#" in the CSS file? I am aware that NetBeans has th ...

org.codehaus.jackson.JsonParseException: An unexpected character ("/" (code 47)) appeared

I have a file with a customer list stored as a HashMap in json format. Here is an example: {"John":{"name":"John","id":"12345", "email":"john@test.com","phone":"555-555-5555"}} This represents just one customer from the list. When the controller is ...

Difficulty with CasperJS multi-select functionality

I am currently attempting to utilize CasperJS for choosing both options in a multiple select within an HTML form: <select id="bldgs" name="bldgs" multiple="multiple" size="6" autocomplete="off"> <option value="249759290">Southeast Financia ...

Exploring the performance difference between MongoDB's find and iterate operations compared to

I'm encountering a unique issue with my Mongo database. In our collection, we have 800k documents with the following structure. { "_id" : ObjectId("5bd844199114bab3b2c19fab"), "u" : 0, "c" : 0, "iden" : "343754856", "name" : "alan", "email" : "<a ...

The value buried within multiple layers of JSON tags

I am dealing with a complex JSON string that is deeply nested. Here is an example of the structure: { "decisionElements": [ { "serviceName": "PreciseId", "applicantId": "APPLICANT_CONTACT_ID_1", "decision": ...

How can I access the Gmail app without being taken directly to the message sending screen?

How can I open my Gmail app with a button click without sending a message? Most tutorials show how to send messages using Intent.ACTION_SEND, but I simply want to view my messages list. Should I find the package name and launch the app, or is there a bet ...

Deleting an ID from an array within a document using Node.js Mongoose

In my model document, there is an array that I am working with. I want to be able to remove a specific ID from this array. Is it possible to do so? Below is what I attempted. module.exports.RemoveFavourite = async (req, res, next) => { try { cons ...

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 ...

Could not find the button or link using any of the following methods: xpath, id, name, or css selector

Element not found using specified id, name, xpath or CSS selector Attempts were made with the following codes, but both failed to yield a response wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\'form\']/p/ ...

Learn how to capture a screenshot after every interaction with a web page using Java and Selenium

Is it possible to capture a screenshot after each interaction with a page, such as clicks and scrolls? I am using Selenium with Java. Can someone please provide guidance on achieving this? ...

Encountered an error when attempting to extend the array function: Uncaught TypeError - Object [object Array] does not contain a 'max' method

Hello, I am currently attempting to integrate this function into my code: Array.getMaximum = function (array) { return Math.max.apply(Math, array); }; Array.getMinimum = function (array) { return Math.min.apply(Math, array); }; This is inspired ...

Error encountered while using JavaScriptExecutor to check the page source for a Null Pointer Exception

I am in need of checking if text is present on a website. After reading about how driver.getPageSource() converts signs < to &lt;, I decided to avoid using getPageSource(). To make my function reusable across multiple files, I planned to create it i ...

Preserving Foreign Key Relationships in Django Rest Framework Serializers

Within my project, I have two interconnected models named Task and Batch, linked through a Foreign Key field. My goal is to verify the existence of a Batch Object in the database before creating a new Task Object. The Batch object represents the current da ...

User input determines the path of Iron Route in Meteor

A requirement is to execute a function that prompts the user for input and then navigates to that specified value. For instance, if the inserted value is: https://www.youtube.com/watch?v=_ZiN_NqT-Us The intended destination URL should be: download?u ...

What is the best way to target and focus on all class fields that have a blank value?

<input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="3"> <input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="4"> Is there a way to target o ...

Unable to establish a websocket connection with either Amber or NPM, uncertain of the reason

Amber CLI (amberframework.org) - v0.11.3 Crystal 0.27.0 [c9d1eef8f] (2018-11-01) LLVM: 4.0.0 Default target: x86_64-unknown-linux-gnu npm 3.5.2 Attempting to incorporate sockets using Crystal Lang and Amber has hit a snag. Despite following the guidelines ...

Node.js Link Management: A Guide to Updating Links

For some time now, I've been attempting to update the tabs on my navigation bar (including the links) when a user logs in. The issue arises on the index page, where users can access it both when logged in and not logged in. In my navigation bar, all t ...