Reload a page after jquery ajax call - javascript

I have a jsp page which displays the details of a student .Based on the student selection from the dropdown box on change event will be fired and retrieve the min and max marks for the student.
<form name="listBean">
<c:forEach var="Item" items="${listBean.nameList}" varStatus="status">
<input type="number"name="nameList<c:outvalue='[${status.index}]'/>.initialMarks"/>
<input type="number" name="nameList<c:out value='[${status.index}]'/>.finalMarks"/>
<input type="submit" value="submit" id="submit" />
MinMarks:<c:out value="${Item.minMarks}"/></c:if>
MaxMarks:<c:out value="${Item.maxMarks}"/></c:if>
</c:forEach>
</form>
After retrieval ,updated data will be stored into the bean.Server request is handled using jquery.ajax() method
function onChange() {
jQuery('form').each(function() {
jQuery.ajax({
url: "http://localhost:9001/submitStudent.do?requestType=auto",
data: $('form').serialize(),
type: 'POST'
});
location.reload();
});
}
Once the server response is successful , i will be reloading the page so that the page will be refreshed with the bean data set during the ajax call.
But it is not displaying the data?What i am doing wrong ?
Or is there any better solution to achieve this?
Any suggestions are welcome .
Thanks

It looks like you are reloading the page immediately after sending the AJAX request, potentially before the server has received and processed it.
You could store your ajax requests in an array and only reload the page when all requests have completed using jquery's when().
function onChange() {
var requests = [];
jQuery('form').each(function() {
requests.push(jQuery.ajax({
url: "http://localhost:9001/submitStudent.do?requestType=auto",
data: $('form').serialize(),
type: 'POST'
}));
});
jQuery.when.apply(jQuery, requests).then(location.reload, errHandler);
}
function errHandler (err) {
// handle any errors
}

Related

Using Ajax to send a request. Despite using preventDefault, the page is reloading

I am writing a Flask App in which I want to be able to use a form to input information into a database without refreshing the page.
Here is my form:
<form id="vocab_form">
<label for="name">Word:</label>
<input type="text" id="word" name="word">
<label for="def">Definition</label>
<input type="text" id="def" name="def">
<input type="submit" value="Add Term">
</form>
Here is the script I am using to send the request. It is embedded in the html file containing the form.
<script>
$(document).on('submit', '#vocab_form', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/',
data:{
word:$(#word).val(),
def:$(#def).val()
},
success:function(){
alert('success');
}
})
});
Here is the route to which I am sending the form data. It calls functions in another file to input the data into my database and to collect some information online with which to render the page.
#app.route("/", methods=["GET", "POST"])
def hello():
if request.method == "POST":
word = request.form["word"]
definition = request.form["def"]
query.add_word(word, definition)
message="Word added successfully! {} means {}".format(word, definition)
else:
message="no form data"
wordlist=query.get_all_words()
lines = web_functions.get_les_mis()
return render_template("home.html", message=message, wordlist=wordlist, lines=lines)
Although my script includes the instruction to prevent the default submit behavior for the form, the page reloads each time I submit the form. I want to prevent this. Any advice or insight would be much appreciated!
Try this instead
<script>
$(document).ready(function() {
$('#vocab_form').on('submit', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/',
data:{
word:$(#word).val(),
def:$(#def).val()
},
success:function(){
alert('success');
}
})
})
});

Not posting jQuery form

