check if button was clicked in the controller - javascript

I have the following button and when clicked it's invoking a function,
Is there a way to know in the controller that this button was clicked ?
$("#RemoveFile").on("click", RemoveFile);
<button class="btn" style="height: 25px" type="button" id="RemoveFile"><p >Remove File</p></button>

As Edurado Says this the implementation which you asked to him
First set hidden field in html page (razor view/ aspx page)
<input type="hidden" id="StakeholderId" name="stakeholderId" />
Then add script like below
$( "#buttonID" ).click(function() {
$( "StakeholderId" ).val(true);
});
And get the value and posting the value to controller like below
var hidden= $('StakeholderId').val();
$.ajax({
type: "post",
url: "Controller/Method",
data: {
hiddenField1: hidden,
hiddenField2: "hiddenValue2",
},
success: function() {
alert("yay")
},
error: function(e) {
console.log(e);
}
});
Hope this helps....

When you click in the button, add an onclick event to this very button and save the clicked status in a hidden field. Then, whenever you send data to the controller, send this hidden field value, stating whether the button was clicked.
UPDATED:
Here is the HTML
<input id="hdnRemoveClicked" type="hidden" value="false" />
And here is the javascript which adds the click event in the button with ID="RemoveFile", and set the hidden field value as true, to show it is clicked.
$( "#RemoveFile" ).click(function() {
$( "hdnRemoveClicked" ).val(true);
// do other things, if needed
});

The only way I know of to so this in MVC is to make an Ajax call to the server via an anonymous function in the JQuery component. Example:
$("#RemoveFile").on("click", "RemoveFile", function () {
// tell server
var jqxhr1 = $.ajax({ type: 'POST', url: "/myControllerUrl",
data: { buttonID: "RemoveFile" } });
$.when(jqxhr1).done(function (response, textStatus, jqXHR) {
if (textStatus != "success") {
alert("Error, please try later");
return false;
}
// update the user interface
});
});

Make an ajax call to a method in Controller where a session keeps track if button was clicked.

Related

jQuery .submit() not working after ajax response

I was trying to call jQuery.submit() function after ajax response. Where ajax response contains a form. But it couldn't call jQuery.submit() function when i submit the form without refresh.
I prepend the form with the existing code after successfull ajax response
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
},
error: function(data) {}
So after adding the form to the existing code. When i tried to submit the form it's got refresh instead of calling the function. How to make jQuery.submit() workable from ajax response?
$(".replyName").submit(function(event) {
alert(event.currentTarget[0].value);
});
You should place the submit event after you prepend the form. Because event's are only binded to the elements after the DOM is loaded.
And because the prepend the form dynamically, jQuery doesn't know which element it has to submit, because it didn't exist at the time it binded the event.
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$( ".replyName").submit(function( event ) {
alert(event.currentTarget[0].value);
event.preventDefault();
});
},
error: function(data) {}
Since the form is not created in the document, you cant listen to submit event, unless you put the event listener after you prepend form into the dom
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$(".replyName").submit(function(event) {
alert(event.currentTarget[0].value);
});
},
error: function(data) {}
You can also handle the event from body dom
$('body').on('submit', '.replyName', function(e){
// code here
});
There are two thing you can do:
Either you can rebind the click function like this:
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$('button').bind('click', function (event) {
event.preventDefault();
alert(event.currentTarget[0].value);
});
},
error: function(data) {}
or you can try this
$('button').on('click', function(e){
// code here
});

Event needs multiple clicks in Jquery

I am trying to get the response from the PHP scripts but the button takes multiple clicks on firing the event. I read about that on Google but unable to understand that why it is going to happen.
Html Code
<form action="javascript:MyResults()">
<input type="submit" value="Search" id ="button1"/>
</form>
Javascript Code
function MyResults(){
$(document).ready(function(){
$("#button1").click(function(){
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"search" : searchDat,
},
success: function(value){
alert( JSON.parse(value));
$.each(value, function(index, value1){
console.log(value1);
});
}
});
});
});
}
</script>
You are declaring $(document).ready(function() inside MyResult function . In first case it will execute the MyFunction & in second case it will execute the code inside the ready function.
Actually there is no need to the action here. Following change will work
HTML
<form id='target'>
<input type="submit" value="Search" id="button1" />
</form>
JS
$(document).ready(function() {
$("#target").submit(function() {
event.preventDefault()
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type: "POST",
async: true,
data: {
"search": searchData,
},
success: function(value) {
alert(JSON.parse(value));
$.each(value, function(index, value1) {
console.log(value1);
});
}
});
});
})
The problem is that your current code doesn't set-up the click-handler for button until the form is submitted. That first click triggers the action attribute on the <form>, which sets up the handler. The second click then calls the button handler.
Instead of your current code, you probably want HTML like this:
<form>
<input type="submit" value="Search" id ="button1"/>
</form>
Use $(document).ready(...) without the wrapper function MyResults(), and be sure to cancel the click event to stop traditional form submission:
<script>
$(document).ready(function(){
$("#button1").click(function(event){
event.preventDefault();
event.stopPropagation();
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"search" : searchDat,
},
success: function(value){
alert( JSON.parse(value));
$.each(value, function(index, value1){
console.log(value1);
});
}
});
});
});
</script>
Here fired one event at two times.
First fired when form submit.
action="javascript:MyResults()"
Second fired after form submit which you have defined in the function part.
$("#button1").click(function(){});

