ajax form is not submitted, just refreshed and nothing - ajax

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>");
});
});
}

Related

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:

Laravel Ajax update request is duplicating data

i am trying to update data using ajax, but my data is being duplicated,
due to ajax URL, i am not sure if i am passing correctly/
Ajax Code:
jQuery(document).ready(function($) {
$('#update-form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers/" + $('#update-id').attr("value"), //error is here
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
alert("updated");
},
});
});
});
view code:
i have table with list of teachers, and edit button for each teacher;
<button type="button" id="btn" value="{{ $teacher->id }}" class="btn btn-primary btn-block btn-sm edit-btn">Edit</button>
in form i have hidden field
<form method="post" id="update-form">
{{ method_field('PATCH') }}
<input type="hidden" id="update-id" value="{{$teacher->id}}" >
<div class="">
<label for="efirst">efirst</label>
<input type="text" class="form-control" name="efirst" id="update-efirst">
<textarea name="esecond" class="form-control" id="update-esecond" rows="6"></textarea>
</div>
<button type="submit" class="btn btn-success" id="update-submit">Update</button>
</form>
when i click on update, teacher ID's are being changed, one teacher id becomes another teacher id. is it correct way to pass teacher id from hidden field?
Write route name like below
At Web.php
Route::post("teacher/{id}/edit","YourController")->name("teacher.update");
At Blade File
$('#update-form').on('submit', function (e) {
e.preventDefault();
var id = $('#update-id').val(); // $('#update-id').attr("value") also ok
$.ajax({
method: "post",
url: "{{ route('teacher.update',id) }}",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
alert("updated");
},
});
});
Try this.
It will be work

Ajax Submitting form Twice

I have a form in a modal window that allows a user to resend a confirmation email. When the form is submitted, the confirmation email is sent twice, instead of once. Everything else is working exactly as it should.
Form is pretty standard:
<form enctype="multipart/form-data" id="ReMailf" name="ReMailf" role="form" data-toggle="validator">
<fieldset>
<div class="row">
<p>You may enter a different email than your original if you wish. However, the original email will remain as the main contact on your application.</p>
<label class="desc" for="prim_email"> Email </label>
<input id="prim_email" name="prim_email" type="email" class="form-control" value="<?php echo $tE['prim_email']; ?>" data-error="Please Enter A Valid Email Address" required/>
<div class="help-block with-errors"></div>
</div>
<div class="row">
<input id="submitForm" name="submitForm" class="btn btn-success" type="submit" value="Resend Conformation "/>
<input name="uniqid" type="hidden" value="<?php echo $tE['unqID']; ?>"/>
<input name="ReMAIL" type="hidden" value="ReMAIL"/>
</div>
</fieldset>
</form>
… and here's the handler:
$(document).ready(function () {
$("#ReMailf").on("submit", function(e) {
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#ReMailf").submit();
});
});
I've read a number of other post about this, and tried some of the suggestions, but nothing is working. It either doesn't submit at all, or submits twice.
This is the only form on the page...
Suggestions please?
It is because you are using a button or submit to trigger the ajax event. Use this instead:
$(document).ready(function() {
$("#ReMailf").on("submit", function(e) {
e.preventDefault(); //add this line
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
or you can just use a simple form with action and method. It will do the job

variable is not found inside ajax

<div class="modal-body">
<form>
<div class="form-group">
<label for="email" class="col-form-label">Email address:</label>
<input type="email" class="form-control" id="signUpEmail" name="email">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Password:</label>
<input type="password" class="form-control" id="signUpPassword" name="password" onchange="check_pass()">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Confirm Password:</label>
<input type="password" class="form-control" id="signUpConPassword" name="password" onchange="check_pass()">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="signUpSubmit" disabled="true" >Sign Up</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function check_pass()
{
//alert(document.getElementById('signUpPassword').value);
if (document.getElementById('signUpPassword').value ==
document.getElementById('signUpConPassword').value) {
document.getElementById('signUpSubmit').disabled = false;
}
else
{
document.getElementById('signUpSubmit').disabled = true;
}
}
$('#signUpSubmit').click(function()
{
//alert("signup completed");
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: $email,
password: $password
},
success: function() {
alert('Email Sent');
}
});
});
</script>
This code snippet shows ReferenceError: $email is not defined when I click on the signupSubmit button although I defined the variable inside the function.
I also try
var email=document.getElementById('signUpEmail').value;
var password = document.getElementById('signUpPassword').value;
but, same error. I guess there is a problem in variable declaration. What is the correct form of variable declaration inside the function?
You have to change the $email and $password to email ,password
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: email,
password: password
},
success: function() {
alert('Email Sent');
}
});
Remove the $
data: {
email: $email,
password: $password
},
The data being passed has two properties - "email" and "password", the values of the properties are stored in the variables email and password.
Your code should look like this:
/* Remove these two lines */
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
...
data: {
"email": $("#signUpEmail").val(),
"password": $("#signUpPassword").val()
}
The $ is the jQuery function call, and the "#signUpEmail" is the selector for the element with an id of "signUpEmail". The val() method will return the value of the input.
document.getElementById("something").value
is the same as
$("#something").val()
If you're using jQuery for the Ajax, you might as well use it to get the values.

Frontend ajax POST call can't login to Django

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);
}
});

Resources