Frontend ajax POST call can't login to Django - ajax

I've spent several days to no avail and was wondering if anyone could help me? I am trying to use Django as a backend only with the ultimate goal of porting to a mobile application. I have a form and ajax call in the front end to a url/view in Django (REST API as well if that is relevant), but for some reason that I don't understand the call won't go through to log me in.
Relevant applications:
Django-Userena
Tastypie
Could anyone advise me in the right direction? Below is the code and thank you!
index.html
<script>
$(document).ready(function(){
`//login test`
`$('#login').submit(function(){`
$.ajax({
url: 'http://127.0.0.1:8000/accounts/signin/',
type: 'POST',
//data: loginString,
data: $('#login').serialize(),
success: function() {
alert('Test');
$('#datadisplay').append("<h2>It worked</h2>");
},
error: function(errorThrown){
alert('Error');
alert(errorThrown);
}
});
});
});
</script>
</head>
<body>
<div id="datadisplay"></div>
<input type="submit" id="getdata" value="Submit">
<div id="loginform">
<form name="login" id="login" action="">
<fieldset>
<label for="id_identification">Username</label>
<input type="text" name="identification" id="id_identification" size="30" value="" />
<br/>
<label for="id_password">Password</label>
<input type="password" name="password" id="id_password" size="30" value="" />
<br/>
<input type="submit" name="submit" class="loginbutton" value="Login" />
</fieldset>
</form>
</div>
api.py
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
include_resource_uri = False
allowed_methods = ['get', 'post']
def override_urls(self):
return [url(r"^(?P<resource_name>%s)/signin%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('signin'), name="api_signin"),
]
def signin(self, request, **kwargs):
self.method_check(request, allowed=['post'])
data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return self.create_response(request, {
'success': True
})
else:
return self.create_response(request, {
'success': False,
'reason': 'disabled',
}, HttpForbidden )
else:
return self.create_response(request, {
'success': False,
'reason': 'incorrect',
}, HttpUnauthorized )

$.ajax({
url: '/accounts/signin/',
type: 'POST',
data: {
csrfmiddlewaretoken: '{{csrf_token}}',
//other variables
},
success: function() {
alert('Test');
$('#datadisplay').append("<h2>It worked</h2>");
},
error: function(errorThrown){
alert('Error');
alert(errorThrown);
}
});

Related

How to send other variable datas along with new FormData() inside AJAX?

Here I am sending the upload files into FormData() to be accessed in expressjs. And it is working perfectly.
$(".commonForm").submit(function (e) { //For Submitting the Uploaded Files
e.preventDefault();
if(validateForm($(this).attr('name'), text))
{
$.LoadingOverlay("show");
var formData = new FormData(this);
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(response){
if (response.status == '200') {
$.LoadingOverlay("hide");
swal({
title: "Excellent!",
text: "Files submitted successfully!",
icon: "success",
button: "Ok",
showCancelButton: true
}).then((result) => {
if (result) {
window.location.reload();
}
});
}
},
error: function (e) {
console.log("some error", e);
}
});
}
});
But along with that I want to send one another field data along with formData.
var text = 'Done';
How to send this along with formData in data ?
I am trying this:
data : {
formData:formData,
text:text
}
But then I don't think that I will be able to retrieve the uploaded files data directly with req.files
UPDATE:
route code/expressjs
router.post('/api/upload/:cid',function(req,res,next){
console.log("req.body.text = " + req.body.text + req.query.text);
upload2(req,res,function(err) {
if(err) {
console.log("Error is important = "+ err);
}
else
{
console.log("Uploaded successfully.");
}
})
})
MULTER CODE:
var upload2 = multer({storage: storage2, limits: { fileSize: 1024 * 1024 * 1 }}).array('FileUploadForClient',4);
HTML HANDLEBAR FORM CODE:
<form name="{{this.status}}" class="commonForm" enctype="application/x-www-form-urlencoded" action="/api/upload/{{this.commonID}}" method="post">
<td class="col-sm-2">
<div class="center">
<select name="sourcesSelect" id="{{this.commonID}}" data-notUse="{{this._id}}" data-Id4AddtasksBigpaths="{{this.Id4AddtasksBigpaths}}" class="custom-select sources" placeholder="{{this.status}}" style="font-size:20px; background: {{this.background}}; color: white;" {{this.statusDisabled}}>
<option value="0" >In Progress</option>
<option value="1" >Done</option>
<option value="2" >Rejected</option>
</select>
</div>
</td>
<!-- <td class="col-sm-2"><span id="deadline" style="font-size:14px"><input type="text" class="form-control" value="{{this.deadline}}" readonly/></span></td> -->
<td class="col-sm-1">
<!-- <input type="file" class="btn btn-light" name="FileUploadForClient" multiple required/> -->
<input type="file" id="{{this._id}}" class="form-control" name="FileUploadForClient" multiple required {{this.statusDisabled}} />
</td>
<td>
<button type="submit" class="btn btn-primary btn-block col-sm-2" style="font-size:16px" {{this.statusDisabled}}>Submit</button>
</td>
</form>
Use the method append to add another parameter to the request
var formData = new FormData(this);
formData.append('text', 'text to send in the request ');

