Get button id of a form in cshtml - javascript

I've two forms on the same page. On clicking any one of the buttons, both queries of the buttons are being submitted as I've used the function IsPost like if(IsPost){ //run queries}
Since both the forms are on the same page, on submission of any button, both the events of the two buttons are triggered.
I want to run separate queries on submission of each of the buttons.
In php, we used if(isset($_REQUEST['buttonname'])){ //run queries }.
Is there any such way, I can achieve the same in cshtml?
Update
What if I already have passed a value in the buttons?
Like for eg:
<div class="btn-group pull-right">
#{
var followersearchcommand = "SELECT * from follow where follow_followerid = #0 and follow_followingid = #1";
var followsearch = db.Query(followersearchcommand, follower_id, row.student_id);
}
#if(followsearch.Count > 0){
<button class="btn btn-primary" type="submit" name="unfollow_followingid" value="#row.student_id" title="Follow" style="display: none"></button>
<button class="btn btn-primary" type="submit" name="unfollow_button" value="unfollow" title="Follow">UnFollow</button>
}
else{
<button class="btn btn-primary" type="submit" name="followingid" value="#row.student_id" title="Follow" style="display: none"></button>
<button class="btn btn-primary" type="submit" name="follow_button" value="follow" title="Follow">Follow</button>
}
</div>

Assign to both buttons the same name and test their value:
#{
if (IsPost){
if(Request["button"] == "buttonA"){
// button A is pressed
} else {
// button B is pressed
}
}
}
<form method="post">
<input type="submit" name="button" value="buttonA" />
<input type="submit" name="button" value="buttonB" />
</form>
Edited
If you want to have two distinct forms, you could use the IsEmpty() method:
#{
if (IsPost){
if(!Request["buttonA"].IsEmpty()){
// button A is pressed
} else {
// button B is pressed
}
}
}
<form method="post">
<input type="submit" name="buttonA" value="buttonA" />
</form>
<form method="post">
<input type="submit" name="buttonB" value="buttonB" />
</form>

html:
<form id="a">
<button type="submit">Submit A</button>
</form>
<form id="b">
<button type="submit">Submit B</button>
</form>
javascript:
$(function(){
$("#a").submit(function(e){
e.preventDefault();
// Query A
alert('A');
});
$("#b").submit(function(e){
e.preventDefault();
// Query B
alert('B');
});
});
Demo
Edit:
You can make an ajax call to your controller's action:
$.ajax({
type: "POST",
url: "#Url.Action("actionName", "controllerName")",
data: { /* your data */ },
success: function (data, textStatus, jqXHR) {
// success
},
error: function (jqXHR, textStatus, errorThrown) {
// error
}
});
And in your controller:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult actionName(/* your data */)
{
var success = DoSomething();
if (!success)
{
throw new HttpException(500, "Server error!");
}
return Json("");
}
Something along those lines...
Hope this helps!

Related

How to use same php function for different button clicks

