The transmission of information via Java, Ajax, and json through web services is currently experiencing issues

Seeking assistance with a persistent error in my code. It keeps returning an error, but no error message is displayed, only the console.log. Any suggestions on how to debug this issue or if you could identify what's wrong?

Thanks! Sami

function foo(){

        alert('Button pressed');
        var user={"id":10,"firstName":" Ted","lastName":"TESTING","age":69,"freeText":"55555","weight":55};

        $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "http://localhost:8080/testSoft/webresources/entity.user/",
        dataType: "json",
        data: user,

        success: function(data){alert(data);},
        error: function(data) {
        console.log('#####################error:################################'+data);                 
        alert('addUser error: ' + data.firstName);
        }
        });
        };

Web service:

@POST
@Override
@Consumes({"application/xml", "application/json"})
public void create(User entity) {
    super.create(entity);
}

User

public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 45)
@Column(name = "firstName")
private String firstName;
@Size(max = 45)
@Column(name = "lastName")
private String lastName;
@Column(name = "age")
private Integer age;
@Lob
@Size(max = 65535)
@Column(name = "freeText")
private String freeText;
@Column(name = "weight")
private Integer weight;

Answer №1

Can anyone explain why this code works outside the function but not inside it? When I try to call the function on a button, it doesn't work:

<button type="submit" class="btn btn-primary" id="btnAddUser" onclick="foo()">Register</button>

However, it does work when the code is placed outside of the function:

<script>
            var user={"id":10,"firstName":" Coka","lastName":"CocaCola","age":69,"freeText":"55555","weight":55};
            alert('user----->' +user.firstName);
            $.ajax({

            type: "POST",
            contentType: "application/json",
            url: "http://localhost:8080/testSoft/webresources/entity.user/",
            dataType: "json",
            data: JSON.stringify(user),

            success: function(data){alert(data);},
            error: function(data) {
            console.log('#####################error:################################'+data);                 
            alert('addUser error: ' + data.firstName);
            }
            });
        </script>

I struggle with JavaScript and I have a strong dislike for it, now even more so :(

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

The issue in Vue JS arises when trying to access JSON key values from an object array using v-for

I am currently working on parsing a list of objects found within a JSON payload into a table utilizing Vue.js. My goal is to extract the keys from the initial object in the array and use them as headings for the table. While the code I have in place succe ...

Reset all divs to their default state except for the one that is currently active using jQuery

Here's the plan for my script: Once a user clicks on a "learn more" button, it will reveal the relevant information in the corresponding box. I'm aiming to implement a feature where if you click on another "learn more" button while one box is a ...

Executing a Javascript function when a form is submitted

function validateForm() { alert("Form submitted successfully"); return true; } <form onsubmit="return validateForm()" action="add.php" method="post" id="p1"> <center>Add New Survey</center> <p>&nbsp;&l ...

Having trouble with changing the selected value in JQuery?

I'm attempting to use jQuery to set the select option, but I'm encountering an issue. It is setting the value properly, but the text is not being updated. I've experimented with .prop('selected',true), .attr('selected',t ...

Animate the sliding of divs using the JavaScript animation function

I've designed some boxes that function similar to notifications, but now I want to smoothly slide them in from the left instead of just fading in. I know that I need to use .animate rather than .fadeIn to achieve this effect. The code snippet I&apos ...

AJAX issue: "Content-Type header is missing the multipart boundary parameter"

Currently, I am encountering an issue while attempting to transfer a file from localhost to a server. The error message displayed in my network console is as follows, with status code 500: "no multipart boundary param in Content-Type" To address this p ...

Utilize orientation detection technology to ascertain the exact placement of an image

On my HTML page, I have a centered header (h1) with a title that displays in portrait mode above an image. When switching to landscape orientation, I want the image to move to the left side of the title. I've experimented with using <br> along ...

Tips on displaying only the child of the current list item while hiding the children of other list items

I have multiple nested ul elements on my page that are displayed using the following jQuery code. jQuery $("li").click(function(){ $(this).children("ul").show("slow"); }); However, I want to only display one nested ul at a time. This means that when ...

What causes the entire page to refresh when using ValidatorCallOut in the Ajax Control Toolkit?

After downloading the Ajax Control Toolkit, I am trying to integrate its components into my project. I have utilized the ValidatorCallOut Component as an extender for a Textbox, so that when the user switches focus to another Textbox, the ValidatorCallOu ...

Issue with dropdown element not triggering JavaScript onchange event

I am in the process of developing an application that involves searching a database and enabling users to compare the results. To achieve this, I require multiple dependent drop-down menus. While I have some understanding of HTML and PHP, my coding experti ...

Tips for removing borders from the AJAX Loading icon in jQuery Mobile

Is there a way to remove the borders from the default jQuery Mobile loading icon? I am attempting to call the ajax-loading.gif icon before any page creation. $(document).on('pagebeforecreate', '[data-role="page"]', function ( ...

Problem with z-index in VueJS: Child div z-index not functioning within v-dialog

I am facing an issue where I have brought a span to display a loading image inside the v-Dialog of a vuejs screen. The problem is that the v-dialog has a z-index of 220 set as inline style, causing my new span (loading image) to appear below the v-dialog. ...

What is the best way to replicate an Ajax call similar to the way Postman does it?

After successfully retrieving JSON data from a URL using Postman, I received an array as a JSON string. Below are screenshots of the process: https://i.stack.imgur.com/6uLSS.png https://i.stack.imgur.com/vDF0L.png I now want to achieve the same result u ...

Tips for invoking a url with JavaScript and retrieving the response back to JavaScript

I am trying to make a URL call from JavaScript with a single parameter, and the URL should respond to that specific request. Here is an example of the response format: {"success":true, "result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireT ...

Troubleshooting: jQuery toggle() issue in Firefox 3.0.12

My jQuery code for toggling is working perfectly in IE6 but not in FF3. I'm wondering what could be causing this issue and if there is a workaround available. <button>Toggle Me</button> <p>Hi</p> <p>Learning jQuery&l ...

Retrieve various JSON entities using Java

Currently, I am facing an issue while trying to retrieve data from Json in Java code. Even though I have written the necessary java code for this task, I am only able to access the "title" field with a value of Event 1. Additionally, when attempting to acc ...

Node.js retrieves a single row from a JSON array with two dimensions

I am working with a two-dimensional JSON array and I am able to retrieve data from the first dimension using data["dimension-1"], but I am struggling to access data from the second dimension using data["dimension-1"]["dimension-2"]. What is the correct m ...

I tried implementing a progress bar for my JSON post and response, but unfortunately, it is not displaying as expected

I have successfully implemented JSON data posting to the server. However, I am facing an issue with integrating a progress bar to show the progress. The progress bar is not displaying at all despite the data being posted and response received. @Override ...

A guide on iterating through a JSON object fetched using Http in Angular 2/Typescript

I am attempting to extract specific data from my JSON file using http. The structure of the JSON is as follows: [{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}] To loop through this retrieved object, I use the following ...

What is the best way to pass an array to PHP and then display it in HTML?

After setting up a form with 3 select tags in my HTML, I attempted to create an array using jQuery and send it to PHP. The goal is to retrieve data from PHP and display it on my HTML page. Below is the code snippet: HTML code <form name="myform"> ...