Get value of submit button from Ajax call

The value of the submit buttons are always null in the Action.
What do I need to change to know which submit button has been clicked?
<form id="actionInvitation">
<div>
<ul>
<li>
#Model.TeamInviteBy
</li>
</ul>
</div>
<input type="submit" name="actionBtn" id="acceptBtn" value="Accept Invitation" />
<input type="submit" name="actionBtn" id="declineBtn" value="Decline Invitation" />
</form>
$('#actionInvitation').submit(function (e) {
e.preventDefault();
var formData = new FormData($('#actionInvitation')[0]);
$.ajax({
url: '#Url.Action("ActionInvitation", "Home")',
type: 'post',
cache: false,
processData: false,
contentType: false,
data: formData,
success: function (data) {
$("#invitationActionMessage").append('Invitation Accepted');
}
});
});
//Action
public async Task<IActionResult> ActionInvitation(UserViewModel userViewModel, string acceptBtn, string declineBtn)
Your formData will not contain the objects you need to pass.
You can change your code like below:
<form id="actionInvitation">
<div>
<ul>
<li>
#Model.TeamInviteBy
<input type="hidden" name="TeamInviteBy" value="#Model.TeamInviteBy">
</li>
</ul>
</div>
<input type="submit" name="actionBtn" onclick="Send(event,this)" value="Accept Invitation" />
<input type="submit" name="actionBtn" onclick="Send(event,this)" value="Decline Invitation" />
</form>
#section scripts{
<script>
function Send(ev,el) {
ev.preventDefault();
var data = $("input[name='TeamInviteBy']").val();
var value = $(el).val();
$.ajax({
url: '#Url.Action("ActionInvitation", "Home")',
type: 'post',
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: { TeamInviteBy: data, actionBtn: value},
success: function (data) {
$("#invitationActionMessage").append('Invitation Accepted');
}
});
}
</script>
}
Action:
public async Task<IActionResult> ActionInvitation( UserViewModel userViewModel , string actionBtn)
{
if(actionBtn="Accept Invitation")
{
//...
}
else
{
}
}
Result:

ajax form is not submitted, just refreshed and nothing

i have a form to register new users. here is the form:
<label for="add-username" class="col-md-4 control-label">Username:</label>
<div class="col-md-8">
<input id="add-username" name="username" type="text" class="form-control" placeholder="username"/>
</div>
</div>
<div class="form-group">
<label for="add-password" class="col-md-4 control-label">Password:</label>
<div class="col-md-8">
<input id="add-password" name="password" type="password" class="form-control" placeholder="password"/>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-4 col-md-8">
<c:if test="${duplicate}">
<p class="alert alert-danger">I'm sorry that username is already taken.</p>
</c:if>
<div id="validationRegisterUserErrors" class="alert alert-danger" style="display:none"></div>
<button type="submit" id="user-register-button" class="btn btn-primary">Register</button>
</div>
</div>
at the end of this jsp file, i have added a script which posts the form in ajax. the script is:
$("#user-register-button").click(function(event){
event.preventDefault();
registerUser();
});
function registerUser(){
var errorDiv = $("#validationRegisterUserErrors");
$.ajax({
url: 'user',
type: 'POST',
headers:{
'Content-type': 'application/json'
},
'dataType' : 'json',
data: JSON.stringify({
firstName: $('#add-first-name').val(),
lastName: $('#add-last-name').val(),
email: $('#add-email').val(),
username: $('#add-username').val(),
password: $('#add-password').val()
})
}).success(function(data){
errorDiv.empty();
errorDiv.hide();
window.location="login";
}).error(function (data, status){
errorDiv.empty();
errorDiv.show();
$.each(data.responseJSON.fieldErrors, function (index, validationError){
errorDiv.append(validationError.message);
errorDiv.append("<br>");
});
});
}
the url "user" is in usercontroller:
#ResponseBody
#ResponseStatus(HttpStatus.CREATED)
#RequestMapping(value="/user", method=RequestMethod.POST)
public User registerUser(#Valid #RequestBody User user, Model model){
user.setPassword(encoder.encode(user.getPassword()));
user.setRole("ROLE_USER");
try {
userDao.createUser(user);
} catch (DuplicateKeyException e){
boolean duplicate = true;
model.addAttribute("duplicate", duplicate);
}
return user;
}
but when i click register the page refreshes and in the url is written http://localhost:8080/signup?firstName=abc&lastName=adcd&email=adc%40ll.com&username=abcdef&password=9376868355
however no user is added. even if i don't fill out the form and click on register button, no validation error appears and it just refreshes the page. what can be the problem?
thanks for your great participation!!!
the problem was in headers:{...}.i changed my ajax to below and the problem solved:
function registerUser(){
var errorDiv = $("#validationRegisterUserErrors");
$.ajax({
url: 'user',
type: 'POST',
data: JSON.stringify({
firstName: $('#add-first-name').val(),
lastName: $('#add-last-name').val(),
email: $('#add-email').val(),
username: $('#add-username').val(),
password: $('#add-password').val(),
homeAddress:$('#add-home-add').val(),
workAddress:$('#add-work-add').val(),
phoneNumber:$('#add-phone').val(),
jobPosition:$('#add-job').val(),
fieldOfStudy:$('#add-field').val()
}),
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'dataType' : 'json'
}).success(function(data, status){
alert("User has been added.");
$('#add-first-name').val('');
$('#add-last-name').val('');
$('#add-email').val('');
$('#add-username').val('');
$('#add-password').val('');
$('#add-home-add').val('');
$('#add-work-add').val('');
$('#add-job').val('');
$('#add-field').val('');
$('#add-phone').val('');
errorDiv.hide();
window.location="login";
}).error(function (data, status){
errorDiv.empty();
errorDiv.show();
$.each(data.responseJSON.fieldErrors, function (index, validationError){
errorDiv.append(validationError.message);
errorDiv.append("<br>");
});
});
}

