Jump to previous page after sending data using ajax - javascript

On page A, I use ajax to send data to server. At sever side, after spring controller gets the data, it returns welcome page B. Evergthing works fine on firefox and IE. But on chrome, after ajax call sends data to server successflully, we can get the reponse: the page B I want. But the page B just show for 1 second. Then jump back to page A again. Now idea why? Thanks.
The form html:
<form class="form" id="register-form">
<input id="username" type="text" placeholder="Username" name="username">
<input id="password1" type="password" placeholder="Password" name="password1" >
<input id="password2" type="password" placeholder="Password" name="password2">
<input id="email" type="text" placeholder="Email" name="email">
<input id="phonenumber" type="text" placeholder="Phone Number" name="phonenumber">
<button onclick="register()" id="register-button">Join us!</button>
</form>
Ajax:
$.ajax({
url: "/myporject/user/addUser",
type: 'GET',
dataType: 'text',
contentType: "application/json; charset=utf-8",
async: false,
cache : false,
data: {
username:username,
password:pwd1,
email:email,
phonenumber:phone
},
success : function(response) {
alert("response:" + response);
document.open();
document.write(response);
document.close();
},
error: function(xhr, textStatus, error){
alert("error!!!");
console.log(xhr.statusText);
alert(textStatus);
console.log(error);
}
});
Spring controller:
#RequestMapping(value = "/addUser", method = RequestMethod.GET)
public #ResponseBody ModelAndView addUser(
#RequestParam(value = "username") String username,
#RequestParam(value = "password") String password,
#RequestParam(value = "email") String email,
#RequestParam(value = "phonenumber") String phonenumber) {
User user = userService.createUser(username, password, email, phonenumber,
User.ROLE_CUSTOMER);
ModelAndView myview = new ModelAndView("welcome");
return myview;
}

Add type="button" (e.g. <button type="button" ...>) so that a (standard, non-Ajax) form submit doesn't happen at the same time.
Or bind the click handler with jQuery and use event.preventDefault()

Related

Spring boot: The request was rejected because no multipart boundary was found in spring boot with ajax call?

I am working with Spring boot. I want to upload a file along with some data using an AJAX call. However, when I enter the data, select the file, and click the submit button, I get the following exception:
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
<form id="course-form" enctype="multipart/form-data">
<input type="text" class="form-control" placeholder="Course Name" name="courseName" id="courseName">
<input type="text" class="form-control" placeholder="Total no of sets" name="noOfSets" id="noOfSets">
<input type="text" class="form-control" placeholder="Total fees" name="fees" id="fees">
<input type="file" class="form-control" placeholder="Select an image" name="image" id="image">
<input type="text" name="requirements" id="requirements" class="form-control">
<input type="text" name="requirements" id="requirements" class="form-control">
<input type="button" value="Add more requirements" id="add-req">
<input type="submit" value="Submit">
</form>
ajax call
function saveCourse(){
var itemData=new FormData($("#courseForm")[0]);
$.ajax({
type : "POST",
url : "/course/save",
data : itemData,
async: false,
processData : false,
cache : false,
contentType : 'multipart/form-data',
success : function(result) {
if(result.message !=null){
alert(result.message);
}
},
error : function(e){
alert("Error! Please enter proper data");
}
});
return false;
}
Controller class
#PostMapping(value="/course/save")
public ResponseDTO addCourse(MultipartHttpServletRequest request, CourseDTO courseDTO)
{
System.out.println("Course controller save menthod started");
return null;
}
Why am I receiving this exception? And, how can I solve the problem?
It seems you are missing not be setting enctype and should explicitly setting contentType: false,:
function saveCourse() {
var form = $('#course-form')[0];
var courseData = new FormData(form);
$.ajax({
type : "POST",
url : "/course/save",
contentType: false,
data: courseData,
processData: false,
success: function(result) {
if (result.message != null) {
alert(result.message);
}
},
error: function(e) {
alert("Error! Please enter proper data");
}
});
return false;
}
By omiting it, the browser will take care of generating the proper content type with multipart boundary, something like:
content-type: multipart/form-data; boundary=----WebKitFormBoundaryQ0pBuvRC1EzDAQWT````
The Issue is resolved with the following ajax code
var itemData=new FormData($("#courseForm")[0]);
$.ajax({
type : "POST",
url : "/course/save",
data : itemData,
dataType : "json"
processData : false,
cache : false,
contenttype : false;
success : function(result) {
if(result.message !=null){
alert(result.message);
}
},
error : function(e){
alert("Error! Please enter proper data");
}
});
return false;
And we need to fetch the data in controller using #RequestParam annotation and the file using #RequestPart annotation

