laravel ajax form won't execute submit button - javascript

Basically my form adds to blade by help of javascript and then i can fulfill data and hit the save button.
The issue is save button doesn't work.
Here is screen record of the process and error you can watch
Code
This function will add new row and form to view where you see in video i filled input and hit save button
var textFieldsCount = 0;
function addTextField(){
textFieldsCount++;
var textfieldhelper = '';
var my_row = $('<div class="row mt-20" id="textField-' + textFieldsCount + '">');
var my_html = '{{Form::open()}}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><div class="col-md-4">{{ Form::label('customsubspecifications', 'Specifications') }}<select class="form-control" id="specification_id" name="specification_id"><option value="">Select</option>'+specifications+'</select></div>';
my_html += '<div class="col-md-4">{{ Form::label('text_dec', 'Your Custom Input') }}'+
'<input class="text_dec form-control" onkeypress="myFunction()" type="text" name="text_dec[]" id="'+ textFieldsCount.toString() +'">'+
'</div>';
my_html += '<div class="col-md-4">{{ Form::label('', 'Actions') }}<br><button type="button" class="btn btn-danger btn-xs" onclick="removeTextField(\'textField-' + textFieldsCount.toString() + '\')">Remove</button><button type="button" class="btn btn-info btn-xs" onclick="addTextField();">Add New</button><button type="button" id="custmodalsave" class="myButton custmodalsave btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
$('#fields').append(my_row);
}
here is where thing happen and I actually try to send data to back-end
$("#custmodalsave").click(function(e){
e.preventDefault();
$.ajax({
type: "post",
url: "{{ url('admin/addnewcustomsubspecifications') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'specification_id': $('#specification_id').val(),
'text_dec': $('.text_dec').val(),
'longtext_dec': $('.longtext_dec').val(),
},
success: function (data) {
$('#custspacmsg').append('<span class="text-success">Custom Specification added successfully in your product!</span>');
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
});
just to be clear I attached output form of my first ajax code so you
can see how things are printed
<div class="row mt-20" id="textField-1">
<form method="POST" action="http://newsite.pp/admin/products/15" accept-charset="UTF-8">
<input name="_token" value="DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16" type="hidden">
<input name="product_id" id="product_id" value="15" type="hidden">
<div class="col-md-4">
<label for="customsubspecifications">Specifications</label>
<select class="form-control" id="specification_id" name="specification_id">
<option value="">Select</option>
<option value="1">CPU</option>
<option value="2">ram</option>
<option value="3">LCD</option>
<option value="4">Mouse</option>
<option value="5">Graphic</option>
<option value="6">Keyboard</option>
</select>
</div>
<div class="col-md-4">
<label for="text_dec">Your Custom Input</label>
<input class="text_dec form-control" onkeypress="myFunction()" name="text_dec[]" id="1" type="text">
</div>
<div class="col-md-4">
<label for="">Actions</label>
<br>
<button type="button" class="btn btn-danger btn-xs" onclick="removeTextField('textField-1')">Remove</button>
<button type="button" class="btn btn-info btn-xs" onclick="addTextField();">Add New</button>
<button type="button" id="custmodalsave" class="myButton custmodalsave btn btn-xs btn-success" style="display: inline-block;">Save</button>
</div>
</form>
</div>
PS: I should add that I have this function working on bootstrap modal
but i wanted to change modal the way you see in video (print by click in blade)
Back-End is working perfectly since I can save data by this Ajax code with modal. Whatever the issue is, is coming from here.

You're defining your click function as
$("#custmodalsave").click(function(e){
But, when this function is defined, $("#custmodalsave") is not available in your DOM as you're appending it:
$('#fields').append(my_row); // my_row contains `[...] id="custmodalsave"`
To fix this, simply use event delegation:
$("body").on("click", "#custmodalsave", function(e){ ... });
For more info on event delegation, please check out the jQuery reference:
http://api.jquery.com/on/

Related

Dynamic Form Post Method on html with array in ASP.NET MVC

I'm building a view that with a modal opens a barcode scanner and every time that I scan a barcode I call a function startScanning() dynamically I'm building inputs inside a form.
When I click submit button I would like to send an array with all the barcodes the problem is that I'm not sure how to call the controller or what I should add in the Action in order to send the array or I if I need to change something in the elements.
My Modal Footer View
<div class="modal-footer">
(What I should write here to pass the array in the action)?
<form action="~/PurchaseOrder/ReceivedFromBarCode" method="post">
<label for="fname">Barcode:</label>
<div id="scanned-result" style="margin-bottom: 25px;"></div>
<div class="box-footer">
<button type="submit" class="btn btn-primary pull-right">
<i class="fa fa-paper-plane">
</i> Submit</button>
</div>
</form>
</div>
Javascript Function
function startScanning(facingMode) {
console.log(facingMode)
var results = document.getElementById('scanned-result');
var lastMessage;
var codesFound = 0;
function onScanSuccess(qrCodeMessage) {
if (lastMessage !== qrCodeMessage) {
lastMessage = qrCodeMessage;
++codesFound;
results.innerHTML += '<br><input placeholder="' + qrCodeMessage +']" name="barcode[' + codesFound + ']" type="text" id="barcode' + codesFound + '" value="' + qrCodeMessage + '" >';
}
}
Controller
[HttpPost]
public async Task<ActionResult> ReceivedFromBarCode(string[] barcode)
{
try
{
return RedirectToAction($"Details");
}
catch (VTHIS.CommunicationException cex)
{
throw cex;
}
}
Elements Console
<div class="modal-footer">
<form action="/secure/specialapp/admin/PurchaseOrder/ReceivedFromBarCode" method="post">
<label for="fname">Barcode:</label>
<div id="scanned-result" style="margin-bottom: 25px;">
<br>
<input placeholder="https://www.kwch.com" name="barcode[1]" type="text" id="barcode1" value="https://="www.kwch.com"><br>
<input placeholder="http://www.qrstuff.com" name="barcode[2]" type="text" id="barcode2" value=" http://www.qrstuff.com">
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary pull-right"><i class="fa fa-paper-plane"></i> Submit</button>
</div>
</form>
</div>

Submit form without form id

I need to submit form using through Ajax call but I'm having trouble selecting the form. I don't want to use form ID because I'm having multiple forms and I need to setup one code for all
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
//$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card" >
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>
No need to add form submit code because you are preventing submit, so when will you click just fetch data from the form and call your AJAX service.
I added one console log where you can see your form data.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
var formData = $(form).serialize();
console.log(formData);
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>
This will help you to reduce duplicating the code..
$(document).ready(function() {
$('form').on('submit', function(e){
e.preventDefault();
Var action = $(this).action;
Var method = $(this).method;
Var data = $(this).serialize();
// perform ajax operation here with data, action and method
});
});
Happy coding :)
Your code is creating submit handler everytime the button is clicked, all you want is to send ajax call onclick, so just do that part.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
// below code is creating submit handler everytime the button is clicked
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
});
});
Also .find returns jQuery object, no need to make it Jquery object again, simple form will do instead of $(form).. rather declare like var $form = $(this).closest(".card-body").find("form")
Something like below, try
$(".pay").on("click",function(){
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});
function submitForm(formData){
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
}
I've created below sample to refer
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
console.log(formData)
submitForm(formData);
});
function submitForm(formData) {
alert("submitting form with " + formData)
$.ajax({
type: 'POST',
url: "php/pay.php",
data: formData
})
.done(function(response) {})
}
});
.card {
width: 50%;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</div>
</div>
<div class="card">
<div class="card-header">
<h1>YYY</h1>
</div>
<div class="card-body">
<form>
<input name="user2" value="mat2" type="hidden">
<input name="id2" value="122" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay2</button>
<button class="btn btn-danger decline" value="decline">decline2</button>
</div>
</div>
Erm.. Why not just put the two buttons inside the form, to avoid any confusion or off-chance that the script might trigger another one of the "multiple forms" and refer to the nameless form through the parent element instead, like?
html:
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</form>
script:
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).parent();
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});

