How to post form data as JSON? - javascript

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>

Related

How to Post Registration Form with File to ASP.NET MVC Action

I'm unclear as to why I'm unable to POST the data in my form to the server. It appears as though the form is defaulting to a 'GET' request although I've hardcoded both the form and the AJAX call to use a 'POST' request. So, I'm out of ideas. Any suggestions are very much appreciated.
The UI looks like this:
This is my Javascript code:
SubmitRegisterForm: function (e) {
var scope = this;
e.preventDefault();
//var formData = new FormData();
//formData.append('profilepic', $('#profilepic')[0].files[0]);
var data = {
FirstName: $('#FirstName').val(),
LastName: $('#LastName').val(),
Email: $('#Email').val(),
Password: $('#Password').val(),
ConfirmPassword: $('#ConfirmPassword').val(),
StripeConnectedAcctId: scope.stripeConnectedAccountId
};
console.log(data);
$.ajax({
url: '/Account/Register',
method: 'POST',
data: { model: data, profilepic: $('#profilepic')[0].files[0] },
enctype: 'multipart/form-data'
}).done(function (resp) {
});
}
Server-side code looks like this, but isn't currently being hit (that would be the problem bub):
Also, I'm seeing these errors on the Chrome Dev tools Console:
Funny enough, the Javascript code executes fine, displaying the data variable just fine, but complains about some Illegal Invocation in Vue... which literally makes no sense as I don't even use any Vue related functions but rather issue an AJAX call.
What on God's green Earth gives???? >=/
I'm hoping I'll wake up to this with a solution in my inbox like it's Christmas!
You are using ASP .NET so if you are using server side rendering I would do something like this and let the framework handle everything.
<form enctype="multipart/form-data" asp-action="controllorAction" method="post">
<label class="form-label" for="firstName">First Name</label><input type="text" asp-for="Model.FirstName" />
<label class="form-label" for="lastName">Last Name</label><input type="text" asp-for="Model.LatName" />
...
<label class="form-label" for="customFile">Profile Picture</label><input type="file" asp-for="Model.File" class="form-control" id="File" />
<input type="submit" value="Submit form" class="btn btn-primary" />
</form>
https://www.w3schools.com/ASp/webpages_forms.asp
Hope this helps you

Jump to previous page after sending data using ajax

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()

Send Ajax Variables with POST to PHP

I am trying to find the best way to send variables from Javascript to PHP without GET method. I found a way to send through POST method with AJAX:
<form method="POST" id="post" enctype="multipart/form-data">
<input type="file" name="image_upload[]" id="img1" />
<input type="file" name="image_upload[]" id="img2" />
<input type="file" name="image_upload[]" id="img3" />
<input type="text" name="description" id="description" />
<textarea class="intext" name="editor" id="editor"></textarea>
<input type="text" name="state" id="state" disabled="true" />
<input type="text" name="city" id="city" disabled="true" />
<input type="submit" id="submit" />
</form>
And I am trying to submit the form with jQuery:
$('#post').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "cpage.php",
data: {
'variable1': 'content var1',
'variable2': 'content var2'
},
success: function () {
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
NOTE: the variable "position" has been declared before and works fine.
Result: I get "Internal Server Error" in the alert. Any ideas?
First of All - show us what is going on the server side.
And now about the files being sent:
You should use FormData element for file submit threw Ajax, its not supported by old browser, the browsers that would support this are : ie>9, chrome > 7, opera > 12 safari >5, android > 3 gecko mobile > 2, opera mobile >12.
Use something like this:
$('#post').submit(function (event) {
event.preventDefault();
if( window.FormData !== undefined ) //make sure that we can use FormData
{
var formData = new FormData($('form#post'));
$.ajax({
type: "POST",
url: "cpage.php",
data: formData ,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data); // <- for debugging
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
} else {
//fallback
}
});
As you can see I added console.log(data), try looking at the returned data to identify any other problems.

JQuery ajax call fails when last input is filled

JQuery noob here,
I'm working on a simple web-app which needs to send registration info to a server.
For some reason this code works fine when only two of the form inputs are filled in, but fails when there's information in the last one, even though I'm not using it in the code. The error callback gets called, but errorThrown is empty. My server receives no data.
Is there anything obviously wrong with this?
Note: the call fails when the last input is filled, no matter how many inputs are in the form.
JQuery:
$(document).ready(function() {
$("#registrationForm button.register").on("click", function(event) {
var params = {
email: $("#registrationForm input.email").val(),
password: $("#registrationForm input.password").val()
};
$.ajax({
url: "/register",
type: "POST",
contentType: "application/json",
data: JSON.stringify(params),
dataType: "json",
success: function(data, textStatus, jqXHR) {
console.log(data);
if(data.user_exists==true)
{
alert("Stop trying to register twice!");
}else{
window.location.href = "/registered";
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error("Error:", errorThrown);
}
});
});
});
And the HTML:
<form id="registrationForm">
<label>Email:</label>
<input name="user[email]" type="text" required="required" class="email">
<br>
<label>Password:</label>
<input name="user[password]" type="password" required="required" class="password">
<br>
<label>Verify Password:</label>
<input name="nothing" type="text" required="required">
<br>
<button onclick="" class="btn btn-default register">Register</button>
</form>
Unless you specify otherwise, the button inside your form will submit the form when clicked. In the click function, put event.preventDefault() to stop this default action from taking place. For more details, see the jQuery docs here.

Google Api get access_token request returns invalid_request

I'm trying to get Google APi's access_token using javascript and always getting error message :invalid_request. There is my code:
var options = {
url: tokenURL,
type: "POST",
headers: { "Content-type": "application/x-www-form-urlencoded"},
dataType: "json",
data: {
"code":successCode,
"client_id": clietId,
"client_secret": clientSecret,
"grant_type": "authorization_code",
"redirect_url": "urn:ietf:wg:oauth:2.0:oob"
},
complete: function (e) {
alert(e.status);
},
};
$.ajax(options);
I also tried to make POST request using simple html form and it works.
<form method="post" action="https://accounts.google.com/o/oauth2/token">
<input name="code" type="text" value="##code##" />
<input name="client_id" type="text" value="##client_id##" />
<input name="client_secret" type="text" value="##client_secret##" />
<input name="grant_type" type="text" value="authorization_code" />
<input name="redirect_uri" type="text" value="urn:ietf:wg:oauth:2.0:oob" />
<input type="submit" /></form>
I have no idea whats wrong with javascript request. Am I missing some parameters or headers?
It looks like the encoding of data (in the first example) doesn't match the content-type.
The encoding of data appears to be application/json, but the content-type specified is application/x-www-form-urlencoded.
You need to change the encoding of data to be urlencoded.
data: "code=successCode&client_id=clientId&client_secret=clientSecret&grant_type=authorization_code&redirect_url=urn:ietf:wg:oauth:2.0:oob"

Categories