Button Click search prefect Working Only Error For Search By Enter Key
Only For NoRecord Result Otherwise Working Correctly
if i search No record result it working once again even i try to correct record does not work hide the popup form & submitted successful mgs display.
This Is the Enter Key Function
$("#app-search").keyup(function (event) {
if (event.keyCode == 13) {
$(".search-pool").click();
}
});
<div class="modal-body">
<div class="row">
<div class="col-md-4 pull-right" id="search-view">
<div class="input-group">
#Html.TextBoxFor(m => m.search, new { id = "app-search", #class = "form-control"})
<a id="btn-clear-search2" class="fa fa-times-circle-o"></a>
<span class="input-group-btn">
<button class="search-pool btn btn-primary" type="button">
<span class="fa fa-search"></span>
</button>
</span>
</div>
</div>
</div>
This is the Button Click Function
$('.search-pool').on('click', function () {
$('#label-error').hide();
$.ajax({
url: '#Url.Action("PoolDetails")',
type: 'GET',
dataType: 'html',
data: { search: $('#app-search').val() }
})
.done(function (responce) {
$('#pool-details').html(responce);
$('#btn-clear-search2').show();
checkSelected();
FillSelected();
})
});
Related
I'm writing a code for the system administrator to be able to reset the users' passwords in their accounts in case they forget said password.
I'm currently having problems passing the target user's ID through Ajax to change said user's password, through debugging tool, the system returns an "undefined" response for "id:", although the "_token" and "password" fields were sent fine.
HTML code for the form
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
Javascript for generating the data-table where it shows the list of User accounts. On the side of the table, the admin can click a button to reset the password of said user.
$(document).ready(function() {
getRoles();
var accounts;
$('#account-management').addClass('active');
accounts = $("#table-accounts").DataTable({
ajax: {
url: "/users/get-all-users",
dataSrc: ''
},
responsive:true,
"order": [[ 7, "desc" ]],
columns: [
{ data: 'id'},
{ data: 'organization_name', defaultContent: 'n/a' },
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'email'},
{ data: 'student_number'},
{ data: 'role.name'},
{ data: 'created_at'},
{ data: null,
render: function ( data, type, row ) {
var html = "";
if (data.status == 1) {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
} else {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
}
html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";
return html;
}
},
],
columnDefs: [
{ className: "hidden", "targets": [0]},
{ "orderable": false, "targets": 7 }
]
});
Javascript for the random password generator and reset password
function resetPassword() {
$.ajax({
type: 'GET',
url: '/user/get-new-password',
processData: false,
success: function(data) {
$('#reset-password').val(data.password);
}
});
}
$(document).on('click', '.btn-reset-password', function() {
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
var id = $('.btn-confirmreset').attr('data-id');
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
Thank you for your help!
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
<input type="hidden" id="user_id" name="user_id" value=""> // initiate the hidden input here
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click', '.btn-reset-password', function() {
var user_id_value = $(this).attr('data-id'); // Get the user id from attr
$('#user_id').val(user_id_value); // Assign the user id to hidden field.
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
//var id = $('.btn-confirmreset').attr('data-id'); // Remove this, it won't work , because this button doesn't contain the data-id
var id = $('#user_id').val(user_id_value); // You can get the value from hidden field
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
</script>
Please refer the above code, You can pass the user id while modal pop up call and set that id to hidden value. then you can access that id from the hidden input. when you submit "form-reset-password" form.
Please look at comments on the above code
Maybe the attr() function is looking for native HTML attribute. So use the following snippet will help.
var id = $('.btn-confirmreset').data('id');
So I've got these cards, a user can click the delete button to remove a card. The card has an ID which deletes the card ID or community_id and user_id from the table. When the clicks the delete button, it sends an ajax delete request to the resource controller (delete method) which does delete the row from the database... sometimes.
It's very strange, sometimes it works, other times it returns a 405 (Method Not Allowed Exception).
Here's the code:
View:
#foreach($communities as $community)
<div class="col-md-3">
<div class="card communityCard">
<div class="loadingCard" loading>
<i class="loadingSpinner fas fa-circle-notch fa-spin"></i>
</div>
<div class="commandPanel">
<div class="commandPanelInterior">
#if($community->banned == 1)
#php($community->description = "This community has been removed for violating our terms of service.")
#else
<form class="form" action="/cad" method="GET">
#csrf
<input name="community_id" type="hidden" value="{{$community->id}}">
<button type="submit" class="sideMenuButton hvr-grow btn-primary"><i class="fas fa-door-open"></i></button>
</form>
#endif
#if($community->owner_id != Auth::user()->id)
<button id="deleteCommunity{{$community->id}}" value="{{$community->id}}" type="submit" class="deleteCommunityButton sideMenuButton hvr-grow btn-danger"><i class="fas fa-trash"></i></button>
#endif
</div>
</div>
<div class="card-header">
<img class="communityIcon" src="/images/communityIcons/{{$community->icon_path}}">
<span class="communityName">{{$community->name}}</span>
</div>
<div class="card-body">
<span class="communityDescription">{{$community->description}}</span>
</div>
#if($community->banned == 0)
<div class="card-footer">
<span class="badge badge-light"><i class="fas fa-users"></i> {{$community->user_count}}</span>
#php($communityBadges = $community->badge_types)
#foreach($communityBadges as $badgeType)
<span class="badge badge-primary" title="{{$badgeType->name}}">{!!$badgeType->badge_icon!!}</span>
#endforeach
</div>
#endif
</div>
</div>
#endforeach
Javascript:
// Remove User From Community Ajax
$('.deleteCommunityButton').click(function(event){
var clickedBtn = "#" + (event.target.id);
var community_id = $(event.target).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
cache: false,
url: '/communitymembers/'+community_id,
data: {
"id": community_id,
"_method": 'DELETE'
},
success: function(response) {
$(clickedBtn).parent().parent().parent().parent().remove();
}
});
});
Controller:
public function destroy($id)
{
$memberList = CommunityMemberList::where('user_id', Auth::user()->id)->where('community_id', $id)->first();
$memberList->delete();
return redirect('/home')->with('message', 'The community has been successfully removed from your account');;
}
Web.php File:
Route::get('/home', 'HomeController#index')->name('home');
Error (From Console):
"message": "The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.",
Thanks :)
I have a form in ASP.NET MVC5 that uses FormMethod.Post I have a Create button that submits the form, but how would I get it to work so that if you click Create then it disables the button. I have tried:
onclick="this.disabled = true"
But then the form is not submitted, hower when it is removed it allows you to add multiple records when clicking Create
This is my code for the form:
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript" type="text/javascript">
// cancel
$(document).on("click",
"#CancelForm",
function(e) {
var uri = '#Html.Raw(Url.Action("Index", "Membership"))';
window.location = uri;
e.preventDefault();
});
// submit
$(document).on("click", "#submitMembership", function(e) {
// Perform Ajax request to check if CAE/IPI Number is unique.
var caeipinumber = $('#addMembershipCAEIPINumber').val();
if (caeipinumber) {
$.ajax({
url: '#Url.Action("IsCAEIPINumberUnique", "Membership")',
data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
type: 'POST',
async: false,
cache: false,
success: function(result) {
if (result.toLowerCase() == "false") {
// Number is not unique and already exists, so display validation error to the user.
e.preventDefault();
$('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
return false;
}
return true;
},
error: function(xhr, status, error) {
}
});
}
});
</script>
}
#section additionalStyles {
}
#section modal {
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-1"></div>
<div id="createMembership" class="col-md-10 formContainer">
<div class="panel">
<div class="panel-heading">
<span class="panel-title">
<i class="glyphicon glyphicon-pencil"></i> Details of New Membership
</span>
</div>
#using (Html.BeginForm("AddMembership", "Membership", FormMethod.Post, new { id = "addMembershipForm", role = "form", #class = "theme-primary form-horizontal" }))
{
<fieldset>
<legend style="display: none">Add Membership Form</legend>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="panel-body p25 fill bt0 pbn">
<div class="form-group">
#Html.LabelFor(x => x.MembershipName, new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.TextBoxFor(x => x.MembershipName, new { id = "addMembershipName", #class = "form-control", placeholder = "Enter Membership Name..." })
#Html.ValidationMessageFor(x => x.MembershipName, string.Empty, new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.CAEIPINumber, new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.TextBoxFor(x => x.CAEIPINumber, new { id = "addMembershipCAEIPINumber", #class = "form-control", placeholder = "Enter CAE / IPI Number..." })
#Html.ValidationMessageFor(x => x.CAEIPINumber, string.Empty, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="text-center">
<input type="button" class="btn btn-primary" id="CancelForm" value="Cancel" />
<input id="submitMembership" type="submit" class="btn btn-primary" value="Create" />
</div>
</div>
</fieldset>
}
</div>
</div>
<div class="col-md-1"></div>
</article>
You should listen the form submit event, the submit input used trigger the form submit event and when the event is triggered you can disable the Button you clicked.
$("#form1").submit(function (){
$("#submitbtn").prop ("disabled",true);
$.ajax({requestprops,success:function(){
$("#submitbtn").prop ("disabled",false);
}});
});
This should work:
<script>
function setDisable(id) {
document.getElementById(id).disabled=true;
};
</script>
<input id="submitMembership" type="submit" onclick="setDisable(this.id)" class="btn btn-primary" value="Create" />
First, I would remove the binding on the click of the submit button and instead bind on the submit event.
Replace your submit button function with the following:
$("#addMembershipForm").submit(function (e) {
var submitButton = $(this).find(':input[type=submit]').prop('disabled', true); // Find and disable the submit button
// Perform Ajax request to check if CAE/IPI Number is unique.
var caeipinumber = $('#addMembershipCAEIPINumber').val();
if (caeipinumber) {
$.ajax({
url: '#Url.Action("IsCAEIPINumberUnique", "Membership")',
data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
type: 'POST',
async: false,
cache: false,
success: function(result) {
if (result.toLowerCase() == "false") {
// Number is not unique and already exists, so display validation error to the user.
submitButton.prop('disabled', false); // Enable submit button
e.preventDefault(); // Do not submit form
$('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
}
},
error: function(xhr, status, error) {
}
});
}
});
var submitButton = $(this).find(':input[type=submit]').prop('disabled', true);is used to find and then disable the button.
It will then do your unique check the same as you had in your original question. However, we will enable the submit button if it returns false so the user can re-submit.
could give me an example to extract data from input after submit button and send in same page to output h2?
This my input and submit button.
<div class="input-field col s6">
<i class="material-icons prefix">perm_identity</i>
<input placeholder="..." id="nameClient" name="nameClient" type="text" class="validate">
<label for="nameClient">Nome do cliente:</label>
</div>
<button class="btn waves-effect waves-light indigo" id="publish-sell" type="submit"><i class="material-icons left">attach_money</i>EFETUAR VENDA</button>
Was using this example to extract the typed data input to another input by means of a click.
$("#copyMapResearch").click(function () {
var endereco = $("#addressDeliveryClient").val();
$("#pac-input").val(endereco);
});
$("#copyToForm").click(function () {
var endereco = $("#pac-input").val();
$("#addressProvider").val(endereco);
});
The purpose of this code is to introduce it into a complete function of ajax.
$(document).ready(function () {
$('#draft-sell').click(function () {
var payload = {
nameClient: $('#nameClient').val(),
nameFantasySell: $('#nameFantasySell').val(),
addresOfClientSell: $('#addresOfClientSell').val(),
annotations: $('#annotations').val(),
neighborhood: $('#neighborhood').val(),
cep: $('#cep').val(),
phoneLandline: $('#phoneLandline').val(),
cellphone: $('#cellphone').val(),
autocompleteBusinessReseller: $('#autocompleteBusinessReseller').val(),
amountProduct: $('#amountProduct').val(),
productSoldSell: $('#productSoldSell').val(),
producFinalPrice: $('#producFinalPrice').val(),
registeredDaySell: $('#registeredDaySell').val()
};
$.ajax({
url: "/product/sell-draft",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(payload),
complete: function (data) {
// here is the place of the code that will extract the data from the data entered in the input and write in front-end
}
});
});
});
This my final html tag to display results.
<h2 class="left-align white-text person-name" id="nameClientReciept">
Thanks for help!!
If you want to use a form with submit button, then you need to use the submit action of the form, and prevent the default.
let form = document.querySelector('form');
let nameClinet = document.querySelector('#nameClient');
let output = document.querySelector('#output');
form.onsubmit = function(e){
e.preventDefault(); // stop the submit from actually happening
console.log("Client Name:", nameClient.value);
output.innerText = nameClient.value;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
<form>
<div class="input-field col s6">
<i class="material-icons prefix">perm_identity</i>
<input placeholder="..." id="nameClient" name="nameClient" type="text" class="validate">
<label for="nameClient">Nome do cliente:</label>
<h2 id="output"></h2>
</div>
<button
class="btn waves-effect waves-light indigo"
id="publish-sell"
type="submit">
<i class="material-icons left">attach_money</i>EFETUAR VENDA
</button>
</form>
I've setup a view which contains a search form:
<form>
<input type="hidden" id="product_id" value="{{$tour->id}}">
<div class="form-group col-md-4">
<label>Date:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="start" placeholder="Start Date">
</div>
</div>
<div class="form-group col-md-4">
<label>End:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="end" placeholder="End Date">
</div>
</div>
<div class="form-group col-md-4" id="dateprice-search">
<label></label>
<button type="submit" class="btn" id="btn-search" >
Search
</button>
</div>
The below is the ajax code to handle the request of the form:
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function() {
$.ajax({
type: 'post',
url: '/date-price',
data: {
'_token': $('input[name=_token]').val(),
'product_id': $("#product_id").val(),
'start': $("#start").val(),
'end': $("#end").val()
},
success: function(data) {
$('.shadow-z-1').show();
$('.shadow-z-1').append("<tr class='liquid-row><td>" + data.start + "</td><td>"+ data.end + "</td><td>" + data.end + "</td><td><a class='btn-m btn btn-m-success'>Available</a></td></tr>");
}
});
});
});
Route:
Route::post('/date-price','GetPublicController#datePrice')
->name('searchDate');
And finally method in controller to give the results:
public function datePrice(Request $request){
$start = $request->start;
$end = $request->end;
$dates = DatePrice::where('tour_id','=',$request->product_id)
->whereBetween('start', array($request->start, $request->end))
->whereBetween('end', array($request->start, $request->end))
->get();
return response()->json($dates);
}
At first the url looks like this before submitting the form http://localhost:8000/trips/popular/trekking/test and url becomes http://localhost:8000/trips/popular/trekking/test? after clicking the search button. Console section of inspect element shows no error in script. What mistake I had made over here ?
It mean your form submiting to same page due to type="submit"
1) change to type="button"
<button type="button" class="btn" id="btn-search" >
2) Here click event should be for button not to div so change the selector and add e.preventDefault(); in jquery to prevent the default submit .
$('#btn-search').on('click', '#btn-search', function() { e.preventDefault(); });
note :
1st : your action attribute missing so form will be submit same page .
2nd : your method attribute missing so it will take default GET method
You have given button type as submit, either remove it as
<button type="button" class="btn" id="btn-search" >
Search
</button>
or use the jquery preventDeafult() function to prevent the default behavior of submit button i.e form submit in your button click event as
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function(e) {
e.preventDefault();
//your ajax code
});
});