When and when doesn't success: value executes in jQuery Ajax method? (Header location not changed)

I'm submitting a form using jQuery Ajax.
The data is submitted successfully but there's a little problem. When I add the commented statements in this code, the success: function(){} doesn't run (location is not changed).
Q. 1 When I remove those statements, it runs. I don't understand this logic. When does it actually executes and how does checking for xy affects this?
Here's my Ajax code:
$(document).ready(function(){
$("#button").click(function(){
**//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result){
$(location).attr('href', 'login2.php');
},
error: function(){
alert(error);
}
});
// }
});
});
Here's concerned input tag:
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />
......
Q.2 When I write event.preventDefault(); to stop the default action of submit button, the required atrributes of input fields don't work. Why is it so? Can it be solved?
To Question 2:
If you call preventDefault for the event of the click on the submit button, then the default behaviour (initiating the submit) is prevented, so the input fields are not checked.
You have to listen on the submit event of the form instead and prevent the default behaviour of this, because the submit event is send after the input elements are checked and before the form is submitted.
$(document).ready(function() {
$("#signupform").on('submit', function(e) {
e.preventDefault();
//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result) {
$(location).attr('href', 'login2.php');
},
error: function() {
alert(error);
}
});
// }
});
});
When you use jquery ajax there is two types of result:
400 - OK status which be capture by the success function
402 or 500 are internal errors and those will be capture by the error function.
Now, in your error function youre trying to print an error variable that does not exist.
Also, when you use preventDefault you have pass variable that handles de event too cancel.

[jQuery]Page refreshes after appending html with .html()

So I'm trying to get some data from the server with php but as soon as it's loaded onto the page it seems to reload the page and make it disappear again.
My html:
<form id="searchForm">
<input name="searchValue" type="text" id="search">
<input type="submit" name="Submit" value="Zoek op klant" onclick="getKlanten()">
</form>
<div id="klanten">
</div>
My js:
function getKlanten(){
var value = $("#search").val();
$.ajax({
url:'includes/getKlanten.php',
async: false,
type: 'POST',
data: {'searchValue':value},
success: function(data, textStatus, jqXHR)
{
$('#klanten').html(data);
},
error: function () {
$('#klanten').html('Bummer: there was an error!');
}
});
}
Can anyone help? It gets put into the div but then instantly disappears again.
Firstly, avoid inline click handlers. The page reloads because by default a form submits the form content to the url specified in action attribute.
Instead attach an event to the form and use preventDefault to avoid the page from refreshing. Do something like this
$('#searchForm').on('submit', function(e){
e.preventDefault();
// your ajax request.
});
Or attach an event to input button like this
$('input[type="submit"]').on('click', function(e){
e.preventDefault();
// your ajax request
});
Read more about preventDefault here

Grails order of function execution

I have a formRemote that calls a function in my controller when it is submitted like this:
<g:formRemote name="editIndivRecForm" url="[controller: 'customer', action:'saveEditedIndividualRecord']" onSuccess="doResult();">
This form is submitted by clicking on a button. Rather, a button that is clicked called 'save' will do other things among clicking the form's submit button via Javascript. Here is the click handler for this button:
$('#save').click(function () {
$("#uniqueId").prop('disabled', false); // Have to enable before form submission else it doesn't go back as a param to controller.
$("#secondaryId").prop('disabled', false);
$("#submit").trigger("click"); // formRemote's submit button
$('#editIndivRecForm').reset;
<g:remoteFunction controller="customer"
action="remediationSearch"
update="content_area"
params="{rerender: true}"/>
});
The problem I'm running into is that I need the function of my controller called by the click handler remediationSearch to run AFTER the function of the controller called by the formRemote's submission saveEditedIndividualRecord is done executing. But it is happening the other way around. And for some reason the function onSuccess="doResult();" doesn't even execute otherwise I was going to move the following code into its body to make things work the way I want:
<g:remoteFunction controller="customer"
action="remediationSearch"
update="content_area"
params="{rerender: true}"/>
here is how doResult is now:
function doResult() {
console.log("done.");
}
the formRemote is submitted but the doResult function prints nothing to the console.
Seeing as all of the Grails AJAX related tags have been deprecated, I would recommend trying it this way:
Markup:
<form id="editIndivRecForm" onsubmit="return false;">
<!-- add fields here -->
<input type="text" id="uniqueId" value="${something}">
<input type="text" id="secondaryId" value="${something}">
<button id="save" type="button">
</form>
JavaScript:
// Function to update your content_area div
function updateContentArea() {
var params = { rerender: true };
var url = "${createLink(controller: 'customer', action: 'remediationSearch')}";
$.get(url, params, function(data) {
$("#content_area").empty().append(data);
});
}
$("#save").on('click', function() {
// Collect values from form and submit ajax request
// Using name and description for example fields here:
var data = {
name: $("#name").val(),
description: $("#description").val(),
uniqueId: $("#uniqueId").val(),
secondaryId: $("#secondaryId").val()
};
var url = "${createLink(controller: 'customer', action: 'saveEditedIndividualRecord')}";
// Submit the (first) AJAX request
$.ajax({
type: "post",
url: url,
data: data,
success: function() {
doResult();
$('#editIndivRecForm').reset();
updateContentArea();
}
});
}

Categories

Resources