Click here to Skip to main content
15,849,325 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
0


I want to send data from HTML form to rest controller using Javascript, but it is getting null at controller. Can anyone please help me with what mistake I am doing here?

I checked using debugging that the data is reaching from HTML to Javascript page but not from Javascript to rest controller.

This is the HTML code:


HTML
<pre><title>Regsitration Page</title>
    
<script language="JavaScript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script src="/js/IntermediateBtwHTMLAndRest.js"></script>

</head>
    <body>
        <div class="container">
            <table width="100%" height="100%" border="0" cellpadding="0" align="center">
            <tr>
                <td align="center" valign="middle">
                <table class="table-bordered" width="350" border="0" cellpadding="3"cellspacing="3" bgcolor="#ffffff">
        
                    <form action="#" name="registerForm" id="registerForm" method="post">
              
                       
                              <tr>
                                    <td height="25" colspan="2" align="left" valign="middle" bgcolor="#ffffff" class="style2">
                                        <div align="center">
                                            User Registration
                                        </div>
                                        
                                    </td>
                                </tr>

                        <tr>
                            <td>Username</td>
                            <td>
                             
                                <input type="text" name="usernm" id="usernm" autofocus="autofocus" class="form-control" />
                            </td>
                        </tr>
                        <tr>
                            <td>Create Password</td>
                            <td><input type="password" name="pwd" id="pwd" class="form-control" /></td>
                        </tr>
                        
                        <tr>
                            <td>Address</td>
                            <td><input type="text" name="address" id="address" class="form-control" /></td>
                        </tr>
                        
                        <tr>
                            <td>Phone</td>
                            <td><input type="text" name="phone" id="phone" class="form-control" /></td>
                        </tr>
                        
                        
                        <tr>
                            <td colspan="2">
                                <!--<button class="btn btn-info" onclick="restCallToRegister()" align="right">
                                    Register
                                </button>
                                -->
                                <button class="btn btn-info" type="submit" onclick="restCallToRegister()" align="right">
                                    Register
                                </button>
                            
                                
                                <!-- <input value="Submit form" type="submit" align="right">
                                    Register
                                </input>
                                -->
                            </td>
                        </tr>
                    
                </form>
       </table>  
         </td>   
         </tr>  
      </table> 
     </div>  

</body>



Javascript code is:
JavaScript
function restCallToRegister()
{
  
     $('#registerForm').submit(function(e) 
        {
            console.log("Reached Here!!!!!!!")
            e.preventDefault();

            var dataObj = new Object();
            dataObj.email = $("#usernm").val();
            dataObj.password = $("#pwd").val();
            dataObj.address = $("#address").val();
            dataObj.phone = $("#phone").val();
            
            var userJson=JSON.stringify(jQuery($('#registerForm').serializeArray()));
            
            $.ajax({
                url : 'http://localhost:8089/register',
                dataType : 'json',
                contentType : 'application/json; charset=UTF-8',
                type : 'POST',          
                data: userJson,
                beforeSend : function(){
                    alert("before");
                },
                complete   : function(){
                    alert("complete");  
                },
                success : function(data) {
                    alert("success"+data.responseText);
                },
                error : function(data) {
                    alert("error"+data.responseText);
                }
            
            });
            

        });
}


Rest controller is:


Java
@RequestMapping(method = RequestMethod.POST,value = "/register")
    public String registerUser(@ModelAttribute("usersTbl") UserModel ums)
    {
        //System.out.println("OOOOOO="+ums.getUid()+ums.getPwd());
        
        System.out.println("Entered in backend Controller...........");
        System.out.println("UMS________"+ums);
        System.out.println("PPPPPP="+ums.getUid()+ums.getUsernm()+ums.getPwd()+ums.getAddress()+ums.getPhone());
        
        String savedOrNot=userService.register(ums);
        if(savedOrNot.equals("Saved"))
        {
            //go to next page
            System.out.println("Done");
            return "You are registered. Go To Login Page to login";
        }
        else
        {
            System.out.println("Not Done");
            return "Error while registering";
        }
        
        
            
    }


What I have tried:

What I have concluded till now is :

The data is reaching from HTML page to javascript code (I checked it from the browser by applying breakpoints in code)
The data reaching to API is null, and it always returns "Error while registering", which is else part of restful API
There is some minor issue I guess for which I have spent days resolving it but not been able to do it till now. If your help can solve it, I would be very thankful.
Posted
Updated 17-Nov-21 23:51pm

1 solution

I can see two areas which may need amending. The first is in your JS, you're creating an object dataObj and populating it with the form information but you're not then using it. The serializeArray() method does not create an object but creates an array which I'm going to guess isn't what your UserModel class is. Instead use:
javscript
const userJson = JSON.stringify(dataObj);

The next part is the bit in the controller where you're trying to consume the content. The @ModelAttribute annotation is designed for models which have been added to a view and bound using something like Spring Forms. Try changing the controller declaration to:
Java
public String registerUser(@RequestBody UserModel ums)

The @RequestBody annotation tells Spring to consume whatever content was POST'd and deserialize it into the parameter type.
 
Share this answer
 
Comments
Member 15435238 19-Nov-21 0:30am    
@Chris Copeland, Thanks a lot man, I have spent days solving this issue. You saved my life. Thanks.
Chris Copeland 19-Nov-21 4:58am    
You're welcome! 😊

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900