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">
Related
I want to post the phone number in my modal popup form.but don't want to disappear the popup after submitting the form clicking on "continue" button. Here is my blade.php code.
<div id="modal-wrapper" class="modal">
<form class="modal-content animate" id="addform">
<input type="text" class="form-control" name="phone_number" placeholder="01**********">
</div>
</div>
<div style="text-align: center; margin-top: 10px;padding-left:18px;">
<button type="submit" style="background-color: #a5abb0;" class="mobile-login__button">CONTINUE
</button>
</div>
here is my script part for ajax part of the code.
<script>
$("#addform").on('submit',function(e){
e.preventDefault();
$.ajax({
type:"post"
url: "/client-mobile-login"
data: $("addform").serialize(),
success:function(response){
},
error:function(error){
console.log(error)
alert("not send");
}
)};
});
});
</script>
and here is my controller function
public function client_mobile_login(Request $request)
{
$client_phone1='88'.$request->input('phone_number');
$result=DB::table('client')
->where('client_phone1',$client_phone1)
->first();
{{ here is my otp sending code.... }}
if($result)
{
$request->session()->put('client_title', $result->client_title);
// print_r($client_phone1);
}
Use type=button
<button type="button" id="submitForm" ...>CONTINUE</button>
And trigger your ajax on click event
$("#submitForm").on('click',function(e){ ... }
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 have a link/popup working with a confirmation box. But now need to migrate it to a checkbox and submit button. I need some assistance with getting the JQuery to work with the form. Any ideas?
https://jsfiddle.net/829mf5qx/2/
<!-- Used with JQuery function below -->
Confirm order?
<!-- Need to edit the Jquery below to work with this code block -->
<div style="margin-top:20px;">
<form name="orderReceived" action="" method="post" onsubmit="return confirm_update();">
<input type='checkbox' name='files' id='1' value='1' /> Confirm order?
<br>
<input type="submit" value="Submit" name="submit">
</form>
</div>
$(document).ready(function() {
$('a[data-confirm]').click(function(ev) {
var href = $(this).attr('href');
if (!$('#dataConfirmModal').length) {
$('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
}
$('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmOK').attr('href', href);
$('#dataConfirmModal').modal({show:true});
return false;
});
});
Here is your solution: jsfiddle
$(function(){
$('#submit').click(function(){
if($("#checkbox").is(':checked')){
if(confirm('Are you sure you want to confirm the order?')){
$('#submitHelper').click();
}
}
});
});
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.
I have a page using a modal to get the users email and I want to add it to a list of subscribers (which is a Django model). Here is the modal code for that:
<div id="notifications" class="modal hide fade" role="dialog" ara-labelledby="Notification" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<h4>Subscribe to Status Notifications</h4>
</div>
<form>
<div class="modal-body">
<input type="email" placeholder="email"/>
<p>This service will notify you by email should any issue arise that affects your plivo service.</p>
</div>
<div class="modal-footer">
<input type="submit" value="SUBMIT" class="btn"/>
</div>
</form>
</div>
I tried to look in the Twitter Bootstrap doc but it really is minimal. I want to POST the data to a Django view that's listening forPOST` requests.
This is the bare essential. I am using regex to compare the format of the email before storing the email id. So if the email does not match the regex the view returns an Invalid Email. So I would like to notify the user about that within the modal itself. But I really have no idea as to how to do this. Someone please help.
UPDATE 1
Tried this based on karthikr's answer:
<form id="subscribe-email-form" action="/notifications/subscribe/" method="post">
<div class="modal-body">
<input type="email" placeholder="email"/>
<p>This service will notify you by email should any issue arise that affects your service.</p>
</div>
<div class="modal-footer">
<input id="subscribe-email-submit" type="submit" value="SUBMIT" class="btn" />
</div>
</form>
<script>
$(function(){
$('subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: "/notifications/subscribe/",
type: "POST",
data: $("subscribe-email-form").serialize(),
success: function(data){
alert("Successfully submitted.")
}
});
});
});
</script>
There is something that is confusing me. What about the onclick event of the modal button?
I got it! I added name="Email" in the line <input type="email" placeholder="email"/>
The Django field is looking for the Email Field. So in my Django view the code is:
request.POST.get("Email", '')
So specifying the field name helps. But it takes me to the URL where I am posting. I want it to display a alert in the same page.
UPDATE 2
So part 1 is working. As in the posts are working. Now I need to show a modal for the success or failure.
Here's what I am trying. So I created this modal with a textarea:
<div id="subscription-confirm" class="modal hide fade in" aria-hidden="true">
<div class="modal-header">
<label id="responsestatus"></label>
</div>
</div>
And the JavaScript:
<script>
$(function(){
$('#subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'notifications/subscribe/',
type: 'POST',
data: $('#subscribe-email-form').serialize(),
success: function(data){
$('#responsestatus').val(data);
$('#subscription-confirm').modal('show');
}
});
});
});
</script>
So the modal comes up, but the data is not set into the label field of the modal.
You need to handle it via ajax submit.
Something like this:
$(function(){
$('#subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#subscribe-email-form').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
A better way would be to use a django form, and then render the following snippet:
<form>
<div class="modal-body">
<input type="email" placeholder="email"/>
<p>This service will notify you by email should any issue arise that affects your plivo service.</p>
</div>
<div class="modal-footer">
<input type="submit" value="SUBMIT" class="btn"/>
</div>
</form>
via the context - example : {{form}}.
I was facing same issue not able to post form without ajax.
but found solution , hope it can help and someones time.
<form name="paymentitrform" id="paymentitrform" class="payment"
method="post"
action="abc.php">
<input name="email" value="" placeholder="email" />
<input type="hidden" name="planamount" id="planamount" value="0">
<input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
name="planform">
</form>
You can submit post form, from bootstrap modal using below javascript/jquery code :
call the below function onclick of input submit button
function form_submit() {
document.getElementById("paymentitrform").submit();
}
You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.
You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.
<form asp-action="AddUsersToRole" method="POST" class="mb-3">
#await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)
<div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add Users to Role</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</form>
You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.
Mozilla documentation on form action