Jquery Ajax call to servlet - ajax

I am trying to make an Ajax call using JQuery to a servlet that returns a JSON object.
In the JSP page I have a form, at first I didn't know how the get the data from the form,
then I found .serialize.
I have the following JavaScript:
$(document).ready(function() {
$("#submit").click(function blabla() {
var formData = $('form').serialize();
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
});
});
});
The information comes from the following form:
<form method= post">
<div class="searchCiteria">
<div id="searchValueBlock1">
<div><span class="label">Case ID:</span><input type="text" name="messagecaseid" size="25"/></div>
<div><span class="label">Onderwerp:</span><input type="text" name="messagesubject" size="25" /></div>
<div><span class="label">Afzender:</span><input type="text" name="messagesender" size="25"/></div>
<div><span class="label">Ontvanger:</span><input type="text" name="messagereceiver" size="25"/></div>
</div>
<div id= "searchValueBlock2">
<div><span class="label">Datum:</span><input type="text" name="date1" size="25"/></div>
<div><span class="label"></span><input type="text" name="date2" size="25"/></div>
<div class="submit">
<input type="submit" value="Search">
</div>
</div>
</div>
</form>
When I use the action parameter in the form the servlet repondes like it should.
But I can't seem to get the Ajax call to work.
What am I doing wrong?

you must add the success param to ajax function
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});

The default behavior of the submit button is to POST the form, which will redirect the user to a URL of the action attribute ond the form. When you don't(which you should...) have an action attribute it will reload the page. To prevent the page from reloading you need to prevent the default behavior by returning false at the end of your $("#submit").click function.

Related

Sending form data through ajax to spring controller is not working

Here is my js code. This will trigger on click of add button and will post the form manually through ajax.
function addRow()
{
var form = $('#fortForm')[0];
var data = new FormData(form);
$.ajax({
type:"POST",
enctype:"multipart/form-data",
url:"${pageContext.request.contextPath}/admin/meeting/saveBlockMom?
${_csrf.parameterName}=${_csrf.token}",
data: data,
processData: false,
contentType:false,
cache: false,
success:function(data){
alert(data);
},
});
}
The jsp code. This contains the form code need to be submitted
<div class='row'><form:form id="fortForm" method="post" modelAttribute="mom" enctype="multipart/form-data">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
<div class='col-md-3'>
<label>hgkk</label><input type='hidden' name="blockName" id="blockName" path='blockName' value="sadsa"/></div><div class='col-md-3'><span>Whether PBG is fortfieted</span>
<label for='Yes'>Yes</label><input type='radio' id='yes_1' name='fortpbgrad_' value='yes' onChange='showFunction()'/><label for='No'>No</label>
<input type='radio' id='no_' name='fortpbgrad_' value='no' onChange='hideFunction()'/>
</div><div class='col-md-3' id='hideBlock_'><input type='text' placeholder='Enter Forfeit Percentage' id="fortPercentage" name="fortPercentage" path='fortPercentage'/></div>
<div class='col-md-3'><label for='Remarks'>Remarks:</label><input type='text' path='Remarks' id='Remarks' name="Remarks"/></div>
</form:form></div>
</div>
<button type="button" style="float:right;" onclick="addRow()">Add</button>
And the Controller in action. Data is not being transmitted to the object blockmom .
#RequestMapping(method=RequestMethod.POST, value="/saveBlockMom")
public String saveBlockMom(#ModelAttribute("blockmom") blockmom blockmom)
{
logger.info("******************You are in function saveBlockMom***********************");
/* blockmom.setBlockMomId((long) 100);*/
service.saveBlockMom(blockmom);
return "redirect:/admin/meeting/meetingList";
}

can i refresh a table from presently showing model-popup

I need to reload a table or div inside a model popup continuously, i failed with my code can you help me....
i tried with ajax ..code is below but its is not updating chats (i am doing a chat task)
**My Ajax code to check new message is or not**
function check_msg()
{
$.ajax({
type: "POST",
url: "<?php echo site_url('member/check_message')?>/",
datatype: "JSON",
success: function(data) {
data = JSON.parse(data);
if(data.MsgStatus == "1")
{
$('#newchat').ajax.reload();
} });}
**HTML**
<div class="modal-body form">
<form action="#" id="chatform" class="form-horizontal">
<input type="hidden" value="" name="UserId"/>
<div class="form-body">
<div class="container" id="container">
<table id="newchat">
<div class="Scroll" id="Scroll">
<div id="messagesout"></div>
</div> </table> </div</div>
function reload_table()
{
table.ajax.reload();
}
Use this code in your ajax and call it

Posting form using AJAX

can anyone please help me with sending the below form using Ajax. All I want is to send it to the trolley1.php page for processing, no call backs or anything like that. Basically replicate the form but sending it with Ajax so the page does not go to the trolley1.php page. I have tried so many methods but have not been able to do this. Bill Gates or Steve Wozniak if you guys are reading this, please help
This gives me a console $.Ajax is not a function in the console
<script>
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
}
});
});
</script>
<?php
echo "
<div class='col-sm-3 mt-5'>
<form class='ajax' method='post' action='trolley1.php?action=add&id=$id'>
<div class='products'>
<a>$img</a>
<input type='hidden' name='id' value='$id'/>
<input type='hidden' name='name' value='$product'/>
<input type='hidden' name='price' value='$price'/>
<input type='text' name='quantity' class='form-control' value='1'/>
<input type='submit' name='submit' style='margin-top:5px;' class='btn btn-info'
value='Add to Cart'/>
</div>
</form>
You have one syntax error in your JS Code - see correct code
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
});
});
});
And you are using jQuery as additional javascript libary. jQuery uses $ to access the methods (e.g. $.ajax) Thats the reason why you get undefined as error.
So you need to load the libary first at the beginning of your page (inside <head>). E.g. directly from their CDN
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Then it should work for you

