Form validations to display the duplicate data field to be highlighted - javascript

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

Related

I am getting Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

I am building an e-com site using the Django framework. to make it more efficient I am using javascript here and there. So the problem occurs at the checkout page and specifically if a user is logged in. On my site, a user can shop even if he is not logged in as a guest user. so if a guest user is going to the checkout page he can submit the process and make payment without running into any issues. But when a user is logged in the checkout page returns the error on load! even before writing anything into the form. I am attaching the checkout page code here for you guys to give it a good look. I have tried to debug it as well as run into the built-in code snippets here. It works fine without any issues
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-lg-6">
<div class="box-element" id="form-wrapper">
<form id="form">
<div id="user-info">
<div class="form-field">
<input required class="Form-control" type="text" name="name" placeholder="Name">
</div>
<div class="form-field">
<input required class="Form-control" type="email" name="email" placeholder="Email">
</div>
</div>
<div id="shipping-info">
<hr>
<p>shipping-info</p>
<hr>
<div class="form-field">
<input required class="Form-control" type="text" name="address" placeholder="Street">
</div>
<div class="form-field">
<input required class="Form-control" type="text" name="city" placeholder="City">
</div>
<div class="form-field">
<input required class="Form-control" type="text" name="state" placeholder="State">
</div>
<div class="form-field">
<input required class="Form-control" type="text" name="zipcode" placeholder="Zip Code">
</div>
</div>
<hr>
<div class="d-grid gap-2">
<input id="form-button" class="btn btn-outline-info" type="submit" value="Continue">
</div>
</form>
</div>
<br>
<div class="col-lg-6">
<div class="box-element hidden" id="payment-info">
<small>Paypal</small>
<button id="make-payment">Make Payment</button>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="box-element">
<a class="btn btn-outline-primary" href="{% url 'cart' %}">←Back to Cart</a>
<hr>
<h3>Order Summary</h3>
<hr>
{% for item in items %}
<div class="cart-row">
<div style="flex: 2;"><img class="row-image" src="{{item.product.imageURL}}"></div>
<div style="flex: 2;">{{item.product.name}}</div>
<div style="flex: 1;">${{item.product.price|floatformat:2}}</div>
<div style="flex: 1;">
<p><strong>x{{item.quantity}}</strong></p>
</div>
</div>
{% endfor %}
<h5>Items: {{order.get_cart_items}}</h5>
<h5>Total: ${{order.get_cart_total|floatformat:2}}</h5>
</div>
</div>
</div>
<script type="text/javascript">
var shipping = '{{order.shipping}}'
var total = '{{order.get_cart_total|floatformat:2}}'
if (shipping == 'False') {
document.getElementById('shipping-info').innerHTML = ''
}
var form = document.getElementById('form');
form.addEventListener('submit', function (e) {
e.preventDefault()
console.log('form submitted...')
document.getElementById('form-button').classList.add('hidden')
document.getElementById('payment-info').classList.remove('hidden')
})
document.getElementById('make-payment').addEventListener('click', function (e) {
submitFormData()
})
function submitFormData() {
console.log('Payment button clicked')
var userFormData = {
'name': null,
'email': null,
'total': total,
}
var shippingInfo = {
'address': null,
'city': null,
'state': null,
'zipcode': null,
}
if (shipping != 'False') {
shippingInfo.address = form.address.value
shippingInfo.city = form.city.value
shippingInfo.state = form.state.value
shippingInfo.zipcode = form.zipcode.value
}
if (user == 'AnonymousUser') {
userFormData.name = form.name.value
userFormData.email = form.email.value
}
var url = '/process_order/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({
'form': userFormData,
'shipping': shippingInfo
})
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
alert('Transaction Completed!');
cart = {}
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
window.location.href = "{% url 'store' %}"
})
}
</script>
{% endblock content %}

ajax submit multiple times

I have created an application in the php, I am using the bootstrap model to update user details using AJAX. Now there are two forms: first updates the user's details and adds comments to another user. When I try to submit a form to AJAX and I try to submit a form, it does not work, when i use ajaxComplete function then my form data has been submitted successfully, but at the time it submits the form multiple times at the same time.
$(document).ajaxComplete(function() {
$("#add-remarks").on('submit', (function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#add-remarks").attr("action"),
cache: false,
context: this,
data: $("#add-remarks").serialize(), //only input
success: function(data) {
var obj = JSON.parse(data);
$("#add-remarks")[0].reset();
if (obj['msg'] == 'isuccess') {
notification('insert');
} else {
notification('error');
}
}
});
}));
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="card-group-control card-group-control-right" id="accordion-model">
<div class="card">
<form method="post" name="update-user-details" id="update-user-details" action="">
<div class="row">
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">First Name</label>
<input type="text" class="form-control" placeholder="First Name" name="customer_name" id="customer_name">
</div>
</div>
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">Mobile</label>
<input type="text" class="form-control" placeholder="Mobile" name="mobile_number" id="mobile_number">
</div>
</div>
<button type="submit" class="btn bg-blue">Save Changes</button>
</div>
</form>
<form method="post" name="remarks" id="remarks" action="">
<div class="row">
<div class="col-md-4">
<div class="form-group form-group-float">
<label class="d-block font-weight-semibold">Remarks</label>
<input type="text" class="form-control" placeholder="Remarks" name="remarks" id="remarks">
</div>
</div>
<button type="submit" class="btn bg-blue">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Move this piece of code outside of your ajaxComplete() function. You are probably somehow triggering the ajaxComplete function multiple times, causing multiple event listeners for the form submit.
$("#add-remarks").on('submit', (function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#add-remarks").attr("action"),
cache: false,
context: this,
data: $("#add-remarks").serialize(), //only input
success: function(data) {
var obj = JSON.parse(data);
$("#add-remarks")[0].reset();
if (obj['msg'] == 'isuccess') {
notification('insert');
} else {
notification('error');
}
}
});
}));

