Why is my html form clearing the page contents after ajax? - javascript

The code should work something like this...
https://jsfiddle.net/Harout360/yhqoadqx/7/
But instead the form post does get correctly processed, then it redirects to the "/" url given as the action url in ajax. I can't figure out why it is redirecting, and if I place a console.log in the ajax it doesn't print to console.
HTML
<form method="post">
<input type="hidden" name="title" value="${title}" />
<button type="submit" value="Submit" id="sub-button" data-loading-text="Loading..." data-complete-text="Submitted!">
Submit
</button>
</form>
Javascript
$(document).ready(function() {
$("button[id=sub-button]").click(function(e){
e.preventDefault();
var button = $(this);
var form = $(this.form);
var form_data = form.serialize();
var form_method = form.attr("method").toUpperCase();
console.log('subscribing...');
$.ajax({
url: "/",
type: form_method,
data: form_data,
success: function(){
button.button('complete');
}
});
});
});
Java Servlet
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String title = req.getParameter("title");
Database.addTitle(title);
}
UPDATE
The Javascript works now because my problem was assigning the function to buttons that didn't exist at the time that document.ready loaded. Instead I now assign the .click to the button when it was actually loaded onto the page. Also I changed button's type to button, removed the id and now use $(.movie) to identify the button by its class.
Updated fiddle to give slight understanding of new approach https://jsfiddle.net/Harout360/yhqoadqx/11/
New Issue
Now the problem is that button.button('complete') is not doing anything. Any guesses as to why?
UPDATE 2 (Solution to new issue)
setTimeout(function() { button.button('complete'); }, 500);

Related

Get input field value in same page without refreshing page php

I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}

Get result back after form submit

I need a quick help.
I want users can upload a csv file. Then I do some parsing and meaningful things with the file in the back. Finally, display the results back to users. When they upload the file, I would like to check to see if the file size is <= 250kb or contains <= 1000 lines.
In JSP:
<form action="/Project/CSVUpload" method="post" enctype="multipart/form-data">
<br />
<input id="uploadfilebutton" type="file" name="file" class="tss-btn tss-btn-blue" accept=".csv" required />
<br />
<input id="processfilebutton" type="submit" value="Process File" class="tss-btn tss-btn-blue" />
</form>
So there is an upload button and a submit button. How can I get a status back after users click the submit button? For example, if the process fails I want to display an pop up error message.
In JavaScript:
function process()
{
$.ajax({
url:"/Project/CSVUpload",
type:'POST',
contentType: 'application/json',
dataType: 'json',
success:function(soapContents){
if (soapContents.haserrors)
{
BootstrapDialog.show({
title: 'Process File Failed',
message: soapContents.returnmessage,
buttons: [ {
label: 'Ok',
action: function(dialogItself){
dialogItself.close();
}
}]
});
}
}
});
}
This works when I don't use form. The form is required because enctype has to be like that.
In Java:
#WebServlet("/CSVUploads")
public class CSVUpload extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
boolean hasErrors = false;
if (CSVUpload success) // assume we get the info from CSVUpload class
{
hasErrors = true;
}
if (hasErrors)
{
log.error("CSVUpload: "+returnMessage);
// Setup JSON response.
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("haserrors", hasErrors);
jsonObjectBuilder.add("returnmessage", returnMessage);
JsonObject jsonObject = jsonObjectBuilder.build();
// Write the JSON out as a response.
PrintWriter printWriter = response.getWriter();
printWriter.print(jsonObject);
printWriter.flush();
}
}
So I made some changes and add a new java class to handle the ajax query... it submits twice, first submit is getting the form info and second submit is checking for a success... I don't know if anyone has better idea, but this is what I change to make it work. It sounds not a good idea, but it works for now. If anyone has better idea please let me know, a working sample will be great.
Use button instead of submit. It is because submit type input is submitting the form, but you also send request using ajax. That's the reason of two requests.

ajax call response is forwarded to new html page on browser

