Submit form without redirection with ajax - javascript

i'm trying to make some things with ajax and it doesn't work.
I have a view with some divs where i will be all the functionality of the page.
The view's code is this:
#extends('cms.public.layouts.default')
#section('content')
<div class="col-md-10">
<h3 style="letter-spacing:40px;text-align:center;color:f15d5e;">PROYECTOS</h3>
</div>
<div id="listall"> <!-- DIV TO LIST ALL THE PROJECTS START HERE -->
<div class="col-md-2" style="padding:20px;">
<button type="button" id="buttoncreate" class="btn btn-danger">Crear Proyecto</button>
</div>
<table class="table">
<thead style="color:white">
<tr>
<th>Id</th>
<th>Slug</th>
<th>Order</th>
<th>Public</th>
<th>Path header</th>
<th>Path home</th>
<th>Fecha creación</th>
<th>Fecha ultima actualización</th>
<th><span class="glyphicon glyphicon-cog"></span></th>
</tr>
</thead>
<tbody style="color:white">
#foreach ($projects as $key => $project)
<tr>
<th>{{$project->id}}</th>
<td>{{$project->slug}}</td>
<td>{{$project->order}}</td>
<td>{{$project->public}}</td>
<td>{{$project->pathheader}}</td>
<td>{{$project->pathhome}}</td>
<td>{{ date('M j, Y', strtotime($project->created_at))}}</td>
<td>{{ date('M j, Y', strtotime($project->updated_at))}}</td>
<td>View Edit
#endforeach
</tr>
</tbody>
</table>
<br><br>
</div> <!-- DIV TO LIST ALL THE PROJECTS END HERE -->
<div id="form1" style="display:none;" class="col-md-8"> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 START HERE-->
<div>
<h3>Crear nuevo proyecto</h3>
</div>
<div id="formcreateproject">
<form method="POST" action="{{ route('admin.projects.store') }}" enctype="multipart/form-data" id="myForm" name="myForm">
<div class="form-group">
<label name="title">Slug:</label>
<input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">
<label name="order">Order:</label>
<input type="number" id="order" name="order" class="form-control form-control-sm">
<label name="public">Public:</label>
<input type="number" id="public" name="public" class="form-control form-control-sm">
<label name="body">Header</label>
<input type="file" name="pathheader" id="pathheader" class="form-control-file" aria-describedby="fileHelp"><br>
<label name="body">Home</label>
<input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp"><br>
<input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">
<input type="hidden" name="_token" value="{{ Session::token() }}">
<br><br><br>
</div>
</form>
</div>
</div> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 END HERE-->
<div id="form2" style="display:none;" class="col-md-6">
<div class="col-md-">
<h3>Crear nuevo proyecto</h3>
</div>
<form method="POST" action="{{ route('admin.projects.store') }}" enctype="multipart/form-data">
<div class="form-group">
<label name="title">Slug:</label>
<input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">
<label name="order">Order:</label>
<input type="number" id="order" name="order" class="form-control form-control-sm">
<label name="public">Public:</label>
<input type="number" id="public" name="public" class="form-control form-control-sm">
<label name="body">Header</label>
<input type="file" name="pathheader" id="pathheader" class="form-control-file" aria-describedby="fileHelp"><br>
<label name="body">Home</label>
<input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp"><br>
<input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">
<input type="hidden" name="_token" value="{{ Session::token() }}">
<br><br><br>
</div>
</form>
</div>
</div>
#stop
And the javascript function is this:
//Javascript view /projects/menu.blade.php
$(document).ready(function(){
$("#buttoncreate").click(function(){
$("#listall").hide();
$("#form1").fadeIn(1000);
$("#createprojectsubmit").submit(function(e){
e.preventDefault();
$.ajax({
url:'/admin/projects/postUpload',
type:'post',
data:$('#myForm'),
success: function(){
$("#form1").fadeOut(1000);
$("#form2").fadeIn(1000);
}
});
});
});
});
The function of hide the first div and fade in the second works, and it submit and create the new project. But url change and show me a white page.
My first thing to do is fadeOut the form1 and fadein the second form. It will be great, if when fadeOut the form1, in her space appears a tick/check.
Thanks a lot, any help will be appreciated.