Here is a simple PHP form with a button..
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Here is the Jquery functions which executes a PHP file.
$(document).ready(function(){
$("#btnnew1").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
$.ajax({
url: 'test.php',
success: function(data) {
$("p").text(data);
}
});
}
});
});
And the test.php is as follows,
<?php
echo 'Button1 clicked'
?>
My question is how to modify my test.php if I have multiple buttons.
As an example,
<form method="POST">
<div class="mb-3">
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew2" class="btn btn-info" >submit</button>
<p></p>
</div>
<div class="mb-3">
<button type='button' id ="btnnew3" class="btn btn-info" >submit</button>
<p></p>
</div>
</form>
Result should be,
If btnnew1 clicks--->echo("Button1 clicked);
If btnnew2 clicks--->echo("Button2 clicked);
If btnnew3 clicks--->echo("Button3 clicked);
Update:
What If I need to run three different php functions(no any pattern)?
Ex:
If btnnew1 clicks--->
sleep(5)
echo("Button1 clicked);
If btnnew2 clicks--->
sleep(15)
echo("Button2 clicked by user);
If btnnew3 clicks--->
sleep(35)
echo("Button3 clicked by user);
In here I am changing little bit your default settings. This will help you as I can understand. You can try as below,
1)Change your button into input type..I have added some inline CSS as well. If you don't like you may neglect it...
<input type="button" style="background-color: #3CBC8D;padding:3px;" class="button" name="fcn1" value="Update My Status"/>
<input type="button" class="button" style="background-color: #3CBC8D;padding:3px;" name="fcn2" value="Update My Status" />
Then go to jquery and use as below, success function change as you wish. Here I have used an alert box...
$(document).ready(function(){
$('.button').click(function(){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
else{
var clickBtnValue = $(this).attr('name');
var fetchdata= 'testme.php',
data = {'action': clickBtnValue};
$.post(fetchdata, data, function (response) {
// Response div goes here.
alert("Updated successfully -"+response);
});
}
});
});
Finally change your testme.php as follows,
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'fcn1':
fcn1();
break;
case 'fcn2':
fcn2();
break;
}
}
function fcn1() {
echo 'Button1 clicked';
exit;
}
function fcn2() {
sleep(5);
echo 'Button2 clicked';
exit;
}
Set the name to each button:
Button 1
Send data using ajax:
Get button text using e.target.text and send using POST method.
$.ajax({
type: 'POST',
url: 'test.php',
data: { buttonTitle: e.target.name},
success: function(data) {
$("p").text(data);
}
});
php:
Inside php use $_GET to get the data which we send from the frontend.
if(isset($_POST['buttonTitle'])) {
$buttonTitle = $_POST['buttonTitle'];
echo $buttonTitle . " clicked";
}

How to submit form without the page reloading

I have this form
<form action="" method="post" enctype="multipart/form-data" onsubmit="submit()">
<input id="name" class="btn" type="file" name="pic" multiple>
<br/><br/>
<button class="btn btn-primary" type="submit" id="submit" name="submit">UPLOAD</button>
</form>
<br/><br/>
Uploaded file: <a target="blank" href="<?php echo $fileurl;?>"><?php echo $fileurl;?></a>
and I have this script
<script>
function submit(event) {
event.preventDefault()
var http = new XMLHttpRequest();
http.open("POST", "", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
</script>
I want to submit the form without the page reloading but isn't working for me.
Your function takes event property, on which you can invoke preventDefault()
function submit(event) {
event.preventDefault()
var http = new XMLHttpRequest();
http.open("POST", "", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
<script>
$('#yourFormData').submit(function(e){
e.preventDefault();
var formData = new FormData($('#yourFormData')[0]);
url ="your route" ;
$.ajax({
url : url,
type : "post",
data : formData,
contentType:false,
processData:false,
success : function(data)
{
// success
},
error : function(y)
{
console.log(error );
}
});
})
See this check function to stop page reloding
As you have requested I have given the full code
function check(event) {
event.preventDefault();
console.log("stopped form submit");
}
<form onSubmit="check(event)">
<input id="name" class="btn" type="file" name="pic" multiple>
<br/><br/>
<button class="btn btn-primary" type="submit" id="submit" name="submit">UPLOAD</button>
</form>
<br/><br/>
</form>

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

jQuery submit form normally or Ajax dependant on variable using FontAwesome buttons

I am using buttons for submit, as that is the only easy way to use fontawesome buttons. I detect which button was selected and place that value in a hidden field so that it is available in my Ajax routine.
This presents a problem, as one button requires a normal submit, as it goes to a script that creates a pdf.
The other conditions submit using Ajax. I attempted the following which, of course, will not work, as it creates a recursion loop.
Cannot figure a means to do this without creating a submit loop.
In Form:
<input type="hidden" id="Clicked" name="Clicked" value="" />
<button type="submit" class="btn btn-success ClickCheck" id="Create" style="display:inline;"> <i class="fa fa-file-pdf-o"> <span>Create Bill</span></i></button>
<button type="submit" class="btn btn-success ClickCheck" id="Reset" style="display:inline;"> <i class="fa fa-times"> <span>Reset</span></i></button>
<button type="submit" class="btn btn-success ClickCheck" id="SaveData"> <i class="fa fa-archive"> <span>Save Only</span></i></button>
<button type="submit" class="btn btn-success ClickCheck" id="Create-Save"> <i class="fa fa-archive"> <span>Create and Save</span></i></button>
jQuery Code:
$(document).ready(function()
{
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
});
$("#MyForm").on("submit", function(event)
{
event.preventDefault();
var Form = $('#MyForm');
var Valid = verify();
if(Valid)
{
if($('#Clicked').val() == "Create")
{
$(Form).attr('action', './blformpdf.php');
$(Form).submit();
}
else
{
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: Form.serialize(),
success: function(response)
{
console.log(response);
}
});
}
}
});
});
The callback should be done from verify() , I've written an example .
var goIsWaiting=false;
var goIsActive=false;
function go(){
if(goIsActive)
adviseGoIsActive()
else{
console.log("Go Is Waiting !");
goIsWaiting=true;
}
}
function activate(){
//.. Doing some stuff here
if(goIsWaiting) adviseGoIsActive();
goIsActive=true;
}
function adviseGoIsActive(){
console.log("Go Is Active !")
}
<input type="submit" value="Go" onClick="go()">
<input type="submit" value="Activate Go Action" onClick="activate()">
The solution for this problem was simply to use links rather than <input> or <button>.
Here is the HTML:
<input type="hidden" id="Clicked" name="Clicked" value="" />
<a class="btn btn-success ClickCheck" id="Create" href="javascript:void(0)"> <i class="fa fa-file-pdf-o"> <span>Create Bill</span></i></a>
<a class="btn btn-success ClickCheck" id="Reset" href="javascript:void(0)"> <i class="fa fa-times"> <span>Reset</span></i></a>
<a class="btn btn-success ClickCheck" id="SaveData" href="javascript:void(0)"> <i class="fa fa-archive"> <span>Save Only</span></i></a>
<a class="btn btn-success ClickCheck" id="Create-Save" href="javascript:void(0)"> <i class="fa fa-archive"> <span>Create and Save</span></i></a>
One of these buttons is a reset. Although you can define a <button> as type="reset", for consistency, as well as other reasons, I left that too as a link and, since the button id is part of my post, the Ajax script detects that and just returns a null, then used a jQuery reset to clear the form after the null Ajax call.
$(document).ready(function()
{
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
var Form = $('#MyForm');
var Valid = verify(); // form verify function
if(Valid)
{
if(ButtonID == "Create") // Send to PDF script
{
$(Form).attr('action', './blformpdf.php');
$(Form).submit();
}
else
{
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: Form.serialize(),
success: function(response)
{
// Do whatever here with response data
}
}
if(ButtonID == "Reset")
{
$('#MyForm').trigger("reset");
$('#Clicked').val('');
}
}
}
});
});