I am trying to write a ajax call in response I am passing back a html string
I am setting this html string as div content. it is working but once the div is updated request is forwarded to new page. I am unable to figure it out.
here is the html code -
<div id="basicdetailsdiv" class="row"><br>
<form:form id="basicdetailsform" method="post" modelAttribute="basicdetailform" action="updatebasicdetails"><br>
<div class="col-sm-6"><br>
..... ...... .....<br>
...... ..... .... <br>
<div id="editbasicsavediv" class="col-xs-5 control-label"> <a id="editbasicsavelink" class="btn vd_btn btn-xs vd_bg-yellow"> <i class="fa fa-pencil append-icon"></i> Save </a> </div>
</form:form>
<div>
.js code
jQuery("#editbasicsavelink").click(function () {
jQuery.ajax({
type: "POST",
url: "updatebasicdetails.xml",
dataType: "html",
data: $("#basicdetailsform").serialize(),
success: function (response) {
alert(response);
alert(response.responseHtml);
alert(response.responseText);
$("#basicdetailsdiv").html(response);
//element.innerHTML = resp.responseText
alert("Details saved successfully!!!");
// XMLHttpRequest.abort();
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
so once the page is updated with response, then request forwards to a new url
localhost:8080/test/updatebasicdetails
this page has same html response what I am receiving from ajax call response.
where I am making mistake????
method code -
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String processForm(#Valid com.mrg.form.BasicDetailsForm bdForm, Model model, HttpServletRequest request
) {
System.out.println("basic details save start");
// service call here to read entity object from db which is data
model.addAttribute("basicdetailform", bdForm);
return getBasicDataResponse(data);
}
getBasicDataResponse(data) is private method which returns a string. data is jpa entity object. inside method stringbuilder to set the values in html string and returns a whole html string with new value.
thnx for your help.
it was my stupid mistake, i missed to remove a js method
inside which on same link click i was submitting the form.
so after executing the given ajax call it was executing that another block and hence submitted the form..what an idiotic mistake. forgive me for that! thnx all.
Try this one
jQuery("#editbasicsavelink").click(function (e) {
e.preventDefault();//this will stop page from refreshing
jQuery.ajax({
//ajax code
)}
});
Check the type of your button ( id = "editbasicsavelink" ). If the type is "submit", change it to button.
(Or)
Add "return false;" in the callback function to prevent the form submission.
Your callback is not getting bound to the html element I guess.. make sure to bind it after the document is completely loaded. add id=editbasicsavelink to your button and make sure to call event.preventDefault() as it'll stop the default action.
jQuery(document)
.ready(function() {
jQuery("#editbasicsavelink")
.on('click',function(event) {
jQuery.ajax({
//ajax code
});
});

Prevent page reload and redirect on form submit ajax/jquery

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.

$.ajax won't access url

I'm trying to send some data via jquery and $.ajax to a php file. When the page loads, a list of names is retrieved from "bewohner_func.php". This works.
At the end of the list is a form, which is used to add a new Name onto the list. It uses $.ajax to send the data, also to "bewohner_func.php", using a switch to differntiate from displaying or adding the data-. Problem is, when I try to send the form, the script does not include the php file. I can safely say that it's not the php file's fault, as I reduced it to an alert.
$(document).ready(function()
{
$("#bew_new").submit(function()
{
var frmData = $("#bew_new").serialize();
$.ajax({
url: "bewohner_func.php",
data: frmData,
success: function(msg)
{
$('#bewohnerliste').fadeOut(400);
$.get("bewohner_func.php", {'bew_new': '0'}, function(data){
$("#bewohnerliste").html(data);
});
$('#bewohnerliste').fadeIn(400);
}
});
return false;
});
});
This is the code for displaying, which does it's job fine:
$(document).ready(function()
{
$.get("bewohner_func.php", {'bew_new': '0'}, function(data){
$("#bewohnerliste").html(data);
});
});
The form:
<form id="bew_new" class="bew_form" action="bewohner_func.php" method="get">
<input name="anrede" size="6" value="Anrede" onFocus="if(this.value=='Anrede')this.value=''">
<input name="name" value="Name" onFocus="if(this.value=='Name')this.value=''">
<input name="wohnbereich" size="2" value="WB" onFocus="if(this.value=='WB')this.value=''">
<input type="submit" value="Neu anlegen">
</form>
It sounds like you are running your submit handler code on page load before form is loaded. If so, submit handler won't be bound to form if it doesn't exist.
You can delegate the handler to an eleemnt, or the document itself, that will be permanent asset in page
TRY:
$("#bewohnerliste").on('submit',"#bew_new",function(){
var frmData = $(this).serialize();
$.ajax......
})

Categories

Resources