Get the ID from a button which has a dynamic ID - ajax

I can not grasp my mind around this.
I am making a ajax call into a servlet. The problem is, on the page that is displayed, i could have 1-20 different buttons that needs to recall the same servlet. So I have the following form...
<form id="ajax-contact">
<input type="text" value="${item.transactionId}" id="transactionId" name="transactionId"/><br>
<input type="text" value="deliveryReceipt" id="action" name="action"/><br>
<input type="text" value="${item.id}" id="id" name="id"/><br>
<button type="submit" id="${item.id}" class="btn btn-primary" data-toggle="modal" data-target=".${item.id}">view delivery receipt</button>
</form>
In my ajax, I have this...
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
//var formData = $(form).serialize();
var id = $("#id").val();
var tranid = $("#transactionId").val();
var action = $("#action").val();
var dataFromForm = "trannsactionId="+tranid+"&action="+action+"&id="+id;
alert(dataFromForm);
alert(formData);
// Submit the form using AJAX.
$.ajax({
url : "Controller",
type: "GET",
data : dataFromForm,
dataType: "json",
})
.success(function(response) {
...
I am trying to make it so the ajax call uses the params for the specific set of information within the form. How can I do this?
Thanks!
More detail:
Once this page shows, if I have 10 sections on there with a button. When I click on the first view delivery receipt button, it works fine.
If I go down my list and click on t he 8th view delivery receipt, itll make an ajax call for the first form.

Related

AJAX shows different behaviors in an if/elseif-statement which is inside the success function [duplicate]

I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.

Use Form to send Email in Spring Boot using Thymeleaf

I want to implement a send mail form using Thymeleaf.
I have a page called start_page.html that contains this form :
<div class="w3-container w3-padding-64" id="contact">
<h1>Contact</h1><br>
<p>We offer full-service catering for any event, large or small. We understand your needs and we will cater the food to satisfy the biggerst criteria of them all, both look and taste. Do not hesitate to contact us.</p>
<p class="w3-text-blue-grey w3-large"><b>Catering Service, 42nd Living St, 43043 New York, NY</b></p>
<p>You can also contact us by phone 00553123-2323 or email catering#catering.com, or you can send us a message here:</p>
<form th:action="#{~/homePage/contact}" th:object="${contactMail}" method="post" target="_blank">
<p><input class="w3-input w3-padding-16" type="text" th:field="*{nom}" th:placeholder="#{homePage.nom}" required name="nom"></p>
<p><input class="w3-input w3-padding-16" type="text" th:field="*{prenom}" th:placeholder="#{homePage.prenom}" required name="prenom"></p>
<p><textarea class="w3-input w3-padding-16" type="text" th:field="*{message}" style="height: 250px;" th:placeholder="#{homePage.message}" required name="message"></textarea>
<p><button class="w3-button w3-light-grey w3-section" type="submit">[[#{homePage.envoyer}]]</button></p>
</form>
</div>
I have already implemented a controller for this form action
#Controller
#PropertySource(ignoreResourceNotFound = true , value = "classpath:messages.properties")
public class HomePageController {
#Autowired
private MailContactService mailService;
#RequestMapping(value = "/homePage/contact", method = RequestMethod.POST)
public String sendMessage(ContactMail contactMail){
mailService.sendContactMail(contactMail);
System.out.println("done");
return "/home/start_page";
}
}
I'm not getting the desired behavior: I though that my page will stay the same but my page is reloading.
I want to order the controller to do something without getting out of my page.
I googled and I found that I can send a service object to my page but I want to avoid this option if there is other solutions .
Thank you.
You'll need to use an AJAX call if you don't want to refresh your page.
What this means is that you want to intercept the default HTTP form post behavior (that will do a full page refresh) using javascript.
For this you need to :
Remove the action tag on your form (let javascript handle it when clicking the button to submit the form)
Add this to your page (will be executed when the form is submitted :
$(document).ready(function () {
$("#contact-form").submit(function (event) {
// do not post the form and trigger full page refresh
event.preventDefault();
var formData = .. // construct some formData
$.ajax({
type: "POST",
contentType: "application/json",
url: "/homePage/contact",
data: JSON.stringify(formData),
dataType: "json",
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
});
});
For a full example, as always, mkyong.com has got you covered :)

How to make Dojo as generic while submitting a form?

I have the following dojo (ver 1.9) code:
require(["dojo/dom", "dojo/on", "dojo/request", "dojo/dom-form"],
function(dom, on, request, domForm){
var form = dom.byId('user_login');
var selectedTabId = showIdOfSelectedTab();
// Attach the onsubmit event handler of the form
on(form, "submit", function(evt){
// prevent the page from navigating after submit
evt.stopPropagation();
evt.preventDefault();
// Post the data to the server
request.post("login1.php", {
// Send the username and password
data: domForm.toObject("user_login"),
// Wait 2 seconds for a response
timeout: 2000
}).then(function(response) {
dom.byId(selectedTabId).innerHTML = response;
});
});
}
);
And html below:
<form name="user_login" id="user_login">
User name: <input type="text" name="user_name" id="user_name" /><br />
Password: <input type="password" name="user_password" id="user_password" /><br />
<button id="submitbutton" name="submitbutton">Submit</button>
</form>
I want to make the above dojo code as generic by sending the post action (login1.php) and the form id (i.e., user_login). I tried several ways but I could not achieve it.
Please let me know if any of you have idea.
Thanks in advance.
-Uday
This is the demo drom the dojo Tutorial right?
http://dojotoolkit.org/documentation/tutorials/1.9/ajax/
Did you get any Errormessages?
So let's see.
Have you load the dojo libary correct? If not, the widgets can't be loaded.
Must be somthing like:
src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js">
Check the path to the login1.php.
If it's in another Folder than your code the path must be something like "../myfolder /myphp/login1.php"
Regards, Miriam

Reloading main view after button in PartialView is clicked

I have a partial view that the user can preform a search in, and the search results are shown in a select box. In my main view I have a section that is supposed to show the search results after a select button is pressed. Right now when I click the select button is loads the correct information into the correct model for my main view, but the main view doesn't change. When I click refresh, the page updates correctly. How do I make the page update automatically when a button is clicked in the plugin view?
My section in the main view (Index.vbhtml) in my main app:
#Section CUInfo
Credit Union Name: #Model.CUInfo.CUName
end section
Here is my controller method in my Plugin:
Function ChangeCUInfo(strCUName As String) As ActionResult
m_hostApp.CUInfo.CUName = strCUName
m_hostApp.blnPluginRefreshButtonPressed = True
Return View("Index", m_hostApp)
End Function
I've tried to set a boolean value in the hostApp object and then in my main razor view call this function if it is true:
#code
If Model.blnPluginRefreshButtonPressed = True Then
#<script type="text/javascript">
$(function () {
window.location.reload();
});
</script>
End If
Model.blnPluginRefreshButtonPressed = False
End Code
EDIT:
JS function called when the select button is clicked:
function loadCU(CUInfo) {
strCU = CUInfo.split('|');
strCUName = strCU[0];
$.ajax({
type: "POST",
url: "/CUContractNumberPlugin/ChangeCUInfo",
data: { "strCUName": strCUName }
});
}
Form that is used in the plugin view:
#Using (Html.BeginForm("ChangeCUInfo", "CUContractNumberPlugin"))
#<div id="LogoSigSearch" style="height:300px;width:500px;position:relative;">
<span style="display:inline-block;height:20px;width:166px;position:absolute;top:35px;left:5px;">Credit Union Name</span>
<br />
#Html.TextBox("strCUName")
<input type="submit" name="LogoSigSearch$ctl02" value="Search" id="LogoSigSearch_ctl02" tabindex="3" style="width:60px;position:absolute;top:5px;left:352px;" />
<input name="LogoSigSearch$ctl05" type="button" onclick="javascript:clearSearch()" value="Clear" style="position:absolute;top:35px;left:352px;width:60px;" />
<select size="4" name="LogoSigSearch$ctl06" id="LogoSigSearch_ctl06" tabindex="5" style="height:230px;width:342px;position:absolute;top:65px;left:5px;"></select>
<input type="button" name="SelectCU" value="Select" onclick="javascript:loadCU(LogoSigSearch_ctl06.options[LogoSigSearch_ctl06.selectedIndex].value)" tabindex="4" style="width:60px;position:absolute;top:65px;left:352px;" />
</div>
End Using
Are both buttons part of a form? A button won't invoke an action without you attaching it to script or making it part of a form with an associated action.
Use a partial view to render the results of the query, even on the main page load. This simplifies your development.
Add a jQuery event handler (jQuery.on()) to watch for the button click on your main page, or if the button is returned in the partial view, just use an on ready handler in your partial and attach a button.click() event, again using jQuery.
The jQuery event handler can take care of submitting the values of the query, posting to your controller, and displaying the results. I have a number of older articles here but they are still relevant to your question and demonstrate submitting data and fetching partials.
Your client-side code will end up looking something like this:
$("#your-button").click(function () {
var fetchUrl = '#Url.Action("ActionName", "Controller")';
$.post(fetchUrl, { searchParams: $("#your-search-box").val() })
.success(function (data) {
// replace the contents of the DIV with the results. 'data'
// here has whatever you sent back from your partial view
})
.error(function (data) {
// handle the error, use a DIV with some kind of alert message etc
});
});
Hope this helps some.

MVC 3: Why is jquery form.serialize not picking up all the controls in my form?

I am trying to create a situation where if a user clicks on an "edit" button in a list of text items, she can edit that item. I am trying to make the "edit" button post back using ajax.
Here's my ajax code:
$(function () {
// post back edit request
$('input[name^="editItem"]').live("click", (function () {
var id = $(this).attr('id');
var sections = id.split('_');
if (sections.length == 2) {
var itemID = sections[1];
var divID = "message_" + itemID;
var form = $("#newsForm");
$.post(
form.attr("action"),
form.serialize(),
function (data) {
$("#" + divID).html(data);
}
);
}
return false;
}));
});
But the form.serialize() command is not picking up all the form controls in the form. It's ONLY picking up a hidden form field that appears for each item in the list.
Here's the code in the view, inside a loop that displays all the items:
**** this is the only control being picked up: ******
#Html.Hidden(indexItemID, j.ToString())
****
<div class="datetext" style="float: right; margin-bottom: 5px;">
#Model.newsItems[j].datePosted.Value.ToLongDateString()
</div>
#if (Model.newsItems[j].showEdit)
{
// *********** show the editor ************
<div id="#divID">
#Html.EditorFor(model => model.newsItems[j])
</div>
}
else
{
// *********** show the normal display, plus the following edit/delete buttons ***********
if (Model.newsItems[j].canEdit)
{
string editID = "editItem_" + Model.newsItems[j].itemID.ToString();
string deleteID = "deleteItem_" + Model.newsItems[j].itemID.ToString();
<div class="buttonblock">
<div style="float: right">
<input id="#editID" name="#editID" type="submit" class="smallsubmittext cancel" title="edit this item" value="Edit" />
</div>
<div style="float: right">
<input id="#deleteID" name="#deleteID" type="submit" class="smallsubmittext cancel" title="delete this item" value="Delete" />
</div>
</div>
<div class="clear"></div>
}
It's not picking up anything but the series of hidden form fields (indexItemID). Why would it not be picking up the button controls?
(The ID's of the edit button controls, by the way, are in the form "editItem_x" where x is the ID of the item. Thus the button controls are central to the whole process -- that's how I figure out which item the user wants to edit.)
UPDATE
The answer seems to be in the jquery API itself, http://api.jquery.com/serialize/:
"No submit button value is serialized since the form was not submitted using a button."
I don't know how my action is supposed to know which button was clicked, so I am manually adding the button to the serialized string, and it does seem to work, as inelegant as it seems.
UPDATE 2
I spoke too soon -- the ajax is not working to update my partial view. It's giving me an exception because one of the sections in my layout page is undefined. I give up -- I can't waste any more time on this. No Ajax for this project.
You could try:
var form = $('#newsForm *'); // note the '*'
Update
Did you change the argument to $.post() as well? I think I may have been a little too simple in my answer. Just change the second argument within $.post() while continuing to use form.attr('action')
New post should look like this:
$.post(
form.attr("action"),
$('#newsForm *').serialize(), // this line changed
function (data) {
$("#" + divID).html(data);
}
);

Resources