AJAX I must double click to submit second textarea! (Laravel)

$(document).ready(function (){
$('#myForm').submit(function (e) {
e.preventDefault(); //Do not submit the form
var dataflow=$(this).serialize(); //Get the inputs value
$.post('{{route('homepage.update')}}', dataflow, function (data){ //post.create is the route name
//The request is done, do something with the server response
});
});
});
I use this to save form without refresh
Here is my route
Route::post('/homepage/update', 'AdminController#Update')->name('homepage.update');
And my html
{{ csrf_field() }}
<div class="form-group">
<label for="title"><b class="fa fa-pencil"></b> Title</label>
<input id="title" class="form-control" value="{{ $article->title }}" name="title">
<br />
<label for="content"><b class="fa fa-home"></b> Desc</label>
<div class="box-body pad">
<textarea id="content" name="content" rows="10" cols="80">
{{ $article->content }}
</textarea>
</div>
</div>
<center>
<div class="form-group">
<button type="submit" class="btn btn-success btn-sm"><b class="fa fa-save"></b> Submit</button>
</form>
My function who update ajax data
public function HomePage(Request $r) {
$article = Article::find(1);
$article->title = $r->input('title');
$article->content = $r->input('content');
$article->homepage = 1;
$article->save();
}
The problem is i must click twice button to save two forms when i click one it submit only title! Please help how to fix that