function "cancel" adds edited form instead cancel it

I'm working on functions for form. Data for this form comes from api call and filling input fields. Submit button works well, but behavior of cancel button is weird, instead of cancel last changes it sends updated data to db. Could anybody help me to find my mistake?
Also I have tried to type="reset" and it returns default empty fields but I need that it has returned old value before editing
My form:
<form style="padding: 15px" ng-submit="submitForm()">
<div class="form-group row">
<div ng-repeat="k in rowKeys | filter: '!id' | filter: '!0' " ng-model="rowValue">
<label for="rowValue" class="col-sm-2">
{{k | hide:'.name' | makeUppercase}}:
</label>
<div class=" col-sm-2" >
<input class="form-control rowValue" id="rowValue" ng-model="rowData[k]" ng-disabled="isDisabled()"/>
</div>
</div>
</div>
<button type="submit" class="btn btn-default" ng-if="rowData" >Save</button>
<button type="button" class="btn" ng-if="rowData" ng-click="cancelForm()">Cancel</button>
js
$scope.submitForm = function() {
$scope.$watch('rowData', function(newValue, oldValue) {
console.log('being watched oldValue:', oldValue, 'newValue:', newValue);
}, true);
$http({
method : 'PUT',
url : $scope.globalUrl + $scope.id,
data : $scope.rowData //form
})
.then(function (res) {
return res;
})
.then(function (){
$('#table').bootstrapTable('refreshOptions', {
'url': $scope.globalUrl
});
})
};
$scope.cancelForm = function () {
$scope.$watch('rowData', function(newValue, oldValue) {
return oldValue;
console.log('being watched oldValue:', oldValue, 'newValue:', newValue);
}, true);
}
Change
<button type="submit" class="btn" ng-if="rowData" ng-click="cancelForm()">Cancel</button>
To
<button type="button" class="btn" ng-if="rowData" ng-click="cancelForm()">Cancel</button>
When you put type="submit" this means that on click it will do the submit action on your form

Categories