Data insertion into database after clicking onto button - javascript

I would like to insert some data into my database using laravel eloquent after pressing a button.
My controller, controller method, route, js files are ready.
I just don't know how to connect these together.
Should i fire an event after clicking the button, if yes how can i do that using blade ?
I have a main page and form like this.
This is my main page :
{{ Form::open(array('action'=>'Mycontroller#myMethod')) }}
<!--Some html here !-->
<div class="row form-group">
<div class="col-sm-4">
<div class="btn btn-success" id="add" onclick="">
Here is my button
</div>
</div>
</div>
{{ Form::close() }}
I need to insert some data after clicking this button. How can i do this ? As like i said all my routes controller and function are ready for this.
Thanks in advance.

Since you already have your form set up, all you have to do is add a submit button and you will go to Mycontroller#myMethod when the submit button is called on.
// submit button
{{ Form::submit('Submit') }}
Then in your myMethod(), you can call this
$data = Input::all();
to get the form data.

Related

alpine.js - populating form data with button

I am trying to use alpine.js to update a form's action, and am running into some confusion.
My code:
<div x-data="data=''">
<template x-if="data.url">
<div>
<form method=POST :action="data.url">
<input type="text" x-model="data.sitenumber">
<button type="submit">Submit form</button>
</form>
</div>
</template>
<input type="button" value="add data" #click="data = {url: 'www.com', sitenumber: 23}">
</div>
When I click on the button, the div form doesn't appear. My ultimate goal is to have a modal popup that is dynamically updated with an action button (delete record, etc.) when a link/button elsewhere in the document is clicked.
I tried following long with this ToDo app tutorial, but this creates a separate function, and I thought it would be possible to pass simple data variables to a different part of the div, especially since I'm not looping through an array.
Thanks!
I think the issue is that you do x-data="data=''" instead of using object initialisation syntax: x-data="{ data: '' }"

AngularJs - submit the form programmatically

I read several answers on this topic but they don't seem to apply to my problem. My problem is quite complex. I have a form which uses ReportViewer.ASPX. The form is defined as following:
<form name="form" novalidate role="form"
sm-dirty-check
id="reportViewer"
method="post"
action="~/Infrastructure/ReportViewer/reportViewer.aspx"
target="viewerIFrame"
ng-show="crud.showForm" class="ng-cloak">
#* Form inputs *#
<input type="hidden" name="labelType" value="Rental" />
<input type="hidden" name="labelLayoutId" value="{{ crud.model.lbLayoutId }}" />
<input type="hidden" name="itemsToPrint" value="{{ crud.jsItemsToPrint }}" />
The actual forms are defined in the tabs using ng-form (I only shared the top portion of my Edit form which is relevant to my question).
I also have these buttons at the bottom of the form:
<button type="submit"
ng-if="crud.model.lbLayoutId!==0"
name="generateLabelButton"
id="generateLabelButton"
class="btn btn-primary pull-left"
ng-click="crud.generateLabel()"
ng-disabled="crud.isSaveButtonDisabled">
#Labels.generateLabel
</button>
<div class="pull-left generateLabelButton">
<data-desc:type ng-if="crud.model.lbLayoutId===0"
value="#Labels.generateLabel"
keep-pristine="true"
on-after-selection="crud.layoutSelected(selectedValue)"
title="{{ '#string.Format(Labels.selectX, Labels.labelLayout)'}}"
param="layouts"
message="#string.Format(Labels.selectX, Labels.labelLayout)"
selected="crud.model.lbLayoutId"
descrip-value="descrip"
id="layoutPickerButton"
name="layoutPickerButton"
button-type="button"
type="7"
filter-by="Label"
description="crud.model.lbLayout">
</data-desc:type>
</div>
So, if I have lblLayoutId defined, I have my regular submit button and I press it and get my form submitted and all is well.
If I don't have the lblLayoutId defined (it's 0), I need to use a directive which has a template for a button, when I press it, it opens a modal form to pick the layout, etc.
So, my problem is that after I picked the layout, I need to submit my form so the label can appear.
I tried making the directive to be of type submit (button-type property), this didn't work.
I also tried the following code in the method which is executed by the button when value is selected:
rentalEquipmentsCrudController.prototype.layoutSelected = function (selectedValue) {
this.model.lbLayoutId = selectedValue;
$("#generateLabelButton").click();
}
rentalEquipmentsCrudController.prototype.generateLabel = function () {
if (this.model.lbLayoutId === 0) return;
this.jsItemsToPrint = "";
this.itemsToPrint = this.getItemsToPrint();
this.jsItemsToPrint = JSON.stringify(this.itemsToPrint);
angular.element($("#viewerIFrame").contents()
.find("#reportViewer_ReportViewer")).empty();
let actionPath = angular.element($("#reportViewer")).attr("action");
if (actionPath.slice(-3) !== "pdf") actionPath += "/Labels.pdf";
angular.element($("#reportViewer")).attr("action", actionPath);
this.showViewer = true;
};
The layoutSelected method is executed from my directive and the next code is executed by my regular button.
So, I'm at lost as how to make it work.
The role of forms in client-side AngularJS applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload. Instead post JSON data and receive JSON data responses. Go to the server for data, but not html/js/css etc.
Read AngularJS <form> Directive API Reference - Submitting a form and preventing the default action.
You don't want to combine ng-click with a button of type="submit", this will still cause the form to submit (non-programmatically). Instead, use type="button". Alternatively, you can keep type="submit" but add the ng-submit="crud.generateLabel()" to the form element
<form>
...
<button type="button" ng-click="crud.generateLabel()">...</button>
</form>
Alternatively:
<form ng-submit="crud.generateLabel()">
...
<button type="submit">...</button>
</form>