Node JS Form Sumit using Ajax

I am new in Node JS , I want to submit a form using ajax like all we are doing in PHP/CakePHP but here i am facing a problem.
HTMl code
<form role="form" action="javascript:;" id="myform">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-default" id="enter">Submit</button>
</form>
My AJAX code is
$('.btn').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
$.ajax({
url: '/ajax',
type: 'POST',
cache: false,
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
console.log(data);
console.log(JSON.stringify(data));
},
error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err);
}
})
});
app.js code
app.post('/ajax', bodyParser(), function (req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
var input = JSON.stringify(req.body);
var data = {
name : input.name,
email : input.email
};
var query = db.query("INSERT INTO users set ?",data, function(err, rows){
console.log(query.sql);
if (err)
console.log("Error inserting : %s ",err );
res.send({'success' : true, 'message' : 'Added Successfully'});
});
});
But when i submit this form then it generate an error in node console like
SyntaxError: Unexpected token "
at parse (D:\man_node\node_modules\body-parser\lib\types\json.js:83:15)
I think that, I am not 100% sure, that you should replace var data = $('#myform').serialize(); with var data = $('#myform').serializeArray();

Integrating AJAX with mailchimp

I'm trying to integrate AJAX with a mailchimp form. I’ve followed another member’s answer but still cannot get it to work. Could you guys see what's wrong with my code?
Thank you.
Here is my code:
<form id="form">
<script>
$( "button" ).click(function() {
formData = {
u: "xxxxxxxxx",
id: "xxxxxxxxx"
};
$.ajax({
url: "http://xxxxxxxxxxxxxxxxxxxxxxx/post-json?",
type: "GET",
crossDomain: true,
contentType: 'application/json',
data: formData,
dataType: "json",
success: function(data) {
//action
},
error: function() {
//action
}
});
});
</script>
<fieldset>
<label for="email_input_id"><input placeholder=
"Type Your Email" type="email" /></label>
</fieldset><button type= "submit">Submit</button>
I finally got my code working.
<form id="form" action="https://xxxxx.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="GET">
<input type="hidden" name="u" value="xxxx">
<input type="hidden" name="id" value="xxxx">
<input type="EMAIL" autocapitalize="off" autocorrect="off"
name="MERGE0" id="MERGE0" size="25" value=""
placeholder="Type your email and press enter">
<p id="response"> </p>
</form>
<script>
$('#form').submit(function(e) {
var $this = $(this);
var paragraph = document.getElementById('response');
$.ajax({
type: "GET",
url: "https://xxx.com/subscribe/post-json?u=xx&id=xx&c=?",
data: $this.serialize(),
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server."); },
success : function(data) {
if (data.result != "success") {
paragraph.innerHTML = data.msg;
} else {
paragraph.innerHTML = data.msg;
}
}
});
return false;
});
</script>

Resources