I'm using tornado to build a web server and now I'm creating a login module. Here is the code:
<body>
<form id="uploadForm">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input name="name" type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input name="password" type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<button id="submit" type="button" class="btn btn-default">Submit</button>
</form>
</body>
<script src="../js/plugins/jquery-3.2.1.min.js?v=c9f5aeeca3"></script>
<script src="../js/common/bootstrap.min.js?v=5869c96cc8"></script>
<script>
$(function(){
$('#submit').on('click',function(){
$.ajax({
url: 'http://www.example.com/login',
method: 'POST',
data: $('#uploadForm').serialize(),
contentType: false,
processData: false,
cache: false,
success: function(data) {
console.log(data);
if( data === 'ERROR'){
alert('login failed')
}else{
location.href = data;
}
},
error: function (jqXHR) {
alert('ERROR');
}
});
});
});
</script>
And the backend part:
class LoginHandler(tornado.web.RequestHandler):
def post(self, path):
try:
print(self.request.body)
name = self.get_body_argument("name")
except Exception as e:
print(e)
When I do a test, I can see that print(self.request.body) gives me the result: b'name=test&password=tttt' but after that I get an exception:
HTTP 400: Bad Request (Missing argument name)
name=test is just in the http body but why it tells me missing argument name?
Tornado only supports "application/x-www-form-urlencoded" and "multipart/form-data" as content type. So when we send a post request to the server, we must send the request with the right contentType. For example,
$.ajax({
url: 'http://www.example.com/login',
method: 'POST',
data: $('#uploadForm').serialize(),
contentType: 'application/x-www-form-urlencoded',
processData: false,
...
Also, we can neglect the contentType in ajax as 'application/x-www-form-urlencoded' is set by default.
Related
Controller:
[HttpGet]
public IActionResult Edit(int id)
{
Teacher teacher = teacherService.GetTeacherById(id);
EditTeacherData(teacher);
return View();
}
public JsonResult EditTeacherData( Teacher teacher)
{
return Json(teacher);
}
Ajax:
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
View:
#model StudentTeacher.Models.TeacherViewModel
#{
ViewData["Title"] = "EditTeacher";
}
<h1>EditTeacher</h1>
<h4>Teacher</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form id="AddTeacherForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="TeacherId" id="TeacherId" />
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" id="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Designation" class="control-label"></label>
<input asp-for="Designation" class="form-control" id="Designation" />
<span asp-validation-for="Designation" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Education" class="control-label"></label>
<input asp-for="Education" class="form-control" id="Education" />
<span asp-validation-for="Education" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="JoiningDate" class="control-label"></label>
<input asp-for="JoiningDate" class="form-control" id="JoiningDate"/>
<span asp-validation-for="JoiningDate" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" id="Submit" />
</div>
</form>
</div>
</div>
teacherService is a service that retrieves data that match with id. But it return null object. When I use this EditTeacherData(teacher); ajax not return a null object But in debugger model show value takes this function. I just wanna get an object through ajax and show data in the field via ajax.
Obviously, there is no parameter passed in to the controller in your ajax, so Edit method will never receive the parameter passed in.
You can implement it with EF core. If you want to use ajax, you can refer to this.
You can also achieve it without ajax, it much easier, please refer to this.
You are not sending data from your ajax request. Please read this for clear understanding
$('#Submit').click(function(){
var formData = $('#AddTeacherForm').serialize();
$.ajax({
type: "GET",
url: "/Teacher/EditTeacherData",
data: formData,
success: function (data) {
debugger;
console.log(data)
},
error: function (response) {
debugger;
alert('eror');
}
});
})
I am trying to use a zapier webhook to write to a google spreadsheet. Here is the simple html I am using:
<form id="my-form">
<input type="text" id="name" name="name" placeholder="Name" />
<input type="text" id="age" name="age" placeholder="Age" />
<input type="text" id="location" name="location" placeholder="Location" />
<input type="text" id="date" name="date" placeholder="Date" />
<button type="submit">Submit</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'https://hooks.zapier.com/hooks/catch/2366642/xxx/',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#response pre').html( data );
console.log(data)
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#my-form').submit( processForm );
})(jQuery);
</script>
When I hit the submit button I am getting the test data that I entered into the initial zap being written to the spreadsheet each time. I am wanting the name, age, location and date fields to be written to the spreadsheet instead
I used this tutorial to get started so I suspect I am getting the data from the form to the ajax request properly. Any help appreciated.
In case anyone else runs into this, I had not selected the fields in the Action portion of the zap. Here is an image. Hope it helps others out:
I've just implemented invisible recaptcha into a web form. Everything works fine with Chrome. But with Microsoft Edge, the image challenge always occurs with every form submission. Which is embarrassing for the users of the website. An idea?
Thanks a lot for your insights and advice :o)
Laurent
Javascript code:
window.onScriptLoad = function () {
var htmlEl = document.querySelector('.g-recaptcha');
var captchaOptions = {
'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'size': 'invisible',
'badge': 'inline',
callback: window.onUserVerified
};
var inheritFromDataAttr = true;
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
window.onUserVerified = function (token) {
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data : {
'lastname' : $("#lastnameField").val(),
'firstname' : $("#firstnameField").val(),
'city' : $("#cityField").val(),
'postalCode' : $("#postalcodeField").val(),
'g-recaptcha-response' : token
},
success:function(data) {
// informs user that form has been submitted
// and processed
},
error: function(xhr, textStatus, error){
// informs user that there was a problem
// processing form on server side
}
});
};
function onSubmitBtnClick () {
window.grecaptcha.execute;
}
HTML code:
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad" async defer></script>
<script type="text/javascript" src="js/petition.js"></script>
...
</head>
<body>
<form id="petitionForm" onsubmit="return false;">
<input id="lastnameField" type="text" name="lastname" placeholder="Lastname" required value="Doe">
<input id="firstnameField" type="text" name="firstname" placeholder="Firstname" required value="John">
<input id="postalcodeField" type="text" name="postalCode" placeholder="Postal Code" required value="ABCDEF">
<input id="cityField" type="text" name="city" placeholder="City" value="Oslo">
....
<input type="submit" name="login" class="g-2" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxx" id="signButton" data-callback='' value="Signer" onclick="onSubmitBtnClick();">
<div class="g-recaptcha" id="recaptchaElement" style="align-content: center"></div>
</form>
...
</body>
</html>
I am trying to send a POST request from axios to a Rails API using the following function in the React frontend:
export function registerUser({ name, email, password }) {
var postdata = JSON.stringify({
auth: {
name, email, password
}
});
return function(dispatch) {
axios.post(`${API_URL}/user_token`, postdata )
.then(response => {
cookie.save('token', response.data.token, { path: '/' });
dispatch({ type: AUTH_USER });
window.location.href = CLIENT_ROOT_URL + '/dashboard';
})
.catch((error) => {
errorHandler(dispatch, error.response, AUTH_ERROR)
});
}
}
The Knock gem expects the request in the following format:
{"auth": {"email": "foo#bar.com", "password": "secret"}}
My current function seem to generate the correct format (inspecting the request in the browser devtools), but I'm getting the following error:
Uncaught (in promise) Error: Objects are not valid as a React child
(found: object with keys {data, status, statusText, headers, config,
request}). If you meant to render a collection of children, use an
array instead or wrap the object using createFragment(object) from the
React add-ons. Check the render method of Register.
class Register extends Component {
handleFormSubmit(formProps) {
this.props.registerUser(formProps);
}
renderAlert() {
if(this.props.errorMessage) {
return (
<div>
<span><strong>Error!</strong> {this.props.errorMessage}</span>
</div>
);
}
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
{this.renderAlert()}
<div className="row">
<div className="col-md-6">
<label>Name</label>
<Field name="name" className="form-control" component={renderField} type="text" />
</div>
</div>
<div className="row">
<div className="col-md-12">
<label>Email</label>
<Field name="email" className="form-control" component={renderField} type="text" />
</div>
</div>
<div className="row">
<div className="col-md-12">
<label>Password</label>
<Field name="password" className="form-control" component={renderField} type="password" />
</div>
</div>
<button type="submit" className="btn btn-primary">Register</button>
</form>
);
}
}
The error is caused by the following line in your code
errorHandler(dispatch, error.response, AUTH_ERROR)
The exception raised clearly explains that. Instead of setting error.response, try to use the actual data from error.response. E.g error.response.data. Also, you can try replacing the error.response with a string and see how that behaves, then reference the string you need from error.response.data.
I fail to upload pictures using formdata. This is my previous code which was working fine(This is just part of a form):
<div class="fileinput fileinput-new" data-provides="fileinput" style="width: 100%;">
<div class="fileinput-preview" data-trigger="fileinput" style="margin: 10px 0px;"></div>
<div>
<span class="btn btn-default btn-file">
<input type="file" id="filePicture" name="filePicture">
</span>
</div>
</div>
And this is my Ajax call:
$(document).on("click", "#sledBuckSaveBtn", function() {
event.preventDefault();
event.stopPropagation();
var fd = new FormData(document.getElementById("saveSledBuckForm1"));
$.ajax({
type: "POST",
url: "/SledBuck/EditFromSledTestDetails", //url,
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function (result) {
var title = "Error", msgtype = "error";
if (result) {
title = "Success";
msgtype = "success";
}
document.location.reload();
}
});
});
But my requirement has changed, I need to use Krajee plugin to create an input type:
Here my new code:
<div class="col-md-9">
<input id="input-#Model.PictureIdList[i]" type="file" class="file" data-show-upload="false" data-show-caption="true" data-input-id="#Model.PictureIdList[i]">
</div>
what problem am I facing. I think the reason is I might need to do configuration for Krajee plugin but I'm not sure. Any suggestions?
I just found the answer. I lacked the name of the file input. Just do like this and the file will be regconized:
<input id="input-#Model.PictureIdList[i]" name= "fileInput" type="file" class="file" data-show-upload="false" data-show-caption="true" data-input-id="#Model.PictureIdList[i]">