Dynamically create buttons or send data to buttons

I am dynamically trying to pass data that I get from my for loop to the buttons. I am using django to get the data in the for loop, html to make the button and jquery to pass the data. I am not sure if this is the best description though.
My code is:
{% for dogs in Dogs.Other %}
<form id="primaryDogForm" action="{% url 'personal:account:email_dog_confirm' %}" method="post">
{% csrf_token %}
<input type="hidden" id="dogId" name="dogId" value="{{ dogs }}">
<input type="button" value="Make this your primary dog" id="makePrimaryButton" class="btn btn-primary" data-toggle="modal" data-target="#makePrimary" />
</form>
{% endfor %}
Basically, people can add a list of dogs to their account and select a dog to be their primary dog. I want a modal to be called when I click on the button. And that modal should display the name of the dog that is potentially being made the primary dog.
The modal code is as follows:
<div class="modal fade" id="makePrimary" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Make Primary</h4>
</div>
<div class="modal-body">
<p>
You are about to make <span id="newDog" name="newDog"></span> your primary dog.
</p>
<hr>
Submit
</div>
</div>
</div>
</div>
The jquery for to make everything work is:
$('#makePrimaryButton').click(function() {
($('#newDog').text($('#dogId').val()));
});
$('#makePrimarySubmit').click(function(){
$('#primaryDogForm').submit();
});
The problem I am facing is that, suppose I have a list of three dogs, each with a "Make this your primary dog" button, then the button works for only the first dog. The rest of buttons dont work until the first button gets clicked.
Once the first button is clicked, all the other buttons also get the value of the first dog. Hence, the dog 2 and dog 3 in the list cant be made primary dogs.
I am pretty sure the problem is with my html and jquery. Is there a way for me to make button dynamic so that the button gets the value of the dog it is associated with? That way, any dog can be made primary dog.
Thank you so much.
The problem here is with the ID's you're placing on the initial HTML in the for loop. ID's are unique in HTML - you should only have one of them with that ID name on a page. This is also why the jquery selector only picks up the first button properly.
Instead, one way to fix this is to use classes instead of ID's, like so:
{% for dogs in Dogs.Other %}
<form class="primaryDogForm" action="{% url 'personal:account:email_dog_confirm' %}" method="post">
{% csrf_token %}
<input type="hidden" class="dogId" name="dogId" value="{{ dogs }}">
<input type="button" value="Make this your primary dog" class="btn btn-primary makePrimaryButton" data-toggle="modal" data-target="#makePrimary" />
</form>
{% endfor %}
Then you'll need to update your jquery code to reflect this change:
var lastEditedForm = null;
$('.makePrimaryButton').click(function() {
lastEditedForm = $(this).closest('form');
var dogId = lastEditedForm.find('.dogId').val();
$('#newDog').text(dogId);
});
$('#makePrimarySubmit').click(function(){
lastEditedForm.submit();
});
Note that because you've got a click event for the modal defined outside of which dog button you've clicked - which dog button got clicked last needs to be tracked for when the modal is confirmed.
Using a variable outside the two click handlers is just one way to deal with this, and potentially not the best way. Another approach is to define a temporary event handler after the initial dog button is clicked - but that also requires ensuring that the event gets cleaned up properly in the event the modal gets cancelled.
-- Edit explaining temporary event handler --
In order to have a temporary event handler created on each of your dog button clicks, you also need to ensure that the temporary handler gets removed (no matter what) each time. In this case, because you're using a bootstrap modal, we can use the close event on the modal to definitively clear out the event handler.
The javascript looks like this:
$('.makePrimaryButton').click(function() {
// note we're still placing the form in a variable here
// so we have easy reference to it in the temporary event
// handler below
var currentForm = $(this).closest('form');
var dogId = currentForm.find('.dogId').val();
$('#newDog').text(dogId);
$('#makePrimaryButton').one('click', function(){
currentForm.submit();
})
});
// hidden.bs.modal is for Bootstrap v3 or v4. If you're using
// Bootstrap v2 it's just 'hidden.'
$('#makePrimary').on('hidden.bs.modal', function(){
// clears absolutely all event handlers on the button,
// not just the ones we set. We would need a reference to
// the function we set earlier in order to take just
// that function off.
$('#makePrimaryButton').off();
})
You should add a data attribute to the button. The link below gives a good example of it's implementation:
Passing data to a bootstrap modal

