JavaScript is not executed in tracking form - javascript

I'm doing an e-commerce website for school and got the task to implement an order tracking system to display the status history of the order. I used a template for this, and half of the code is working. In the views.py file I fetch the information form the database and put it in json format.
However in my html file there is a js script that is supposed to display the iformation from the database and that is not working.
I unfortunately do not have any previous experience with web development, so I'm lost as to why it doesn't work because in the video that used the template it worked.
If someone could help me that would be fantastic as we have to hand the project in in two days.
PS.:
When I put in the ref code and email, it just gives back the HttpResponse with the json. I'm not sure what to do with the HttpResponse though. How does it interact with the script in the html file?
I put
jQuery.noConflict();
at the start of the script as I thought maybe the bootstrap js was overshadowing my script. It didn't do anything though.
Here is my views.py function:
def tracking(request):
if request.method == "POST":
ref_code = request.POST.get('ref_code', '')
email = request.POST.get('email', '')
try:
order = Order.objects.filter(ref_code=ref_code, email=email)
if len(order) > 0:
update = OrderUpdate.objects.filter(ref_code=ref_code)
updates = []
for item in update:
updates.append(
{'text': item.update_desc, 'time': item.timestamp})
response = json.dumps(updates, default=str)
return HttpResponse(response)
else:
return HttpResponse('Please enter a valid ref code and email address.')
finally:
print()
return render(request, 'order_tracking.html')
Here is the script from the order_tracking html file:
<script>
jQuery.noConflict();
$('#trackingForm').submit(function(event) {
$('#items').empty();
var formData = {
'ref_code': $('input[name=ref_code]').val(),
'email': $('input[name=email]').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
};
print(ref_code)
$.ajax({
type: 'POST',
url: '/order-tracking/',
data: formData,
encode: true
})
.done(function(data) {
console.log(data)
updates = JSON.parse(data);
if (updates.length > 0 & updates != {}) {
for (i = 0; i < updates.length; i++) {
let text = updates[i]['text'];
let time = updates[i]['time'];
mystr = `
<li class="list-group-item d-flex justify-content-between align-items-center">
${text}
<span class="badge badge-primary badge-pill">${time}</span>
</li>`
$('#items').append(mystr);
}
} else {
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
Sorry, We are not able to fetch this ref code and email. Make sure to type correct ref code and email</li>`
$('#items').append(mystr);
}
});
event.preventDefault();
});
</script>
And this is the rest of the html file, I'm not sure if it's relevant:
{% block content %}
<div class="container tracking">
<div class="col my-4">
<h2> Enter Your Order ID and Email address to track your order </h2>
<form method="post" action="#" id="trackingForm">{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputname">Ref Code</label>
<input type="text" class="form-control" id="ref_code" name="ref_code" placeholder="Ref Code">
</div>
<div class="form-group col-md-6">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email">
</div>
<button type="submit" class="btn btn-primary">Track Order</button>
</div>
</div>
<div class="col my-4">
<h2>Your Order Status:</h2>
<div class="my-4">
<ul class="list-group" id="items">
</ul>
</div>
</div>
</div>
{% endblock content %}

Related

jquery not sending data to Post Action Asp.Net Core MVC

I am trying to save a ViewModel object from a partial view in a modal, and I get a 404 error when I try to post it. The url is being called, but the ViewModel data isn't being sent. I have been reading similar questions on here and on MSN for hours and nothing I've tried fixes the problem. I took out the repetitive days of the week code for brevity, but I can
add them back in if anyone wants a complete working example. Here is the code
EmployeeViewModel
public class EmployeeViewModel
{
public bool Monday { get; set; } = false;
//...bool properties for Tuesday through Sunday
public Employee Employee { get; set; }
}
Employee/ _AddEmployeeModalPartial
#model JSarad_C868_Capstone.ViewModels.EmployeeViewModel
#Html.AntiForgeryToken()
<div class="modal modal-fade" id="addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="addEmpoyeeLabel">Add Employee</h4>
<button type=button class="close" data-bs-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Add">
<div class="form-group">
<input asp-for="Employee.Id" class="form-control" />
<input asp-for="Employee.Availability" class="form-control" />
<label asp-for="Employee.Role"></label>
<select asp-for="Employee.Role" class="form-control">
<option value="Bartender">Bartender</option>
<option value="Server">Server</option>
</select>
<span asp-validation-for="Employee.Role" class="text-danger"></span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Name"></label>
<input asp-for="Employee.Name" class="form-control" />
<span asp-validation-for="Employee.Name" class="text-danger"></span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Phone"></label>
<input asp-for="Employee.Phone" class="form-control" />
<span asp-validation-for="Employee.Phone" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Email"></label>
<input asp-for="Employee.Email" class="form-control" />
<span asp-validation-for="Employee.Email" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Address"></label>
<input asp-for="Employee.Address" class="form-control" />
<span asp-validation-for="Employee.Address" class="text-danger">
</span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label>Availabiliy</label>
</div>
<div class="row pb-4">
<div class="col">
<div class="form-check">
<input asp-for="Monday" class="form-check-input"
type="checkbox" />
<label asp-for="Monday" class="form-check-label"></label>
</div>
<!--...//form check boxes for Tuesday trough Sunday -->
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"
data-bs-save="modal">Save</button>
</div>
</div>
</div>
</div>
EmployeeController.cs
[HttpGet]
public IActionResult Add()
{
EmployeeViewModel viewModel = new EmployeeViewModel();
return PartialView("_AddEmployeeModalPartial", viewModel); ;
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Add(EmployeeViewModel viewModel) //code never reaches this Action
{
viewModel.Employee.Availability = ConvertDaysToChar(viewModel.Employee.Availability)
if (ModelState.IsValid)
{
_db.Employees.Add(viewModel.Employee);
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return PartialView("_AddEmployeeModelPartial", viewModel);
}
}
site.js
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-bs-toggle="ajax-modal"]').click(function (event) {
/* event.preventDefault();*/
var url = $(this).data('url');
console.log(url)
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-bs-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
console.log(actionUrl);
var sendViewModel = form.serialize();
console.log(sendViewModel);
//$.post(actionUrl, sendViewModel).done(function (data) {
// PlaceHolderElement.find('.modal').modal('hide');
/*above is the code from a tutorial for modals. It also doesn't send the object to
post action*/
$.ajax({
type: 'POST',
url: actionUrl,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(sendViewModel),
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
})
})
When I click the save button on the model, the console.log(sendViewModel) returns the correct Serialization with all of the properties and their correct names. And the properties change correctly when there is input.
Employee.Id=&Employee.Availability=&Employee.Role=Bartender&Employee.Name=&Employee.Phone=&Employee.Email=&Employee.Address=&Monday=false&Tuesday=false&Wednesday=false&Thursday=false&Friday=false&Saturday=false&Sunday=false
But I get an error "Failed to load resource: the server responded with a status of 404 ()"
and when I check it the page says "No webpage was found for the web address: https://localhost:44313/Add HTTP ERROR 404" as if it's trying to get a post. It is also missing the controller, but if I change my form action to "Employee/Add" in the _Partial view it still doesn't send the data along with the url, which is causing an entirely different problem. I would greatly appreciate any help or guess or input of any kind. I'm about five seconds away from throwing my laptop out the window on this one. Thanks.
1.Remove the #Html.AntiForgeryToken() inside your form,like below:
<form action="Add" >
#Html.AntiForgeryToken()
....
Then after you serialize the form you can get the AntiForgeryToken, like below:
Because when you don't add #Html.AntiForgeryToken()inside form, after you serialize the form you don't get the AntiForgeryToken, like below:
Besides, if you use <form asp-action="Add" > In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add #Html.AntiForgeryToken(),you can find in the below :
2.change your ajax like below:
$.ajax({
type: 'POST',
url:'/Employee/Add',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: sendViewModel,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
result:
First, I had to change the form action from "Add" to "Employee/Add". ThenI had to remove the antiforgery token from my post action. The first code that is commented out actually works fine otherwise. In my defense I did remove the antiforgery token when I had the wrong URL, but I forgot to retest that when I had the correct one.

How do you implement input( or form) dependent on a select menu(drop down list)?

I'm working on grading system and I'm currently working on the form that's deals with the user entering the students results now the form I have, has 2 drop-down list(classroom, students) that are dependent. The issue and where I'm stuck is
When the user select the classroom the second drop-down menu will only show the students in that class, I have already figure that out..the issue is I want the input fields for how much subject the student is doing to appear so that the user can enter the grades for each subject specific to that student in the class
Eg if I select classroom 1b and selected student Mary.. if Mary is doing 5 subjects then 5 input field should appear so that I can enter the mark for the subjects
Link with a video showing what I'm talking about video showing an examplehttps://drive.google.com/file/d/11FoCZyOBVdUhTcvCqA1Ke0fEgRmMVC-G/view?usp=drivesdk
Models.py
Class Classroom(models.Models): name = models.charfield()
Class marks (models.Models): classroom = models.foreignkey(Classroom) Grade = models.Floatfield()
Html form
<div class="container-fluid">
<form id="result-form" method="post">
{% csrf_token %}
<!-- Modal -->
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"> {% block modal-title%} Add Result {% endblock%}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12" id="msg8" style="font-size: 2rem; color:rgb(255, 144, 47)"></div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Class Name</label>
{% render_field form.room class+="form-control" %}
</div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Exam Name</label>
{% render_field form.exam class+="form-control" %}
</div>
<div class="col-md-12 form-group p-2">
<label class="form-label">Student</label>
{% render_field form.student class+="form-control select2" %}
</div>
<div class="hidden" id="subject-fields"></div>
<div class="form-group mb-3 pt-2">
<button type="button" id="resBtn" class="btn btn-info" title="Add">Submit</button>
</div>
</div>
</div>
</form>
</div>
{% block script%}
{% endblock%
script
$(document).on('click', '#submit-btn', function(event){
var response_data = []
var subject_name= $('.course');
var subject_objs = $('.subject_id');
for(i=0;i<subject_name.length;i++){
var subject_id = $(subject_objs[i]).find('input').val();
var grade_input = {
"Marks": subject_id,
}
response_data.push(grade_input);
}
$.ajax({
type: "POST",
url: "{% url 'marks' %}",
data: response_data,
success: function(response){
alert("Success");
}
});
});
This is how your view should look like.
def question_choice_view(request):
if request.method == "POST":
question_choice_data = request.POST['data']
I am not a jQuery User. As far as i can see i would put a eventlistener on the student form via .addEventListener('change', (event)See here. This would fire a function every time something changes on the select option. With that you could also collect the selected option values of the classroom and student name and make a request to get the subject names for the chosen student. After successful response i would insert the subject fields via JavaScript in the DOM.
**
function createInput(item) {
// This function takes a item and creates a new input
var newLabel = ' <br><label for="$item-mark">$item:</label>'
var newInput = '<input type="text" id="$item-mark-id" name="$item-mark"><br><br>';
newLabel = newLabel.replaceAll("$item", item)
newInput = newInput.replaceAll("$item", item)
// combine into a single str
newInput = newLabel + newInput
var studInput = document.getElementById("student-id");
// insert element inputs after student
studInput.insertAdjacentHTML('afterend', newInput);
}
function cleanOldInputs(item) {
var oldELement = item + "-mark-id"
oldELement = document.getElementById(oldELement)
if (oldELement) {
// remove old label and input
oldELement.previousSibling.remove()
oldELement.remove()
} else {}
}
function getAPIcall() {
// This is what your API sends
var responsObject = ["writing", "creativity"];
// loop throug
responsObject.forEach(item => {
// if you already picked a student clean old inputs from DOM
cleanOldInputs(item)
// send to function for input creation
createInput(item)
})
}
// get the Student Input
var studentSelect = document.getElementById("student-id");
studentSelect.addEventListener("click", function() {
// Fire anything you like
getAPIcall()
});
<form action="/action_page.php">
<label for="student">Choose a student:</label>
<select name="student" id="student-id">
<option value="harry">harry</option>
<option value="ivy">ivy</option>
</select>
</form>
Quick and dirty**

How to display error on the same page when an error is returned by a form?

I have built a login form using below code.
I am using a CGI version CGIDEV2 native to IBMi series. I am Validating the userid and password in the flower.cgi program. If the userid and password are validated, I am loading another html file to show a table. This works flawlessly.
If the userid and password are wrong, I am returning out of the program without writing anything. This results in a 500 Internal server error.
I want to capture this 500 Internal server error using javascript. I have tried using ajax but was not successful as I have limited understanding of javascript.
What could be the best way to achieve this?
<form method="POST" action="/nature/flower.cgi">
<!-- Username input -->
<div class="form-outline mb-4">
<input type="text" name="userid" id="form3Example3" class="form-control form-control-lg" style="text-transform:uppercase" placeholder="Enter a valid IBMi UserID" />
<label class="form-label" for="form3Example3">IBMi UserID</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="passwd" id="form3Example4" class="form-control form-control-lg" placeholder="Enter password" />
<label class="form-label" for="form3Example4">Password</label>
<br>
</div>
<div class="d-flex justify-content-between align-items-center">
<!-- Checkbox -->
<div class="form-check mb-0">
<input class="form-check-input me-2" type="checkbox" value="" id="form2Example3" />
<label class="form-check-label" for="form2Example3">Remember me</label>
</div>
Forgot password?
</div>
<div class="text-center text-lg-start mt-4 pt-2">
<button type="submit" class="btn btn-primary btn-lg" style="padding-left: 2.5rem; padding-right: 2.5rem;">Login</button>
</div>
</form>
You can't capture an error from a URL the browser is navigating to.
The only way you could would be if you replaced the normal form submission with Ajax (in which the request is made and the response processed with JavaScript).
Generally speaking, if you were going to do that you would also want to rewrite the CGI program so it output structured data (e.g. as JSON) instead of semantic data (HTML).
It would not be a particularly small undertaking. You said you had tried it, which probably gives you some idea of the scope of it (i.e. far outside the scope of a Stackoverflow question).
A more sensible approach would almost certainly be to track down the cause of the 500 error and change the CGI program so it would capture it itself.
yes, the fetch api in javascript can post form data to your CGI program and check for the 500 response code. Then the web page can either display an error message or run the form.submit() method to actually submit the form up to the server.
Here is PHP and javascript code that simulates the whole thing. Should work similar with CGI. The key is you change the form submit button from type 'submit' to type 'button'. That way, clicking the submit button can run javascript code instead of the form being submitted to the server.
<?php
// site/tester/php/submit-form.php
header("Content-type: text/html; charset:utf-8;");
?>
<?php
$userid = isset($_POST["userid"]) ? $_POST["userid"]: '' ;
$passwd = isset($_POST["passwd"]) ? $_POST["passwd"]: '' ;
$remember = isset($_POST["remember"]) ? $_POST["remember"]: 'off' ;
if ( strtolower($userid) == 'alex')
{
http_response_code( 500 );
echo "$userid - invalid user name";
exit ;
}
?>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row mt-3">
<div class="col-auto">
<h1>submit form demo</h1>
</div>
</div>
</div>
<div class="container">
<div class="row mt-3">
<div class="col-4">
<form method="POST" id="main-form" action="./index.php">
<!-- Username input -->
<div class="form-outline mb-4">
<input type="text" name="userid" id="userid"
class="form-control form-control-lg"
value="<?= $userid ?>"
style="text-transform:uppercase" placeholder="Enter a valid IBMi UserID" />
<label class="form-label" for="userid">IBMi UserID</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="passwd" id="passwd" class="form-control form-control-lg"
placeholder="Enter password" />
<label class="form-label" for="passwd">Password</label>
<br>
</div>
<div class="d-flex justify-content-between align-items-center">
<!-- Checkbox -->
<div class="form-check mb-0">
<input class="form-check-input me-2" type="checkbox"
<?= ($remember == 'on' ? 'checked' : '' ) ?>
name="remember" id="form2Example3" />
<label class="form-check-label" for="form2Example3">Remember me</label>
</div>
Forgot password?
</div>
<div class="text-center text-lg-start mt-4 pt-2">
<button id="login-button" type="button" class="btn btn-primary btn-lg"
style="padding-left: 2.5rem; padding-right: 2.5rem;">
Login</button>
</div>
</form>
</div>
</div>
<div id="login-errmsg-collapse" class="collapse row mt-3">
<div class="alert alert-warning" role="alert">
<p id="login-errmsg">Invalid login. User name does not exist.</p>
</div>
</div>
</div>
<div class="container">
<div class="row mt-3">
<div class="col-auto">
<p>userid: <?= $userid ?></p>
<p>passwd: <?= $passwd ?></p>
<p>remember: <?= $remember ?></p>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<script src="./app.js"></script>
</body>
// ./submit-form/app.js
// enable the submit button click handler.
{
const elem = document.getElementById('login-button');
elem.addEventListener('click', event =>
{
login_click();
});
}
// -------------------------------- login_errmsg_show ---------------------
function login_errmsg_show( respText )
{
// show the response message in the bootstrap collapse alert box.
{
const elem = document.getElementById('login-errmsg') ;
elem.textContent = respText ;
}
const myCollapse = document.getElementById('login-errmsg-collapse')
const bsCollapse = new bootstrap.Collapse(myCollapse, {
toggle: false
});
bsCollapse.show( ) ;
}
// -------------------------------- login_click -------------------
async function login_click()
{
const elem = document.getElementById('main-form');
if (elem)
{
const {respText, status} = await webpage_post( ) ;
if ( status != '500')
{
elem.submit();
}
else
{
login_errmsg_show( respText ) ;
}
}
}
// --------------------------------- webpage_post -----------------------
async function webpage_post( )
{
const userid = document.getElementById('userid').value ;
const passwd = document.getElementById('passwd').value ;
const remember = 'on' ;
const url = "./index.php";
const params = { userid, passwd, remember } ;
const query = object_toQueryString(params);
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: query
});
const respText = await response.text();
const status = response.status ;
console.log( respText ) ;
return {respText, status} ;
}
// ------------------------- object_toQueryString ------------------------
function object_toQueryString(obj)
{
const qs = Object.keys(obj)
.map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]))
.join('&');
return qs;
}

how can i resolve the issue in displaying the ajax search results in django?

Problem
The results are being retrieved by the ajax search function but when I display the data retrieved in the selector using $(selector).htm(data) it loads whole the page with a page with correct search results.
The code is attached below with the screenshot of what I'm getting from this code for a better understanding.
JS
$('#searchsubmit').on('click', function(e){
e.preventDefault();
q = $('#search').val();
console.log(q);
updateContentBySearch(q);
});
function updateContentBySearch(q) {
var data = {};
data['search_by'] = q
// data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val();
$.ajax({
method: 'POST',
url: "{% url 'main:Search' %}",
data: {
'search_by': q,
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: function (data) {
searchSuccess(data)
}
});
}
function searchSuccess(data, textStatus,jqXHR)
{
$('#search-results').html(data);
}
HTML
<div class="row">
<div class="row justify-content-center" style="text-align:center">
<form class="d-flex col-md-6" id="searchform" method="POST">
{% csrf_token %}
<div class="input-group mb-3" style="text-align:center">
<input name="q" type="text" class="form-control" placeholder="Search" id="search">
<button class="btn btn-primary shadow px-5 py-2" type="submit" id="searchsubmit">Search</button>
</div>
</form>
</div>
<hr style="border-top: 1px solid #ccc; background: transparent;">
<div class="row" id="search-results">
{% regroup transaction by productID as ProductList %}
{% for productID in ProductList %}
///some code
</div>
{% endfor %}
</div>
VIEWS
#csrf_exempt
def search(request):
q = request.POST.get('search_by')
print(q)
product = Products.objects.all()
cart_product_form = CartAddProductForm()
transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID')
print(transaction)
context={
'products':product,
'transaction': transaction,
'cart_product_form':cart_product_form
}
html = render_to_string('main/home.html',context)
return JsonResponse(html,safe=False , content_type="application/json")
SCREENSHOT
Now in this screenshot u can see it showing me two banners and search bars and after the second the products from the search results are displayed. It's like it loads the whole page again within the page from the selector i have passed data too.
DOES ANYONE KNOWS HOW TO RESOLE THIS ISSUE OR WHERE I HAVE DONE WRONG.
because you render 'main/home.html' agin ! you just need send a json response with your context data and add it to web page with JS or create a new html template and render that with your context data and send that as response!

i try ajax partial refresh html,but it does't work

I'm trying to load the page locally with Ajax, but the following code doesn't work.
My idea is to pass the 'MSG' information of 'views' to Ajax and refresh the page locally without loading the entire page. If the input does not meet the requirements, the front end rejects the submission and gives a prompt message.
views.py
def login(request):
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
captcha = {'image_url': image_url, 'hashkey':hashkey}
if request.POST:
username = request.POST['username']
password = request.POST['password']
key = request.POST['hashkey']
capt = request.POST['captcha']
if username and password:
if captchautil.is_valid(capt, key):
user = auth.authenticate(username=username, password=password)
human = True
if user:
auth.login(request, user)
return redirect('/')
else:
msg = '用户名密码错误'
else:
msg = '请输入正确的验证码'
else:
msg = '请输入用户名与密码'
return render(request, 'login.html', locals())
return render(request, 'login.html', locals())
login.html
{% block content %}
<div id="login" class="login">
<form action="/login/" method="post" class="navbar-form">
{% csrf_token %}
<div id="input" class="form-group">
<input type="username" name="username" class="form-control" placeholder="请输入手机号或邮箱" id='user' title="请输入手机号或邮箱"><br><br>
<input type="password" name="password" class="form-control" placeholder="密码" id='pwd' title="请输入密码"><br><br>
<img src="{{image_url}}" alt='验证码' id='id_captcha'>
<span>看不清验证码?刷新</span>
<br>
<input id='captcha' placeholder="请输入验证码" name="captcha" class="form-control" type="text" data-toggle="tooltip" data-placement="bottom" title="请输入验证码">
<input value="{{hashkey}}" type="hidden" name="hashkey" id='hashkey'>
<br>
<button type="submit" class="btn btn-primary form-control" name="click" id='click'>登录</button>
</div>
<p style="margin-left: auto;" id="msg">{{ msg }}</p></div>
</form>
<div style="margin-left: 3%">
<span>
忘记密码了?
</span>
<span style="margin-left: 3%">免费注册</span>
</div>
</div>
{% endblock %}
{% block lastscript %}
<script type="text/javascript">
$(document).ready(function(){
//刷新验证码
$('#refresh_captcha').click(function(){
$.getJSON("/refresh_captcha/", function(result){
$('#id_captcha').attr('src', result['image_url']);
$('#hashkey').val(result['hashkey'])
});
});
});
$(function(){
$("#click").submit(function(){
var username = $("#user").val();
var password = $("#pwd").val();
var captcha = $("#captcha").val();
var key = $("#hashkey").val();
$(this).ajaxSubmit({
type:'post',
url: '/login/',
dataType: 'text',
data:{'username':username, "password":password, "capt":captcha, "key":key},
success:function(msg){
$("#msg").html(msg);
}
});
return false;
})
})
</script>
{% endblock %}
I didn't find out where the problem was. Please help me if you know
If you are fetching form dynamically and if you are trying to say like your javascript click functions are not working then you should try below.
$(document).on("click","#test-element",function() {
});
instead of normal click or submit an event
$("#click").submit(function(){ }); .
As per my knowledge if you are creating dynamic elements then the normal click event of jquery will not work. you need to write click event what added above.

Categories