AJAX POST data not being sent

On button click, i want to post the contents of the email text box. When i click the login button nothing happens.
My File dir:
Model/ <-- configuration.php is inside Model dir.
View/
Controller/
index.php <-- calls the header, body, and footer php classes that are in the view dir
<!-- Modal body -->
<div class="modal-body" style="padding:40px 50px;">
<form>
<div class="form-group">
<label for="usrname"><span class="glyphicon glyphicon-user"></span> Username</label>
<input type="text" class="form-control" name="email" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="psw"><span class="glyphicon glyphicon-eye-open"></span> Password</label>
<input type="text" class="form-control" id="password" placeholder="Enter password">
</div>
<div class="checkbox">
<label><input type="checkbox" value="" checked>Remember me</label>
</div>
<button type="button" name="loginButton" id="loginButton" name="loginButton" class="btn btn-success btn-block">Login</button>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<p>Not a member? Sign Up</p>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#loginButton").click(function() {
$.ajax({
type: "POST",
url: "Model/configuration.php?action=login",
data: "email=" + $("#email").val(),
success: function (result) {
alert("result");
}
})
})
})
</script>
PHP file
<?php
if($_GET['action'] == "login") {
print_r($_POST);
}
?>
The problem seems to be that your if condition had an extra parentheses.
Try this:
<?php
if($_GET['action'] == "login") {
print_r($_POST);
}
?>
$("#loginButton").click(function() {
$.ajax({
type: "POST",
url: "Model/configuration.php?action=login",
data: {email:$("#email").val()},
success: function (result) {
alert("result");
}
})
})
You should serialize your form and pass to data.
data: $("#FormId").serialize()
See also https://api.jquery.com/serialize/

Laravel 5.2 Modal popup for forget Password displaying 500 internal server Error while running ajax function

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.

How I change properties of form inputs to disable = "false" after making it "true"

I have a form that submits via Ajax. After the user sends the form, the text changes displaying that the data was sent successfully and then shows the form filled out. I want to display the form but I don't want them to re-submit the form so I want to disable the inputs as well as the submit button. I have 3 operations, add, update and view. After making the form inputs in view disabled, is stay disabled in add.
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Report</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-2">
<label for="ex1">Square</label>
<input type="text" name="square" id="square" class="form-control">
</div>
<div class="col-xs-2">
<label for="ex1"> Number </label>
<input type="text" name="report_number" id="report_number" class="form-control">
</div>
<div class="col-xs-4">
<label>Report Date </label>
<input type="date" name="report_date" id="report_date" class="form-control" />
</div >
</div>
</br>
<div class="row">
<div class="col-xs-12">
<label>Notes </label>
<textarea rows="15" cols="80" type="text" name="notes" id="notes" class="form-control" > </textarea>
</div >
</div>
<br />
<label>Select Image</label>
<input type="file" name="user_image" id="user_image" />
<span id="user_uploaded_image"></span>
</div>
<div class="modal-footer">
<input type="hidden" name="report_id" id="report_id" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
<script>
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var addedSquare = $('#square').val();
var addedNumber = $('#report_number').val();
var addedDate = $('#report_date').val();
var extension = $('#user_image').val().split('.').pop().toLowerCase();
if(extension != '')
{
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
$('#user_image').val('');
return false;
}
}
if(addedSquare != '' && addedNumber != '')
{
$.ajax({
url:"insert.php",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Both Fields are Required");
}
});
$(document).on('click', '.update', function(){
var report_id = $(this).attr("id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{report_id:report_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#square').val(data.square).prop( "disabled", false );
$('#report_number').val(data.report_number).prop( "disabled", false );
$('#report_date').val(data.report_date).prop( "disabled", false );
$('.modal-title').text("Edit Report");
$('#report_id').val(report_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
$('#operation').val("Edit");
}
})
});
$(document).on('click', '.view', function(){
var report_id = $(this).attr("id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{report_id:report_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#square').val(data.square).prop( "disabled", true );
$('#report_number').val(data.report_number).prop( "disabled", true );
$('#report_date').val(data.report_date).prop( "disabled", true );
$('.modal-title').text("View Report");
$('#report_id').val(report_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("View");
$('#operation').val("View");
}
})
});
</script>
how could I make the inputs enabled again in add ?
just .prop( "disabled" , false );

Categories

Resources