How to post form data as JSON?

I'm trying to build a registration site for a group project we are working on but can't figure out how to send the form data as json. I've tried googling a lot and changing the code but nothing seems to work. The problem I have is that when i press on the submit button I get an error like this from the API:
{"":["The input was not valid."]}
I think the reason is that my form does not send the data as JSON and it's they format they require according to their API documentation. My form code looks like this:
<form id="register_form" action="https://https://url.com/users/register" method="post">
<input type="text" pattern="[A-Za-z]{1,20}" placeholder="Name" name="name" title="Up to 20 alphabetical characters" required>
<input type="email" placeholder="Email" name="email" title="Must be a valid email address" required>
<input type="password" pattern="[a-zA-Z0-9-]+{8,20}" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
<input type="text" pattern="[a-zA-Z0-9-]+" placeholder="Homeadress" name="homeadress">
<input type="text" placeholder="Postnumber" name="postnumber">
<input type="text" placeholder="City" name="city">
<br>
<button value="Submit" type="submit">Register</button>
</form>
And the script i've been trying to get to work looks like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>
<script type="text/javascript">
$('register_form').on('submit', function(event){
var obj = $('register_form').serializeJSON();
$.ajax({
type: 'POST',
url: 'https://url.com/users/register',
dataType: 'json',
data: JSON.stringify(obj),
contentType : 'application/json',
success: function(data) {
alert(data)
}
});
return false;
});
</script>
Any help would be greatly appreciated since I'm not very familiar with coding stuff like this.
Edit:
I also tried it with a script like this but still getting the same response:
<script>
$(document).ready(function(){
$("#submit").on('click', function(){
var formData = {
"name": $('input[name=name]').val(),
"email": $('input[name=email]').val(),
"password": $('input[name=password]').val(),
"homeadress": $('input[name=homeadress]').val(),
"postnumber": $('input[name=postnumber]').val(),
"city": $('input[name=city]').val()
};
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: 'https://url.com/users/register',
type : "POST",
dataType : 'json',
data : JSON.stringify(formData),
success : function(result) {
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
I tested it with our teachers test api also and the response is this:
{"message":"Bad Request","reason":"val: nil fails spec: :user-system.spec/login-request predicate: map?\n"}
There's a couple problems here.
Invalid start tag for script element. This was probably a copy and paste error, but worth mentioning:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>
missing greater than symbol ^
Selecting register_form instead of #register_form in two places, the second was unnecessary regardless because you could reference this instead. This also resulted in the form submission not being cancelled.
You didn't include a $.serializeJSON plugin, again I'm assuming this is a copy and paste error.
$.serializeJSON (whichever you choose) should return a JSON string, but you run JSON.stringify on the result, which will be a string inside a string.
https://https:// This isn't a huge issue because it is in the action attribute of a form that should never submit, but worth mentioning.
In the example below I've provided a simple replacement for $.serializeJSON, and corrected the rest of the issues listed above. serialize_form in the code below can be replaced with whatever $.serializeJSON plugin you choose to use.
I have commented out the ajax request as what is really of concern here is getting the JSON from the form data, so I just log it to the console instead so that you can see it is a JSON string. I also removed the pattern attributes and required flags from the input for ease of testing.
const serialize_form = form => JSON.stringify(
Array.from(new FormData(form).entries())
.reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {})
);
$('#register_form').on('submit', function(event) {
event.preventDefault();
const json = serialize_form(this);
console.log(json);
/*$.ajax({
type: 'POST',
url: 'https://url.com/users/register',
dataType: 'json',
data: json,
contentType: 'application/json',
success: function(data) {
alert(data)
}
});*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="register_form" action="https://url.com/users/register" method="post">
<input type="text" placeholder="Name" name="name" title="Up to 20 alphabetical characters">
<input type="email" placeholder="Email" name="email" title="Must be a valid email address">
<input type="password" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter">
<input type="text" placeholder="Homeadress" name="homeadress">
<input type="text" placeholder="Postnumber" name="postnumber">
<input type="text" placeholder="City" name="city">
<br>
<button value="Submit" type="submit">Register</button>
</form>

I use java Servlets and cannot redirect to another page after submitting form and sending data in JSON format

I don't have a lot experience in web developing.
I want to sent form data in request body in JSON format. When server reсieve data it should register new user and redirect user to another page with user's data.
Deserializing and ragistration into database works good.
The main problem is that after sending form data to the server the page recieve response with new page(url and content), but just in headers and doesn't change.
How can I change the page after sending form data??
Here is Javascript handling and HTML code of form:
<script>
function makeJSON(form) {
var userData = {
"phone_number" : form.phone_number.value,
"country" : form.country.value,
"city" : form.city.value,
"date_of_birth" : form.date_of_birth.value,
"email" : form.email.value,
"sex" : form.sex.value,
"login" : form.login.value,
"password" : form.password.value
};
var requestString = JSON.stringify(userData);
var request = new XMLHttpRequest();
request.open("POST", "/registration");
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(requestString);
}
<div id="topNavLine"></div>
<div class="regBody">
<div class="regFormTop"><h1>Registration form</h1></div>
<form id="registration" method="post" onsubmit="makeJSON(this);" enctype="application/x-www-form-urlencoded">
<fieldset>
<legend>Personal data</legend>
<p><label>Phone:</label><input name="phone_number" type="text" form="registration"></p>
<p><label>Country:</label><input name="country" type="text" form="registration"></p>
<p><label>City:</label><input name="city" type="text" form="registration"></p>
<p><label>Date:</label><input name="date_of_birth" type="date" form="registration"></p>
<p>
<Label>Email:</Label><input name="email" type="text" form="registration"></p>
<p><label>Sex:</label>
M<input type="radio" name="sex" value="male">
F<input type="radio" name="sex" value="female">
</p>
</fieldset>
<fieldset>
<legend>Login data</legend>
<p><label>Login:</label><input name="login" type="text" form="registration"></p>
<p><label>Password:</label><input name="password" type="password" form="registration"></p>
<p><label>Confirm password:</label><input name="passwordValidation" type="password" form="registration"></p>
</fieldset>
<div class="regButton">
<button class="regButton" type="submit" form="registration">Register</button>
</div>
</form>
</div>
Here is doPost servlet method:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String str = request.getReader().lines().collect(Collectors.joining());
System.out.println(str);
UserRegData userRegData = new ObjectMapper().readValue(str,UserRegData.class);
long tmpId = new Random().nextLong();
if (tmpId < 0) {
tmpId *= -1;
}
userRegData.setId(tmpId);
userRegData.printUser();
try (Connection connection = ConnectionWithDB.connectToDB()) {
ManagingData.setRegistrationData(userRegData, connection);
} catch (SQLException e) {
e.printStackTrace();
}
response.setStatus(201);
response.sendRedirect("/page_of_user");
}
The whole approach is a bit wrong IMHO. The response should be handle by a callback function in javascript. If there are validation errors for example you can show them in the same form.
If all is succesful then in javascript you call 'page_of_user'.
Here is JQuery in action:
$.ajax({
type: "POST",
url: "/registration",
data: userData ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){ document.location.href='/page_of_user'; },
failure: function(errMsg) {
alert(errMsg);
}
});

jQuery Internal Server Error

This is simple login page created in asp.net but jQuery doesn't work here. I am getting this error again and again, please help me solve this.
This is my HTML markup:
<html>
<body>
<form id="form1" runat="server">
<div>
User Name :<input type="text" name="UserName" placeholder="Enter User Name" /> <br />
Password :<input type="password" name= "Password" placeholder="Enter password" /></br>
<input type="button" value="Login" id="SubmitLogin" />
</div>
</form>
<script type="text/javascript">
$('#SubmitLogin').click(function () {
alert("I am in Submit Button click");
Login_User();
});
Login_User = function () {
postData = {UserName:'UserName1',Password:'Password1'};
debugger;
$.ajax({
//async:'false',
type: 'POST',
url: 'LoginForm.aspx/Login_validate',
datatype: 'json',
data: JSON.stringify({ "dbparameters": postData }),
contentType: 'application/json; charset=utf-8 ',
success: function (outputresult) {
alert("i am in Success " + outputresult + " .");
},
error: function (XMLHttpRequest, status, error) { alert("Error In System : " + status + " " + error); }
})
}
</script>
</body>
</html>
and my code-behind:
[WebMethod]
[ScriptMethod]
public string Login_validate(Dictionary<string, string> dbparameters) {
string UserName, Password;
UserName = dbparameters["UserName"];
Password = dbparameters["Password"];
return UserName + Password + " ";
}
I Have come to an Answer that Data sent in this request is in-coded in Double Cotes, this gives error
data sent as
`{"dbparameters ":{"UserName":"UserName1","Password":"_Password1"}}`
but this should be sent as
{"dbparameters ":{"UserName":UserName1,"Password":_Password1}}
how to do this ? this will solve Internal Server Error.

C# WebApplication POST

I'm trying to POST a form using C#
I make some searches, however I couldn't code it right way (I am new in this field).
Here are my codes;
View;
<form>
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" id="input-username" name="Username" required autocomplete="on" />
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" id="input-password" name="Password" required autocomplete="on"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="button button-block" id="button-login">Log In</button>
</form>
Controller;
// GET: User
[HttpPost]
public ActionResult Login()
{
string username = Session["Username"].ToString();
string password = Session["Password"].ToString();
Service iLocationService = new Service();
var result = Service.MemberGetLogin( username, password, "127.0.0.1" );
ViewBag.Message = result;
return View();
}
Javascript;
jQuery(document).ready(function () {
$("#button-login").click(function () {
$.ajax({
type: "POST",
url: "/Controllers/UserController/login/",
data: $(this).serialize(),
dataType: "json"
})
.done(function (result) {
console.log(result);
})
.fail(function (a) {
console.log( a);
});
});
});
What I am trying to do is POST the input values to chech the user.
Thanks in Advance
Look at this line
string username = Session["Username"].ToString();
In your code you are trying to read the username and password values from Session variables. Who set the user name and password to Session ? You should be reading those from the posted form and use that.
[HttpPost]
public ActionResult Login(string userName,string password)
{
// do something with userName and password and return something
}
Also, you need to make sure that you are serializing the form, not the button clicked. I personally prefer to use the Html helper method to generate the form tag and use the action attribute value of the form in my javascript code instead of hardcoding the urls.
So in my razor view
#using(Html.BeginForm("login","User"))
{
//Your existing form inputs goes here
<button class="button button-block" id="button-login">Log In</button>
}
and in the script
$("#button-login").click(function () {
$.ajax({
type: "POST",
url: $(this).closest("form").attr("action"),
data: $(this).closest("form").serialize()
})
});
Since you are doing an ajax form submit, i suggest you return a json response which your client code can parse and do further things.
[HttpPost]
public ActionResult Login(string userName,string password)
{
//if userName and password are valid
return Json(new { Status="success"});
// else
return Json(new { Status="failed", Message="Invalid credentials});
}
and in your done callback, you should inspect this value and do further things
.done(function (result) {
if(result.Status==="success")
{
window.location.href="/Home/Index"; // change to wherever you want to redirect to
}
else
{
alert(result.Message);
}
})

Categories