How to disable a button if certain condition happened

How to disable a button if certain condition happened. Example my order_status is 'Accepted' then the button for 'Accept' will be disabled. How can I disabled it using javascript?
Below is my code, but it didn't quiet working and I dont know why.
<div class="form-group">
<label for="order_status" class="col-sm-2 control-label" style="width:20%;">Order Status</label>
<input type="text" class="form-control" name="order_status" id="t_order_status" style="width:80%;" placeholder="" value="" required="required" readonly>
</div>
<button type="button" input style="background-color:#4CAF50;color:white;border-color:#000000;" name="submitDelivered" id="submitDelivered" class="btn btn-success" data-toggle="modal" data-target="#myDeliverModal" onclick="deliver('<?= $_POST['order_id'] ?>')" > Delivered </button>
<button type="button" input style="background-color:#0000FF;color:white;border-color:#000000;" name="submitAccept" id="submitAccept" class="btn btn-success" data-toggle="modal" data-target="#myAcceptModal" onclick="accept('<?= $_POST['order_id'] ?>')" > Accept </button>
<button type="button" style="background-color:#FFFF00;color:black;border-color:#000000;" class="btn btn-success" data-toggle="modal" data-target="#myDropdown" onclick="send('<?= $_POST['order_id'] ?>')"> Send </button>
<button type="button" input style="background-color:#f44336;color:white;border-color:#000000;" name="submitCancel" id="submitCancel" class="btn btn-success" data-toggle="modal" data-target="#myCancelModal" onclick="cancel('<?= $_POST['order_id'] ?>')">Cancel</button>
<script>
function viewOrder(order_id, order_id, user_id, order_date, order_time, order_deliveryCharge, order_totalAmount, address, coordinates, driver_number, order_status) {
document.getElementById("t_order_id").setAttribute("value", order_id);
document.getElementsByName("ORDER_ID_MODAL_2")[0].setAttribute("value", order_id);
document.getElementById("t_user_id").setAttribute("value", user_id);
document.getElementById("t_order_date").setAttribute("value", order_date);
document.getElementById("t_order_time").setAttribute("value", order_time);
document.getElementById("t_order_deliveryCharge").setAttribute("value", order_deliveryCharge);
document.getElementById("t_order_totalAmount").setAttribute("value", order_totalAmount);
document.getElementById("t_address").setAttribute("value", address);
document.getElementById("t_coordinates").setAttribute("value", coordinates);
document.getElementById("t_drivers_number").setAttribute("value", driver_number);
document.getElementById("t_order_status").setAttribute("value", order_status);
document.getElementById("ORDER_MODAL_ACCEPT").setAttribute("value", order_id);
document.getElementById("ORDER_MODAL_DELIVER").setAttribute("value", order_id);
document.getElementById("ORDER_MODAL_CANCEL").setAttribute("value", order_id);
}
function accept() {
var x = document.getElementById("t_order_status").value;
if(x == "Accepted"){
document.getElementById("submitAccept").disabled = true;
}
}
</script>
Please help me guys with my problem. If you have other suggestion/idea how can I solve this problem feel free to comment guys. I really appreciate it a lot guys, Thanks!

Search with ajax on click and show results in same page laravel

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

Categories