you are calling submit event on button which does not belong to button. It belongs to form. So call the click event on button and use preventDefault() to stop the form to be submitted as
$("#createprojectsubmit").submit(function(e){
e.preventDefault();
//your further code goes here
}
use like this
$("#createprojectsubmit").click(function(e){
e.preventDefault();
//your further code goes here
}
You can also trigger the submit event on your form as
$("#myForm").submit(function(e){
e.preventDefault();
//your further code goes here
}

This is because you are mixing 2 ways to handle the submission of your form: the click on the button and the form submission itself.
The function submit as you call in your script is making the binding of the submit event when the button is clicked.
Here is how to bind your code only on the submit event of your form:
$(document).ready(function(){
$("#buttoncreate").click(function(){
$("#listall").hide();
$("#form1").fadeIn(1000);
$("#myForm").submit();
});
$("#myForm").submit(function(e){
e.preventDefault();
$.ajax({
url:'/admin/projects/postUpload',
type:'post',
data:$('#myForm'),
success: function(){
$("#form1").fadeOut(1000);
$("#form2").fadeIn(1000);
}
});
});
});
EDIT: Edited answer to take in account the click on the button.
At first, we bind the click event on the button to handle animations and trigger the form submission by calling submit function on the form.
Then, we bind the submit event on the form to handle the ajax call in replacement of the classic postback form submission.

Related

Laravel insert dynamic input values with radio button

I am a beginner at Laravel, I want to insert a more dynamic address field to the database and I want to select one primary address using the radio button. I can able to add more address fields, but, I am unable to select one primary address because it's selecting all radio button values. I have given below using my code
This is My Blade File
<div>
<form action="{{ route('register.post') }}" enctype="multipart/form-data" accept-charset="utf-8" method="POST" >
#csrf
<div class="form-group row">
<label for="address" class="col-md-4 col-form-label text-md-left">Address</label>
<div>
<table id="dynamicAddRemove">
<tr>
<td><button type="button" name="add" id="add-btn" class="btn btn-success">Add More Details</button></td>
</tr>
<tr>
<td>
</td>
<tr>
</table>
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Save
</button>
</div>
</form>
<div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
var i = 0;
$("#add-btn").click(function(){
//alert("I am an alert box!");
++i;
$("#dynamicAddRemove").append('<tr><td><input type="text" name="moreFields['+i+'][house_no]" placeholder="House No" class="form-control" /></td><td><input type="text" name="moreFields['+i+'][street_name]" placeholder="Street Name" class="form-control" /></td><td><input type="text" name="moreFields['+i+'][area]" placeholder="Area" class="form-control" /></td><td><input type="text" name="moreFields['+i+'][pincode]" placeholder="Pincode" class="form-control" /></td><td style="padding-left:50px;"><input type="radio" class="form-check-input" name="moreFields['+i+'][primary_address]" value="'+i+'"></td><td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
});
$(document).on('click', '.remove-tr', function(){
$(this).parents('tr').remove();
});
</script>
This is My Controller File
public function postRegistration(Request $request)
{
$id = DB::getPdo()->lastInsertId();
foreach ($request->moreFields as $key => $value) {
Address::create([
'user_id'=>$id,
'house_no'=>$value['house_no'],
'street_name'=>$value['street_name'],
'area'=>$value['area'],
'pincode'=>$value['pincode'],
'primary_address'=>$value['primary_address'],
]);
}
You dont need to make different name radio buttons use same name for all radio buttons so that user can not select other radio button after selecting one
<input type="radio" class="form-check-input" name="moreFields" value="'+i+'">
Laravel 8 Dynamic Radio Button Edit Page
This worked for me
#foreach($lease_stores as $lease_store)
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="lease_store_id" id="inlineRadio1" #if($general_details->lease_store_id==$lease_store->id) checked value="{{$lease_store->id}}"
#else value="{{$lease_store->id}}"
#endif>
<label class="form-check-label" for="inlineRadio2">{{$lease_store->name}} </label>
</div>
#endforeach
Controller master fetch
$lease_stores=Leasestore::all();

In jsp page Confirm only appear on first row form button click. On second row form submit it does not appear and my ajax call is executed

I have developed spring boot web application, on front end I have JSP pages.
I am displaying list of user in table and there are corresponding action(form for each action) like update, reset, delete etc in my each row. On Delete action I am first displaying confirm message. If user press Ok I am making Ajax get call to Controller which delete user from database and return status 0 or 1. I have notice that on first record it show confirm and on OK it send the call and proper response is return back. When I click on second record delete button it does not show confirm message and submit the form which return error 405 Get Method not supported. I have also observe no other record is work as per behavior.
My JSP code is as below
I have tried different way to show confirm message like onclick I have tried to execute it but same is result.
I have remove all other js/css libraries and only j query on my page but it produce same output. I have also tried to create a simple page and simulate same behavior it also show same.
<div id="disabledContent" class="container border rounded bg-light"
style="margin-top: 5px; margin-bottom: 10px;">
<form method="post" action="/createUserDetails">
<button type="submit" value="Add User"
class="btn btn-success btn-lg">+</button>
</form>
<table class="table table-light">
<thead class="thead-light">
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th colspan="6" scope="col">Actions</th>
</tr>
</thead>
<tbody>
<c:forEach items="${userList}" var="item">
<tr>
<td>${item.firstName}</td>
<td>${item.lastName}</td>
<td>
<form method="post" action="/assignUserLicense">
<input type="hidden" name="userId" value="${item.id}">
<input type="hidden" name="customerUniqueId"
value="${customerUniqueId}">
<button type="submit" value="Assign License"
class="btn btn-warning">Assign License</button>
</form>
</td>
<td>
<form method="post" action="/unassignUserLicense">
<input type="hidden" name="userId" value="${item.id}">
<input type="hidden" name="customerUniqueId"
value="${customerUniqueId}">
<button type="submit" value="UnAssign License"
class="btn btn-warning">Unassign License</button>
</form>
</td>
<td>
<form method="post" action="/modifyUserDetails"
id="modifyUserDetailsForm">
<input type="hidden" name="userId" id="userId"
value="${item.id}"> <input type="hidden"
name="customerUniqueId" id="customerUniqueId"
value="${customerUniqueId}"> <input type="hidden"
name="displayName" id="displayName"
value="${item.displayName}"> <input type="hidden"
name="userPrincipalName" id="userPrincipalName"
value="${item.userPrincipalName}"> <input
type="hidden" name="firstName" id="firstName"
value="${item.firstName}"> <input type="hidden"
name="lastName" id="lastName" value="${item.lastName}">
<button type="submit" value="Modify User"
class="btn btn-warning">Modify User</button>
</form>
</td>
<td>
<form method="post" action="/resetUserUserDetails">
<input type="hidden" name="userId" value="${item.id}">
<input type="hidden" name="customerUniqueId"
value="${customerUniqueId}">
<button type="submit" value="Get User"
class="btn btn-warning">Reset Password</button>
</form>
</td>
<td>
<form id="myDeleteFrom">
<input type="hidden" name="userId" value="${item.id}">
<input type="hidden" name="customerUniqueId"
value="${customerUniqueId}">
<button type="submit" value="Get User"
class="btn btn-warning">Delete User</button>
</form>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<div></div>
</div>
my javascript code
$(document)
.ready(
function() {
$("#myDeleteFrom")
.submit(
function() {
var confirmResponse = confirm("Are you sure you want to delete this user");
if (confirmResponse) {
//Ajax get call
} else {
return false;
}
});
});
I am expecting it should work on any row delete form submit button click.

jQuery and Ajax not working $.on

I want when I click on Clear button, all fields in the form to be cleared.
The ajax request is only replacing the form from the tag <form> to </form>.
When it is clicked on Clear button, the console output is working.
I have the following form:
<div class="col-lg-5 formWrapper">
<form data-th-fragment="layoutForm" id="layoutForm" class="form-horizontal" data-th-object="${layout}" data-th-action="#{/layouts/add}" method="POST" role="form">
<div class="row">
<input id="objectId" data-th-field="*{id}" type="hidden">
<input data-th-if="*{filePath} !=null" data-th-field="*{filePath}" type="text" hidden="hidden">
<label for="layoutName" >Layout name</label>
<input data-th-field="*{name}" id="layoutName" class="form-control" type="text">
</div>
<div class="row">
<div class="col-lg-4">
<label for="status">Status</label>
<select id="status" data-th-field="*{status}"class="form-control">
<option value="1">Active</option>
<option value="0">Blocked</option>
</select>
</div>
<div class="col-lg-6">
<label for="exhibitorName">Exhibitor</label>
<select data-th-field="*{exhibitor}" name="exhibitorName" id="exhibitorName" class="form-control">
<option data-th-each="exhibitor : ${exhibitorsList}" data-th-value="${exhibitor.id}" data-th-text="${exhibitor.exhibitorName}"></option>
</select>
</div>
</div>
<div class="row">
<div class=" col-lg-3">
<input id="clearForm" type="reset" value="Clear" class="form-control btn-lg btn btn-default">
</div>
<div class=" col-lg-3 col-lg-offset-4">
<input id="submitButton" type="submit" value="Add" class="form-control btn-lg btn btn-success">
</div>
</div>
</form>
</div>
The form looks something like this:
The jQuery is as follow:
$(document).ready(function() {
$('.formWrapper').on('click','#clearForm', function (event) {
$(this).closest('form').find("input[type=text]").val("");
console.log("ASD");
});
});
The snipped is how I replace the form:
$("body").on('click','#editLayout', function(event){
var ajax = $.ajax({
url : "/layouts/edit/" + $(this).data("id"),
dataType : "html",
success: function (data) {
$("#layoutForm").replaceWith(data);
$('#submitButton').val('Edit').addClass('btn-warning').removeClass('btn-success');
}
});
});
Try this,
$('#form_id').trigger("reset");
or
$('#form_id')[0].reset();
A reset button doesn't need any script at all (or name or id):
<input type="reset">
and you're done. But if you really must use a script, note that every form control has a form property that references the form it's in, so you could do:
<input type="button" onclick="this.form.reset();">
But a reset button is a far better choice.
Try to use $('#clearForm').reset(); or $('#clearForm')[0].reset();

Symfony search form without reload page

I use symnfony and have form for search entity by parameters, but when submit form my page reload, I don't know how realized search form when fill out fields and under form I have result without reload page, like write in filed some word and in this time under update block with result
this my form with action, action wait get parameters and rendering in this view with form and result
<div class="filters" id="filter_form">
<form action="{{ path('outbound_invoices') }}" method="get">
<div class="choice-group" role="group" data-toggle="buttons">
<label class="btn active">
<input type="radio" name="status" value={{ status_draft }} checked="checked">{{ status_draft|trans }}
</label>
<label class="btn">
<input type="radio" name="status" value={{ status_sent }}>{{ status_sent|trans }}
</label>
<label class="btn">
<input type="radio" name="status" value={{ status_paid }}>{{ status_paid|trans }}
</label>
</div>
<div class="choice-group" role="group" data-toggle="buttons">
<label class="btn active">
<input type="radio" name="type" value="all" checked="checked">all
</label>
<label class="btn">
<input type="radio" name="type" value="contract">contract
</label>
<label class="btn">
<input type="radio" name="type" value="other">other
</label>
</div>
<input name="search" id="filter-employees" placeholder="{{ 'search'|trans }}" class="form-control">
<p>from Date: <input type="text" name="from_date" id="from_datepicker" dataformatas="dd-mm-yyyy"></p>
<p>to Date: <input type="text" name="to_date" id="to_datepicker" dataformatas="dd-mm-yyyy"></p>
<input type="submit" value="Submit">
</form>
</div>
// block result
<table class="table">
<thead>
<tr>
<th>
{% trans %}invoice_number_short{% endtrans %}
</th>
</tr>
</thead>
<tbody>
{# #var outboundInvoice \AppBundle\Entity\OutboundInvoice#}
{% for outboundInvoice in outboundInvoices %}
<tr class="clickable" data-href="{{ path('outbound_invoices_show', {'id': outboundInvoice.id}) }}">
<td>
{{ outboundInvoice.invoiceNumber }}
</td>
{% endfor %}
</tr>
</tbody>
</table>
in action I just create query builder for find entities and rendering in template. How it's realized with ajax without reload and search in real time ?
Here is an example to post your form via ajax with jQuery:
var form = $('#my-form');
$.post(
form.prop('action'), //action url
form.serializeArray(), //serialized form data
function(result){ //callback
console.log(result);
}
);
Use the AJAX as you'd normally do:
//add jquery here
$('#filter-employees').click(function(e){
e.preventDefault();
$.ajax({
action:"/invoices"
//...
}).done(function(resp));
});
Then in the controller action, you need to verify if the request is a XMLHttpRequest one, and create the functionality accordingly.
/**
* #Route("/invoices", name="outbound_invoices")
*/
public function processAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
//do work
}
return $this->redirectToRoute('whatever');
}
OBS: I would recommend you to use Angular for this type of things.

jQuery onclick not working properly with validation

i have used onClick method to confirm update for my Bootstrap form. but when i click create button it popup the confirm message without going to validation.
wht i want is if user click create button first it will show the required field validation and after all success only confirm popup should display..
please advice
<form data-toggle="validator" class="form-horizontal" role="form" method="POST"
action="{{ action('Admin\UserController#store') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<div class="col-md-12">
<label class="control-label popup-label">Full Name</label>
<input required type="text" class="form-control" name="full_name"
value="{{ old('full_name') }}">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="control-label popup-label">Username</label>
<input required type="text" class="form-control" name="username"
value="{{ old('username') }}">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="control-label popup-label">Password</label>
<input pattern=".{5,10}" required title="5 to 10 characters"
type="password" class="form-control"
name="password" value="{{ old('password') }}">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" onclick="return confirm('Do you want to create this admin?');">Create</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
Your create button is of submit type, its default action is to submit the form. Make it of type button and use the below function:
<button type="button" class="btn btn-primary" onclick="createBtn();">Create</button>
<script>
function createBtn(){
if(confirm('Do you want to create this admin?')){
document.getElementsByTagName("form")[0].submit();
}
}
</script>
I presume you are using the Bootstrap Validator plugin: http://1000hz.github.io/bootstrap-validator/
This plugin provides a way to know when the form has been validated by providing you with an event you can listen on.
('#form').validator().on('validate.bs.validator', function (e) {
console.log('validated.');
// perform confirm and other post-validation tasks...
confirm('Do you want to create this admin?');
}

Categories