I'm trying to post a form via Ajax, and I came across jQuery's POST, which sounds like the propper tool to use. I tried using the following html form:
<form id="my_form" action="http://localhost:4567/pedidos/guardar" method="POST">
Name:<br>
<input type="text" name="person_name"><br>
Amount:<br>
<input type="text" name="amount">
<br>
<input type="submit" value="Submit" id="submit_form">
</form>
<script type="text/javascript">
$('#submit_form').click( function() {
$.post( 'http://localhost:4567/pedidos/guardar', $('#my_form').serialize(), function(data) {
// ... do something with response from server
alert( "Data saved: " + data );
},
'json' // I expect a JSON response
);
});
</script>
This form was built based on this SO answer
I'm expecting to POST the form to /pedidos/guardar. On the server side, to test that the form is properly posted, I created a really small Sinatra script:
require 'sinatra'
require 'json'
not_found do
status 404
"This page could not be found"
end
get '/' do
"Hello World!"
end
get '/pedidos' do
{ :person_name => "#{params[:person_name]}" }.to_json
end
post '/pedidos/guardar' do
#{}"I got #{params[:person_name]}."
{ :person_name => "#{params[:person_name]}" }.to_json
end
When using my form, I'm getting {"person_name":"Juan"}, which is the expected response from Sinatra. But I'm not getting any alert window, it's like no Ajax is being used at all.
What am I missing in my form to make it work with Ajax? Do I need the action and method="POST" there?
Thanks in advance
You are sending your data throw ajax: $.post is a shorthand to $.ajax, but as the documentation explains it, you have to get a reference to the submit event and stop the default action.
$('#submit_form').click( function( event ) {
// Stop form from submitting normally
event.preventDefault();
Try replacing the script with this
$('#submit_form').click( function(){
$.ajax({
url: 'http://localhost:4567/pedidos/guardar',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify($('#my_form').serialize()),
success: function(data){
alert( "Data saved: " + data );
}
});
});
setting the contentType is for the response data type.

call post method without submit button causing infinite loop

I have a form from which I want latitude and longitude and I want want load this without submit button.
<form method="post" id="myform" action="" >
<input type='hidden' value='' name='latitude'/>
<input type='hidden' value='' name='longitude'/>
</form>
I tried
document.getElementById("myForm").submit();
But it causes infinite loop and I want it on the same page so I am not giving action.
I add this function but still not working.
function send_data(lat, lon) {
document.getElementById('place_lon').innerHTML = lat + ' : ' + lon;
// $("input[name='lattitude']").val(lat);
// $("input[name='longitude']").val(lon);
$j = jQuery.noConflict();
$j(document).ready(function() {
$j('#myform').submit(submit_myform);
});
function submit_myform() {
$j.ajax({
url: window.location.href,
type: 'POST',
data: $j(this).serialize(),
dataType: 'json', //data type of Ajax response expected from server
success: myform_success //callback to handle Ajax response and submit to Paypal
});
return false;//prevent normal browser submission, since the form is submitted in the callback
}
function myform_success(response) {
//this is called whenever the ajax request returns a "200 Ok" http header
//manipulate the form as you wish
$("input[name='latitude']").val(lat);
$("input[name='longitude']").val(lon);
// $j('#lattitude').val(lat);
// $j('#longitude').val(lon);
//submit the form (to the form's action attribute)
document.forms['#myform'].submit();
}
}
What happens is that as soon as form is loaded it submits itself, then loads again and submits etc.
Try using AJAX request to send data to the server.
$.ajax({
type: "POST",
url: window.location.href,
data: $('#myForm').serialize()
});

How do I use AJAX to print out data inside a div?

I have two files. One file is named index.php and another file is named process.php.
I have a form that submits to process.php in index.php:
<form class="form" action="process.php" method="POST" name="checkaddress" id="checkaddress">
<table>
<tr class="element">
<td><label>Address</label></td>
<td class="input"><input type="text" name="address" /></td>
</tr>
</table>
<input type="submit" id="submit" value="Submit"/>
</form>
<div class="done"></div>
I also have a process in process.php to echo some data based off of the input. How would I be able to use AJAX to submit the form without leaving the page?
Is it something like:
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.done').fadeIn('slow');
}
});
What page would I put the above code on if it was right?
Also, how do I change the above code to say what the process.php outputted? For example, if I echo "Hello" on process.php, how do I make it say it in the done div?
I have seen many responses regarding AJAX, but they all rely on data that is pre-made like APIs. I need to do a database query and fetch the data dependent on the address entered and print the data out.
You need to collect the data in the form so that you can submit them to the process page, and you need to run your code when submitting the form (and cancel the default form submission)
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = $(this).serialize();
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml) {
// add the returned data to the .done element
$('.done').html( resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
[update]
If you want to modify the data before submitting them, you will have to manually create the parameters to pass to the ajax
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = {};
var address = $('input[name="address"]', this).val();
// alter address here
address = 'something else';
dataToPassToAjax.address = address;
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml ) {
// add the returned data to the .done element
$('.done').html(resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
You could use the jQuery form plugin: http://jquery.malsup.com/form/
Let me know if you want example code.

Keep old returned Ajax data in div instead of overwriting

I am using ajax to update a section of my website, it is all working great at the moment and updating a div with the response data I get back.
However, at the moment it is just replacing the text in the div everytime I keep submitting the ajax form, what I want is for the data to stay and just keep adding on underneath with the data returned from the ajax request. Here is the code
Html
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
<br /><br /><br /><div id="testarea" style="width: 200px; height: 100px; background-color: #9f1717; color: #fff;"></div>
Jquery
$(document).ready(function() {
$("#foo").submit(function() {
var url = "new_shout_ajax_test.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#foo").serialize(), // serializes the form's elements.
success: function(data)
{
//alert(data); // show response from the php script.
$('#testarea').text(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
});
Code in the new_shout_ajax_test.php
$bar = $_POST['bar'];
echo $bar;
Basically I want the data to return like this
Ajax request 1 Data
Ajax request 2 Data
Ajax request 3 Data
Instead of keep getting overwritten by the new data.
.append() is what you're looking for
$(document).ready(function() {
$("#foo").submit(function() {
var url = "new_shout_ajax_test.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#foo").serialize(), // serializes the form's elements.
success: function(data)
{
//alert(data); // show response from the php script.
$('#testarea').append(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
});
Just this :
$('#testarea').append(data); // Append the next data from ajax to the previous

Categories