Bootstrap modal email form

I've searched for an answer but could not find any. Maybe someone here can point me to the right direction.
I have a simple modal form (bootstrap). It's meant to work like this.
You enter the form and click Send. The form-info is sent to e-mailadress. When mail is sent new modal with confirmation is displayed.
I've tried to implement this solution: Bootstrap Modal ajaxified
So far i have this:
The modal:
<div class="hide fade modal" id="input-modal">
<form class="form-horizontal well" data-async data-target="#input-modal" action="/some-endpoint" method="POST">
<fieldset>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<label>Name</label>
<input id="name" type="text" placeholder="Type your name...">
</div>
<div class="modal-footer">
Cancel
<button type="submit" class="btn btn-primary" value="send"/>Send</button>
</div>
</fieldset>
</form>
The Javascript:
jQuery(function($) {
$('body').on('submit','form[data-async]', function(event) {
alert('submit Event');
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(data, status) {
$target.html(data);
}
});
event.preventDefault();
});
});
But I need help with sending the input by mail and also sent info back to modal as a confirmation.
I've tried to solve this by myself for several days now, but now I've given up.
If you're using jQuery >= 1.5 look at the documentation here. This will provide you with a place to handle your new modal when the AJAX call returns. So your code would look something like this.
jQuery(function($) {
$('body').on('submit','form[data-async]', function(event) {
alert('submit Event');
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
}).done(function(data){
//pop your modal here
$('#your-new-modal').modal('show')
});
event.preventDefault();
});
This is assuming you plan to send the email server side as you can't send it from Javascript. In your example you would have changed the HTML content of the tag to the data returned from the AJAX call instead of opening a new modal. You can find documentation on opening the new modal via Javascript here.
Did not run this so there may be typos.

how do I add an ajax response to my form without adding a new js file?

I have this simple submission form and I want to "ajaxify" it so the user isn't redirected to this page thanks.php after submission. I want the content from thanks.php to respond and show inside the div.
What jquery code will plug right into this to show the response.
<div ><form method="post" action="http://domain.com/thanks.php">
<input type="text" placeholder="Enter Email" name="email" id="email" >
<input type="submit" name="submit" value="Submit" ></form></div>
I would give 'form' and 'div' a class or id so it is not so generic, but this should work.
$("form").submit(function (){
$.ajax({
url: "http://{url}/thanks.php",
type: 'POST',
data: {email: $("#email").val()},
success: function ( data ) {
$("div").html(data);
}
});
return false;
});

Resources