django javascript behaving oddly

I've a button called "Add new usage", basically, when user clicks it, it'll display the form, a pretty simple behavior, but I don't understand how it always triggers the action in the form underneath it, I'm very confused, here's my code:
<div class="row">
<p style="padding-left: 0.5cm;">
<button id="create_new_spa" class="btn btn-small btn-primary"
onclick="javascript:show_create_new_usage_form();" type='submit'
onclick="this.disabled=true">
Add new usage
</button>
</p>
</div>
<div class="row" id="create_new_usage_form" style="display:none">
<form method="post" action="/purchasing/item_info_spa_details_update/">
</form>
</div>
And here's my js code:
{% block jquery2 %}
function show_create_new_usage_form() {
$("#create_new_usage_form").show();
}{% endblock %}
So, I was expecting to click the "Add new usage" button, then the form shows up, however, now it displays form instantly, and following that, instantly within in like 20 ms, it quickly goes to action in the form, doesn't allow the user to see the form, and then quickly hides the form again.
I cannot see anything wrong with the code, please help!
Thanks a lot!
EDIT This answer is not correct. I leave it here for the insight from the comments below.
the following original statement is not correct see comments below:
The show() function of jquery is used to reveal an element for a given time (default 400ms).
See documentation here:
http://api.jquery.com/show/
You could e.g. use:
.css( "display", "inline" )
to show the form on click and then hide it with a dedicated function that is called via action.

Open Django template in bootstrap Modal

I'm trying to open a Django template in Twitter-Bootstrap Modal. Earlier I did it using JavaScript but it only opened once.
I read somewhere that Bootstrap Modals are more customizable, so giving it a try, I referred to an already answered question. I've the same problem and I've tried the same solution but it doesn't work for me. The only thing I get is blackened screen.
The flow goes like this:
A Django template is rendered which has several worker's details.
In that template, I've links to "Add advance" for every worker.
Clicking on which I want to open Modal.
In that Modal, I want to open another Django template containing a
form.
Filling the form, either close or press enter.
For any of these events on Modal, save the data from the form.
What I've done is here:
Template where the link is clicked: form.html
<a class="contact" href="#" data-form="/popupadvance/?worker_id={{value.worker_id}}&year={{year}}&month={{month}}" title="Advance"> Add advance</a>
<div class="modal hide" id="contactModal">
<script>
$(".contact").click(function(ev) { // for each edit contact url
ev.preventDefault(); // prevent navigation
var url = $(this).data("form"); // get the contact form url
alert(url);
$("#contactModal").load(url, function() { // load the url into the modal
$(this).modal('show'); // display the modal on url load
});
return false; // prevent the click propagation
})
</script>
The template which should open: popup.html
<div class="modal hide" id="contactModal">
<form id="form" class="well contact-form" action='/popupadvance/?worker_id={{value.worker_id}}&year={{year}}&month={{month}}' >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
{% csrf_token %}
{{worker_id}} <br />
{% for a in old_advances %}
{{a.advance_amount}} {{a.advance_date}}<br />
{% endfor %}
<input type="integer" id="popupadvance_{{worker_id}}" placeholder="Advance ++" class="popupadvance" >
</div>
<div class="modal-footer">
<input class="btn btn-primary" type="submit" value="Save" />
<input name="cancel" class="btn" type="submit" value="Cancel"/>
</div>
</form>
Clicking on the link: "Add advance", the only thing I get is the alert I've added closing which I get blackened screen over which the Modal should appear but neither the Modal, nor the form is rendered there. But pressing forward button on browser, I get the popup.html rendered on a new page, which probably tells that the URL is working on clicking the link, but only the Modal doesn't open.
I would like to tell that the input field in pupup.html is able to save data to database with OnChange event as I did when I opened up the dialog box using JavaScript.
Any help to find the problem will be greatly appreciated. As I don't see any error on Browser console.
Thanks.

Categories

Resources