so ive an HTML page that have multiple generated forms:
{% for row in data %}
<form action="/aggiorna_pratica" method='POST' id="inserisci_app_{{ row[0][1] }}">
<input name="id_pratica_{{ row[0][1] }}" type='hidden 'id="id_pratica_{{ row[0][1] }}" value="{{ row[0][1] }}"></input>
<button type="submit" class="btn btn-success aggiorna_app">
<i class="fa fa-check"></i>
</button>
</form>
{% endfor %}
row[0][1] contains the id of the row.
Im trying to send ajax requests from every single one of them, but i get the same ID of the frist row from every row.
This is the Javascript
$(document).ready(function() { $(".aggiorna_app").click(function(event) {
//prevent submit
event.preventDefault(); //Thx #alex
//do things on submit
$.ajax({
data : {
tipo_richiesta : "inserisci_intervento",
id : $('#id_pratica').val(),
data_int : $('#data_int').val(),
ora_int : $('#ora_int').val()
},
type: "POST",
url: "/aggiorna_pratica",
beforeSend: function(){
//Before send data
},
success: function(data){
console.log(data);
}
});
});
});
I know im a newbie but i could really use some help
Here is a working example to test your click event. The click event is on .aggoriorna_app buttons inside each form, but the id being passed into the ajax call looks to be grabbing the .val() every time, e.g, $('#id_pratica').val(). You'll see in my example that when a button is clicked, find the nearest input value and set the ajax id to that value. I assume that's what you need.
$(document).ready(function() {
$(".aggiorna_app").click(function(event) {
//prevent submit
event.preventDefault(); //Thx #alex
var id = $(this).parent().find('input').val();
alert(id);
});
});
form {
margin-bottom: 3rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<form action="/aggiorna_pratica" method='POST' id="inserisci_app_{{ row[0][1] }}">
<input name="id_pratica_{{ row[0][1] }}" type='hidden 'id="id_pratica_1" value="input_1"></input>
<button type="submit" class="btn btn-success aggiorna_app">
<i class="fa fa-check"></i>CLICK ME
</button>
</form>
<form action="/aggiorna_pratica" method='POST' id="inserisci_app_{{ row[0][1] }}">
<input name="id_pratica_{{ row[0][1] }}" type='hidden 'id="id_pratica_2" value="input_2"></input>
<button type="submit" class="btn btn-success aggiorna_app">
<i class="fa fa-check"></i>CLICK ME
</button>
</form>
<form action="/aggiorna_pratica" method='POST' id="inserisci_app_{{ row[0][1] }}">
<input name="id_pratica_{{ row[0][1] }}" type='hidden 'id="id_pratica_3" value="input_3"></input>
<button type="submit" class="btn btn-success aggiorna_app">
<i class="fa fa-check"></i>CLICK ME
</button>
</form>
</div>
Related
I am using 2 buttons to open two separate php pages but I would like to use one function to trigger both the buttons. The AJAX function that gets triggered should check which button was pressed and then open the php page associated with it. Such that "Export Page 1" should open Page 1.php and "Export Page 2" should open Page 2.php.
I am able to open one php page with my AJAX function. Now how do I check which button was pressed so I could open the right php page. How do I achieve this?
<html>
<body>
<div>
<input type ="submit" name="login" id="login" style="float: right; margin-right: 5px;" class= "btn btn-primary" value="Export Page 1" data-toggle="modal" data-target="#loginModal"/>
<input type ="submit" name="login" id="login" style="float: right; margin-right: 5px;" class= "btn btn-primary" value="Export Page 2" data-toggle="modal" data-target="#loginModal"/>
</div>
</body>
</html>
<div id="loginModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Login</h4>
</div>
<div class="modal-body">
<label>Username</label>
<input type="text" name="username" id="username" class="form-control" />
<br/>
<label>Password</label>
<input type="password" name="password" id="password" class="form-control" />
<br/>
<button type="button" name="login_button" id="login_button" class="btn btn-primary">Login</button>
<script>
$('#login_button').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username != '' && password != '')
{
$.ajax({
url:"Login.php",
method:"POST",
data:{username:username, password:password},
success:function(data){
if(data == 'No')
{
alert("Wrong Data");
}
else
{
$('#loginModal').hide();
window.open("Page 1.php"); //For page 1
// OR window.open("Page 2.php"); //For page 2
}
}
});
}
else
{
alert("Both fields are requried");
}
});
});
</script>
Because IDs must be unique, give each button a different ID
<input type="submit" id="login1" value="Export Page 1"...
<input type="submit" id="login2" value="Export Page 2"...
you can then give both buttons the same event - this would also work if you gave them both the same class and did the event on that class.
Within the event, store the button id somewhere where it can be picked up later by the modal's login button.
Because you're auto-opening the modal, there's a separation from open-dialog with button1/2 to click login on modal, so they're not related. You'll need to store on the modal/global/etc which button was used to open the modal when it's opened so that you can use that value when you actually login.
Let's store it on the modal's login_button:
$("#login1,#login2").click(function() {
$("#login_button").data("source_button", this.id);
});
where this.id will be login1 or login2.
Now when the login_button is clicked, we can see which button it was:
$("#login_button").click(function() {
$.ajax({
method: "POST",
data: { username: username, password: password },
success: function(data) {
$('#loginModal').hide();
var source_button = $("#login_button").data("source_button");
if (source_button == "login1")
window.open("Page 1.php");
else
window.open("Page 2.php");
}
});
});
To make this a little more usable (and less maintenance-heavy), you can make some small changes:
don't use an ID on the page button
code the destination page onto the page button
<input type="submit" class="pagelogin" data-page='page1.php' value="Export Page 1"...
<input type="submit" class="pagelogin" data-page='page2.php' value="Export Page 2"...
then
$(".pagelogin").click(function() {
$("#login_button").data("page", $(this).data("page"));
});
and in the callback
success: function() {
$('#loginModal').hide();
window.open($("#login_button").data("page"))
}
so when you want to add page3 etc you just add a new input with no code changes and keeps the separation of data (the page1.php) from the code (the js), which is always a goodthing(tm).
You can use functions for that:
function openPage(page) {
$.ajax({
method:"POST",
data:{
username:username, password:password
},
success:function(data) {
$('#loginModal').hide();
window.open(page);
}
});
}
In the html:
<input type="submit" onclick="openPage('Page 1.php')" name="login" id="login" style="float: right; margin-right: 5px;" class= "btn btn-primary" value="Export Page 1" data-toggle="modal" data-target="#loginModal" />
<input type="submit" onclick="openPage('Page 2.php')" name="login" id="login" style="float: right; margin-right: 5px;" class= "btn btn-primary" value="Export Page 2" data-toggle="modal" data-target="#loginModal" />
you can use the dataset aswell
make a single function for both buttons use the event parameter to extract the data-page out of the clicked element and pass through it
function submitButtonHandler(e) {
var targetPage = e.target.dataset.page;
console.log('Target is ' + targetPage);
}
window.addEventListener('load', function() {
document.getElementById('button1').addEventListener('click', submitButtonHandler);
document.getElementById('button2').addEventListener('click', submitButtonHandler);
});
<input type="submit" value="Login 1" data-page="Page 1" id="button1">
<input type="submit" value="Login 2" data-page="Page 2" id="button2">
how to pass value selected from radio button to ajax url.
I have radio button select download/upload.
CODE:
<form id="listofiles" action="" class="post-form" role=form method="post">{% csrf_token %}
Select: Download:
<input class="form-check-input" name="optionsRadios" type="radio" value="download">
or Upload:
<input class="form-check-input" name="optionsRadios" type="radio" value="upload">
BUTTON:
<input type="submit" value="GO" id="download" name="download" class="btn btn-info" />
<input type="submit" value="GO" id="upload" name="upload" class="btn btn-warning" />
Based on which one is select button will show.
CODE:
<script>
$("input[name='optionsRadios']:radio")
.change(function() {
$("#upload").toggle($(this).val() == "upload");
$("#download").toggle($(this).val() == "download"); });
</script>
Once the user selects the options, it will load the data from the other HTML file into div
CODE:
<div id="fetchdata" align="center">
<!-- LOADING DATA FROM THE AJAX listofiles.html -->
</div>
AJAX CODE:
$("#listofiles").submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
url: 'listofiles.html',
type: $(this).attr('GET'),
data: $(this).serialize(), // get the form data
success: function(data) { // on success..
$("#fetchdata").html(data); // update the DIV
console.log(data);
}
});
return false;
});
HTML: listofiles.html
Issue, in this page, I have two forms with the different ID. How to load forms based on the optionsRadios selected.
CODE:
<div id="download" style="display:none"><div align="center" class="container">
<form id="download" action="download" role=form method="POST" class="post-form">{% csrf_token %}
. . .
<div class="col" align="left">
<button type="submit" name="download" class="btn btn-primary btn-lg">DOWNLOAD</button>
</div></div></form></div></div>
<div id="upload" style="display:none"><div align="center" class="container">
<form id="upload" action="upload" role=form method="POST" class="post-form">{% csrf_token %}
. . .
<div class="col" align="left">
<button type="submit" name="upload" class="btn btn-primary btn-lg">UPLOAD</button>
</div></div></form></div></div>
I am assuming that we stay on the same page: then we can update your code:
Reuse the same selector:
$("input[name='optionsRadios']:radio:checked").val() == "upload");
Use the checked pseudoselector to see which value was selected to toggle the correct div.
Executing this code will result in multiple elements with the same id name. Better to use class names or unique ids.
$("#listofiles").submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
url: 'listofiles.html',
type: $(this).attr('GET'),
data: $(this).serialize(), // get the form data
success: function(data) { // on success..
$("#fetchdata").html(data); // update the DIV
$("div[id='upload']").toggle($("input[name='optionsRadios']:radio:checked").val() == "upload");
$("div[id='download']").toggle($("input[name='optionsRadios']:radio:checked").val() == "download");
//there is already another element with id download | you need to change that, so circumventing like this for now.
}
}
});
return false;
});
I need some help about this code
I have some code in blade view
#foreach($cart as $ct)
<button type="button" id="edit{{$ct->id}}" class="btn-btn-delete">
<i class="mr-1 fas fa-edit"></i>Edit
</button>
//when I {{$ct->id}} at this point, it return id of current product
<div class="form-popup" id="myForm{{$ct->id}}">
//however, when I {{$ct->id}} at this point, it return id of the last product
<form action="{{route('cart.update',$ct->id)}}" class="form-container" method="post">
#csrf
#method('patch')
<h1>Edit information</h1>
<input type="text" name="name" value="{{$ct->name}}">
<button type="submit" class="btn">change</button>
<button type="button" class="btn cancel" id="close{{$ct->id}}">Close</button>
</form>
</div>
<script>
var ID = {{$ct->id}};
var code = 'edit'+ID;
var end = 'close'+ID;
var form = 'myForm'+ID;
document.getElementById(code).addEventListener("click",function(){
document.getElementById(form).style.display = "block";
});
document.getElementById(end).addEventListener("click",function(){
document.getElementById(form).style.display = "none";
});
</script>
#endforeach
when I run my code and click on Edit button the expected value in input field of each row must be different. However, it all gets the value of the last column in the database.
How I can fix it?
Following is approach using addEventListener() and classes to target elements as well as data attributes (like data-target="myForm1") for element specific data to use inside an event handler.
It is currently working for the "Edit" and "Cancel" buttons which have the same class popup-toggle along with their other existing classes.
You can use this approach as a template for your other elements/actions
// in DOMContentLoaded event handler or after elements exist
const popToggleButtons = document.querySelectorAll('.popup-toggle');
[].slice.call(popToggleButtons).forEach(function(btn) {
btn.addEventListener('click', handleToggleBtnClick)
});
function handleToggleBtnClick(event) {
const btnData = this.dataset,
popup = document.getElementById(btnData.target),
classMethod = btnData.action === 'show' ? 'add' : 'remove';
// add or remove active class depending on which button was clicked
popup.classList[classMethod]('active');
}
.form-popup {
display: none
}
.form-popup.active {
display: block
}
<div>
<button type="button" data-target="myForm1" data-action="show" class="popup-toggle btn-btn-delete">
<i class="mr-1 fas fa-edit"></i>Edit #1
</button>
<div class="form-popup" id="myForm1">
<form action="..." class="form-container" method="post">
<h1>Edit information #1</h1>
<input type="text" name="name" value="name 1">
<button type="submit" class="btn">change</button>
<button type="button" class="btn cancel popup-toggle" data-target="myForm1" data-action="hide">Close</button>
</form>
</div>
</div>
<div>
<button type="button" data-target="myForm2" data-action="show" class="popup-toggle">
<i class="mr-1 fas fa-edit"></i>Edit #2
</button>
<div class="form-popup" id="myForm2">
<form action="..." class="form-container" method="post">
<h1>Edit information #2</h1>
<input type="text" name="name" value="name 2">
<button type="submit" class="btn">change</button>
<button type="button" class="btn cancel popup-toggle" data-target="myForm2" data-action="hide">Close</button>
</form>
</div>
</div>
And this $emp->id gives me an accurate id, so it's not an issue I just get id={{$emp->id}} from this? Help please.
<a href="{{'/employee'}}?id={{$emp->id}}" type="button" name="u_id" > Apply Attribute </a>
After Click on Apply Button the value, using this it always returns the 1st user id, or if I use this outside from foreach loop it will give me the 2nd user id, so if we get the when click on href and want to store this id value in a variable and use this in the value? So please help me to get the value from the anchor tag? I am happy if you solve this problem. Thanks developers in advance.
<form action="{{'/rating'}}" method="post">
{{csrf_field()}}
<input type="hidden" name="user_id" value="{{$emp->id}}" />
<input type="submit" style="margin-bottom: 10px;" class="btn btn-success pull-right" name="apply" value="Apply"/>
</form>
Why are you pulling {{'/employee'}} ?
#foreach($employ as $emp)
<tr>
<td>{{$emp->name}}</td>
<td>
<a href="/employee?id={{$emp->id}}" type="button" name="u_id"class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Apply Attribute
</a>
</td>
#endforeach
Href Like That:
<a href="{{$emp->id}}" type="button" id="uu_id" class="btn btn-primary uu"
data-toggle="modal" data-target="#myModal"> Apply Attribute </a>
Using This Script To get Value from Href:
<script type="text/javascript">
$(document).ready(function() {
$(".uu").click(function(event) {
var u_id = $(this).attr('href');
event.preventDefault();
document.getElementById("hiddenVal").value = u_id;
});
});
</script>
And in your Form like this:
<form action="{{'/rating'}}" method="post">
{{csrf_field()}}
<input type="submit" style="margin-bottom: 10px;" class="btn btn-success
pull-right" name="apply" value="Apply"/>
<input type="hidden" name="hiddenVal" id="hiddenVal" />
</form>
And Last How to get this Value in the Controller And save to Database:
public function store(Request $request)
{
$rates = new Rating;
$user_id = $_POST['hiddenVal'];
$rates->user_id = $user_id;
$rates->save();
return redirect('/employee');
}
Though a common question I searched around and tried all hit and trial .. but no avail .. still the issue for jquery validation persist before ajax call.. The form is getting submitting without any validation
Please provide any info where i may be getting wrong
<script type="text/javascript">
$(document).ready(function () {
$('#myform').validate({
rules: {
objective: {
required: true,
minlength: 150
},
},
submitHandler: function ()
{
var dataString = $("#myform").serializeArray();
$("#flash").show();
$.ajax({
url: "xyz.php",
type: "POST",
data: dataString,
cache: false,
async: false,
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
},
success: function (data) {
$("#flash").hide();
$('#info').html(data.objective);
$('.success').fadeIn(200).show();
$("#objective").focus();
}
});
return false;
}
});
});
</script>
html
<form class="form-horizontal " name="myform" id="myform" action="include/process.php" method="post">
<div class="form-group">
<label for="objective" class="col-lg-3 control-label">Objective</label>
<div class="col-lg-9">
<textarea class="form-control" rows="6" id="objective" name="objective" placeholder="Objective" ></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-12">
<button type="submit" id="editbtn" class="btn btn-sm btn-success pull-right hovertip" data-toggle="tooltip" data-original-title=" Add ">Add Data</button>
</div>
</div>
</form>
There are three more similar forms on the same page...
Add e.preventDefault in the beginning of your click handler.
$("#editbtn").click(function (e) {
e.preventDefault();
// rest of the code.
}
It will prevent your form from being sent without going through your js code.
You could do what #Romain said or change the HTML to:
<input type="button" id="editbtn" class="btn btn-sm btn-success pull-right hovertip" data-toggle="tooltip" data-original-title=" Add " value="Add Data" />
So the form doesn't submit
If you are going to trigger the submit via JavaScript, then you can type the button as 'button', instead of submit:
<button type="button" id="editbtn" class="btn btn-sm btn-success pull-right hovertip" data-toggle="tooltip" data-original-title=" Add ">Add Data</button>
This will prevent the default submit action from executing, and let you handle everything via your onclick method.