My purpose is once modal form submitted, ajax pass the username and password to a view and get back the json info to update the modal form, I trace the djanog code ,and 100% sure the JsonResponse(rsdic) has been executed in server side, as well as client fully receive the son info with ajax success function.
The problem is how to update the #error_message1 field which embeded in model. I tried .html() or .append(), all failed.
I leave the core coding for your reference, many thanks again for your help again.
ajax component:
$.ajax(
{
type: "POST",
url: url,
data: {
'username': username,
'password': password
},
dataType: 'json',
success: function(data){
$('#login-form')[0].reset();
if (data.ret != '1107'){
var htmlcode ="<p> data.info </p>";
$('#modal').find('.error_message1').append(htmlcode);
}
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
html component:
<div class="modal fade" id="modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="form-modal-body" class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4>EXP LOGIN</h4>
<form role="form" action="{% url 'auth_login' %}" method="post" id="login-form">
{% csrf_token %}
<ul>
<li>
<div class="g-icon"><i class="iconfont icon-yonghu"></i></div>
<input type="text" name="username" id="username" value="" placeholder="User name" />
</li>
<li>
<div class="g-icon"><i class="iconfont icon-mima"></i></div>
<input type="password" name="password" id="password" value="" placeholder="Password" onblur="check1()" />
<div class="g-cue" id="error_message1">Your email or password was entered incorrectly.</div>
</li>
</ul>
<div class="g-btn">
<input class="g-submit" id='login-button' type="submit" value="{% trans 'Log in' %}" />
<input type="hidden" name="next" value="{{ next }}" />
</div>
<p><span>{% trans "Not a member?" %} Join now.</span></p>
</form>
</div>
</div>
</div>
</div>
you have error_message1 as id not class
$('#modal').find('#error_message1').html(htmlcode);
Related
I am trying to Check weather email exist or not to send reset password link.
For that am using ajax function but its showing 500 internal server error before runing ajax.
I knw 500 is for token miss match error but do i need token to check email existing or not.
But I think so, with the form tag token is auto generated and then also am using {{ csrf_field() }}
But it showing same error 500 Internal server. Just Help how can resolve this issue and do i need to generate token manually.
Views : login.blade.php
{!! Form::open(array('url' => '/auth/login', 'class' => 'form- login')) !!}
<div class="form-title"> <span class="form-title">Login</span> </div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Username</label>
<input class="form-control form-control-solid placeholder-no-fix required" type="text" autocomplete="off" placeholder="Email" name="email" />
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control form-control-solid placeholder-no-fix passwordclass required" type="password" autocomplete="off" placeholder="Password" name="password" />
</div>
<div class="form-actions">
<button type="submit" class="btn red btn-block uppercase clicklogin" style="background-color:#d5ed31 !important;border-radius:4px !important;border:1px solid #ddd;">Login</button>
</div>
<div class="form-actions">
<div class="pull-left">
<label class="rememberme mt-checkbox mt-checkbox-outline">
<input type="checkbox" name="remember" value="1" />
Remember me <span></span> </label>
</div>
<div class="pull-right forget-password-block"> <a class="btn-link" data-target="#modalforget" data-toggle="modal">Forgot Password? </a></div>
</div>
{!! Form::close() !!}
<!-- END LOGIN FORM -->
<!-- BEGIN FORGOT PASSWORD FORM-->
{!! Form::open(array('url'=>'password/reset','class' => 'form-horizontal create_forget_form','method'=>'POST', 'id' =>'forgetdata', 'files' => true)) !!}
{{ csrf_field() }}
<div class="modal fade" id="modalforget" tabindex="-1" data-width="760px" >
<div class="modal-dialog" style="width:760px !important;">
<div class="modal-content" style="background-color:#26344b;padding:20px;border-radius:12px !important;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<div class="form-title"> <span class="form-title">Forget Password</span> </div>
</div>
<div class="modal-body" style="height:auto !important;">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<strong style="color: #ffffec; font-size: large; "> Please enter your email. A password reset link will be sent to this email.</strong>
</div>
</div>
</div>
<div class="row"></div>
<div class="row">
<div class="col-md-10">
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<input class="form-control required" type="email" autocomplete="off" placeholder="Email" id="forget_email" name="forget_email"style="font-size: large;" />
<span class="my-error-class" id="email_status"></span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" value="Submit" id="submitButton" class="btn green">Submit</button>
<button type="button" value="Cancel" class="btn default red" data-dismiss="modal">Cancel</button>
<button type="reset" value="Clear" class="btn blue">Clear</button>
</div>
</div>
</div>
</div>
</div>
</form>
Ajax function in login.blade.php
<script type="text/javascript">
$('#submitButton').click(function(){
var formdata=new FormData($(this)[0]);
$.ajax({
url:"{{ URL::to('password/reset') }}",
type: 'POST',
data: formdata,
async: false,
cache: false,
contentType: false,
processData: false,
context:this,
dataType: "json",
success: function (returndata)
{
if(returndata == 0)
{
$( '#email_status' ).html('This Email does not Exists');
return false;
}
else
{
$( '#email_status' ).html("");
return false;
}
},
error: function(data)
{
console.log(data);
}
});
});
</script>
Route file:
Route::group(['middleware' => 'auth'], function()
{
Route::post('password/reset','Auth\AuthController#resetPassword');
}
Controller Auth\AuthController#resetPassword:
public function resetPassword()
{
$email =Input::get('forget_email');
$user_email = DB::table('users')->where('email', $email)->whereNull('deleted_at')->first();
if($user_email)
{
return '1';
}
else
{
return '0';
}
}
Screen Shot Of Error
I think you have to write your route outside auth group.
Route::post('password/reset','Auth\AuthController#resetPassword');
The issue is you are using POST request with ajax and for every post request you have to pass the csrf-token with the request like:
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
Put this in your ajax code and everything will be fine.
Or if you want to exclude the specific URI from CSRF verification, go to project/app/Http/Middleware, there is a file VerifyCsrfToken.php in which put the routes list in:
protected $except = [
// route list here
];
All the routes defined here excludes from csrf-token check.
I want to display an error in a bootstrap modal when a user submits an incorrect login form. Right now, the submitting the form just reloads the current page so I can't get the JSON response.
basic.html where the login modal appears
...
<button type="button" class="btn btn-secondary btn-sm" data-toggle="modal" data-target="#loginModal" id="login_modal_trigger">Log In</button>
{% include 'registration/login.html' with form=form %}
...
registration/login.html
<div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Log In</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="content-container" class="container p-none">
<div class="lgn-container col-lg-8">
<form id="login-form" method="post"
action="">
{% csrf_token %}
<table class="table">
<tr>
<td><label for="id_username">Username</label></td>
<td><input id="id_username" name="username"
type="text" class="form-control"></td>
</tr>
<tr>
<td><label for="id_password">Password</label></td>
<td><input id="id_password" name="password"
type="password" class="form-control"></td>
</tr>
</table>
{% if form.errors %}
<p class=" label label-danger">
Your username and password didn't match.
Please try again.
</p>
{% endif %}
<input type="submit" id="ajax_form_submit" value="Login"
class="btn btn-primary pull-right" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
script.js:
I figured event.preventDefault(); would prevent refreshing when there is an error.
$(document).ready(function() {
$("#login-form").submit(function(event) {
jQuery.ajax({
"data": $(this).serialize(),
"type": $(this).attr("method"),
"url": "{% url 'login_user' %}",
"success": function(response) {
// switch(response.code) {
// // Do what you want with the received response
// }
console.log(response);
if (response.code == 0) {
console.log("fail");
}
}
});
event.preventDefault();
});
});
project/urls.py
...
urlpatterns = [
...
url(r'^login/$', views.login_user, name='login_user'),
...
]
...
app/views.py
from django.contrib.auth import authenticate, login
def login_user(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
return HttpResponseRedirect(reverse('app:detail', args=(username,)))
else:
# Return an 'invalid login' error message.
response = {'code': 0}
return HttpResponse(response, content_type='application/json')
# return HttpResponse(status=404)
The login modal currently doesn't even work with my edits, but my main problem is the refreshing of the page after submitting instead of just giving me a response in JSON to then edit the HTML with. The js I use is mostly from other posts.
In your app/views.py you need to change else (that identify erro login) to:
return HttpResponseRedirect(reverse('app:login', args=(response,)))
Now you pass in the first parameter the name of your login view, and agr you send the 'response'.
In your template:
{% if code == 0 %}
<p class=" label label-danger">
Your username and password didn't match.
Please try again.
</p>
{% endif %}
I have a form field where the user enters data. If the user has entered a duplicate data which is already stored in the database and I have done it so to detect it's a duplicate data. But I want to make the field in a form in which the user enters duplicate data to be displayed red showing that this username already exists along with the field which he has entered duplicate data highlighting red. I have already written a JavaScript function to fetch all the data from database and it is doing so. It's not able to highlight the field red in which user has entered duplicate data.
Any help would be deeply appreciated.
{% extends "base.html" %}
{% block head %}
<script src="{{ url_for('static', filename = 'user.js') }}"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<style>
.buttonalign{
margin-top: 20px;
}
</style>
{% endblock %}
{% block content %}
<div class= "content" style="z-index: 1">
<div class="row">
<div class="wrapper col-md-offset-4 col-md-4 col-md-offset-4">
<form action="/auth/add_users" method="post" name="Add_Form">
<h3 class="text-center">Add User</h3>
<hr>
<div class="form-group">
<h4> Username </h4>
<input type="text" class="form-control Email/Username" name="username" id="username" placeholder="username" required="true" autofocus="" />
</div>
<div class="form-group">
<h4> Password </h4>
<input type="password" class="form-control Password" name="password" id="password" placeholder="password" required="true"/>
</div>
<div class="form-group">
<h4> Email </h4>
<input type="email" class="form-control Email/Username" name="email" id="email" placeholder="email" required="true" autofocus="" />
</div>
<div class="form-group">
<h4> Site_url </h4>
<input type="text" class="form-control site_url" name="site_url" id="site_url" placeholder="site_url" required="true" autofocus="" />
</div>
<div class="buttonalign">
<button class="btn btn-sm btn-primary btn-block" name="Submit" value="Submit" type="Submit" id="submit">Submit</button>
</div>
</form>
</div>
</div>
</div>
<div class="content" style="z-index: 999; position: absolute; right: 240px; top: 10px;" >
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary" id="box" style="display:none;">
<div class="panel-heading">
<button type="button" class="close" data-target="#box" data-dismiss="alert">
<span aria-hidden="true">×</span><span class="sr-only">X</span>
</button>
Subscribers
</div>
<div class="panel-body" style="max-height: 500px; overflow-y: scroll;">
<div id = "show-json-result"></div>
<input type="hidden" id = "userid" value="{{current_user.id}}"/>
</div>
</div>
</div>
</div>
</div>
<script>
$( "#username" ).focusout(function() {
username = $(this).value;
$.ajax({
method: "GET",
url: "/auth/get_users",
data: { username: "username" }
}).done(function( response ) {
<!-- console.log(":::::"); -->
if(response == "username"){
console.log($username);
$("username").borderColor = "red";
}
});
});
$( "#email" ).focusout(function() {
email = $(this).value;
$.ajax({
method: "GET",
url: "/auth/get_users",
data: { email: "email" }
}).done(function( response ) {
if(response == "email"){
$("email").borderColor = "red";
}
});
});
$( "#site_url" ).focusout(function() {
site_url = $(this).value;
$.ajax({
method: "GET",
url: "/auth/get_users",
data: { site_url: "site_url" }
}).done(function(response) {
if(response == "site_url"){
$("site_url").borderColor = "red";
}
});
});
</script>
{% endblock %}
I think $("username").borderColor = "red"; is wrong , you can define an id for that elements and use
$("#username").css("border-color","red");
I am using this form as a connector with my server in order when i put the correct user and password connects with the form of my web and redirects to the ip but when i put a wrong password or a wrong user i dont want to redirect just stay in the same page.
<div class="container"><!-- CONTAINER -->
<div class="row"><!-- ROW -->
<div class="col-md-4"></div>
<div class="col-md-4"><!-- COL 3 -->
<form class="login" autocomplete="off" method="post" action="http://139.59.200.233:8080/track/Track">
<h5>SERVIDOR 1</h5>
<h2 class="title">Acceso a plataforma GPS</h2>
<input id="accountLoginField" type="hidden" value="occidentegps" name="account" required>
<input type="text" name="user" placeholder="Usuario" autofocus required/>
<i class="fa fa-user"></i>
<input type="password" name="password" placeholder="Contraseña" required />
<i class="fa fa-key"></i>
<button>
<i class="spinner"></i>
<span class="state">INICIAR SESIÓN</span>
</button>
</form>
</div><!-- COL 3 -->
<div class="col-md-4"></div>
</div><!-- ROW -->
</div><!-- CONTAINER -->
The user will always be redirected when using a html form submission. The only way to check if the credentials are correct before redirecting the user is to submit the form data using JavaScript (xhr, ajax, or fetch).
Try something like this:
$("#your-submit-button").click(function(){
$.ajax({
type: 'POST',
url: 'youriP',
dataType: 'json',
data: $('#yourForm').serialize(),
success: function (x) {
// Code to redirect
},
});
return false;
});
I hava a bootstrap modal form that i use to send a 4 field message. After the submit button is press i want to show the user a "thank you" message. But instead of that my form is closing and the page is refreshing.
How can i do for the modal form to stay open in order to display below the submit button the message.
Thank you!
<section class="modal-form">
<!-- Modal Video first page -->
<div class="modal fade" id="participa-modal" tabindex="-1" role="dialog" aria-labelledby="participa-modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Participă la un demo!</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form id="form" method="post" class="contact" action="" enctype="multipart/form-data" data-parsley-validate>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="homepage_firstname" id="homepage_firstname" class="form-control-contact" placeholder="Nume" required>
</div>
<div class="form-group">
<input type="email" name="homepage_email" id="homepage_email" class="form-control-contact" placeholder="Email" required>
</div>
<div class="form-group">
<input type="text" name="homepage_phone" id="homepage_phone" class="form-control-contact" placeholder="Telefon" data-parsley-type="number" minlength="10" maxlength="10" required>
<input type="hidden" name="inner_message" id="inner_message" value="Participare demo curs!">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control-contact" name="homepage_message" id="homepage_message" placeholder="Scrisoare de intentie"></textarea>
</div>
</div>
</div>
<div class="form-actions">
<input type="hidden" name="homepagesubmitted" value="TRUE" />
<button type="submit" class="btn orange sign-in-btn">Înscrie-te</button>
</div>
<?php echo $homepage_send ?>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- End Modal Video first page -->
</section>
UPDATE:
Ok. So i've manage to make it work the following code $(function () {
var frm = $('#participa-modal');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
location.reload();
}
});
ev.preventDefault();
});
});
The quetion is how can i replace alert('ok') to point for a thank you in the same pop-up under the SEND button.
$(".modal-body form").submit(function(e) {
var url = "ActionScript.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), // serializes the form's elements.
success: function(data) {
$(this).html("Thank you!!!");
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
check the above code for your requirement
Terms Used
$(".modal-body form") class and child form selector in order to target your submitting form
.submit( to trigger event on submit of your form
type: "POST" is for secure traversing of data, by method post
.serialize() is to gather (assemble) and send the posting data
success: is a callback in order to proceed while the submission is successful.