Submit a form without refreshing page in html, js - javascript

i have a small form chat like this and i want when click submit that form will not make the page refresh.
<form name="form1" method="post" id="formchat" action="forum_add_1313940.xhtml">
<input name="text" id="text2" max-lenght="1000"></input>
<input type="submit" name="submit" class="submit" value="Gửi" id="chats" />
</form>
and the js
<script language="JavaScript">
$('#formchat').submit(function ()
{
sendformchat(); return false;
});
</script>
But when i click "Gửi", the page gonna refresh.
How to make it when click "Gửi", the page not gonna refresh ?

If you want asynchronous behavior, you should handle the form in an AJAX style, you can read about AJAX here!
here is an example using jquery on your form:
var form = $('#form_chat');
form.find('input[type=submit]').on('click', function(e) {
e.prevetDefault();
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function(response) {
console.log(response);
}
});
});

Related

How to autosubmit form with ajax

i m trying to submit my form without any user interaction,i don't know how to do that, do you have a lead for?
Thanks by advance
Below my code
Html form
<form id="myform" method="post">
<div>
<input type="hidden" name="print_names" id="print_names" value="print_names" />
<input type="submit" name="loginBtn" id="loginBtn" value="test" />
</div>
</form>
Ajax part for submit
$(document).ready(function(){
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'form.php',
data: $(this).serialize(),
success: function(response)
{
Your form has no target action, in that caase you could use just:
document.forms.myform.submit();

Submit a form with a file without refresh

Hello guys i don't know to submit a form without page refresh.
This is my code:
My form:
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="submit" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Javascript:
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
How i can modify my code to submit along with text a file towards the mysql db?
Your first issue is in this line:
<button type="submit" name="action" ... />
You have two possibilities:
change type="submit" to type="button"
use event.preventDefault() in your $("#sendbutton21").click(function() {
After, your ajax call can be changed in order to include the file:
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'POST',
processData: false,
success: function(data) {
alert(data);
}
});
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
// for testing...
url = 'https://api.github.com/repositories';
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'GET',
processData: false,
success: function (data) {
console.log(data[0].id);
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="button" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Try https://jquery-form.github.io/form/ plugin to easily send form via ajax sample code:
$('#post123').ajaxForm(function() {
// SUCCESS CALLBACK
});
To submit a form without refresh, use event.preventDefault().
$("#sendbutton21").click(function(event) {
event.preventDefault();
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Instead of
$("#sendbutton21").click(function() {
use
$("#post123").submit(function() {

Ajax Form doesn't remain on page

Been beating my mind at this but its now time for me to ask for help (ask i got work tomorrow and dont want to be on this all night)
My form is inside a modal and this is my script
$(function() {
$("#applyForm").on('submit' , function(e) {
$.ajax({
type: 'POST',
url: $("#applyForm").attr("action"),
data: $('#applyForm').serialize(),
success: function(data){
alert('successfully submitted')},
error: function(data){
alert('something went wrong')
}
});
});
});
It all works, It fires up the script and submits to the backend with a success message but as soon as you close the popup sucess message it redirects to the action "apply-now" page.
How can i prevent this without it breaking the submit, As i've tried return false and preventDefault.
Heres the form
<form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="hidden" value="1">
<input name="listing_id" type="hidden" value="{$listing_id}">
MY FORM DATA
<button type="submit" id="submit" class="btn btn-warning">Apply now</button>
Any help would really be appreciated !
Thanks
J
The form is being submitted twice. Once with the form action and the other time with the ajax call. If you prefer to have only the ajax call sent, returning false outside the ajax function should do the trick. When to use PreventDefault( ) vs Return false?
$(function () {
$("#applyForm").on('submit', function (e) {
//e.preventDefault();
$.ajax({
type: 'POST',
url: $("#applyForm").attr("action"),
data: $('#applyForm').serialize(),
success: function (data) {
alert('successfully submitted')
},
error: function (data) {
alert('something went wrong')
}
});
return false;
});
});
Try this if you want the page not to reload:
$(function() {
$("#applyForm").on('submit' , function(e) {
e.preventDefault();
//... the rest of your code
//or add return false;
return false;
});
});
As you catch the actual submiting the "normal" process will happen, you don't wan't that. So you have to stop it by e.preventDefault(). You can read the documentation about it here.
Or look right here for an example where it stays on the same page.
$("#form").submit(function(e){
e.preventDefault();
$(this).append("The page is staying here");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form">
<input type="text" name="first" id="first">
<input type="submit" value="enter">
</form>
Hopefully this helps you.
I Hope this work.
1) <button type="submit" id="submit" class="btn btn-warning">
Apply now</button> with preventDefault method
2) button type="button" id="submit" class="btn btn-warning">Apply now</button>
change the type="submit" to type="button"
Example
<form action="/apply-now/" enctype="multipart/form-data" id="applyForm" method="post" name="applyForm" class="form">
<input name="is_data_submitted" type="text" value="1">
<input name="listing_id" type="text" value="999">
MY FORM DATA
<button type="button" id="submit" class="btn btn-warning">Apply now</button>
</form>
$(document).ready(function(){
$("#applyForm").on('click','#submit' , function() {
alert("Click check")
console.log($('#applyForm').serialize())
});
});
You're not preventing the default form submission behavior. To fix up, add the following immediately before your Ajax call:
e.preventDefault();
Extra tip: to ensure the form only gets submitted once per "submit" click, stop the propagation of the click event from bubbling up through the DOM.
Immediately following the preventDefault, put this:
e.stopPropagation();

Stop form from redirecting on submit

I'm very aware that this question has been asked several times but I have tried at least 6 solutions and it has not worked. I'm collecting data to send to a google form but on form submission the browser redirects to a success page. I'd like for it to all happen using AJAX but my code isn't working.
HTML:
<form id="userinfo" method="get" action="https://script.google.com/macros/s/xxx/exec" accept-charset="UTF-8" onsubmit="return false">
<input type="text" name="name" id="formname" placeholder="Name">
<input type="text" name="email" id="formemail" placeholder="Email">placeholder="Game Days">
<input type="submit" value="submit" id="upload_data"/>
</form>
JS:
$("#userinfo").submit(function(e) {
var urll = "https://script.google.com/macros/s/xxx/exec"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: urll,
data: $("#userinfo").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
You could use the jQuery Form Plugin to send the form without doing a submit.
Your code should look kinda like this:
$("#userInfo").ajaxSubmit({
success: function(data)
{
alert(data); // show response from the php script.
}
});

Repopulating div with new form/content using jQuery/AJAX

Are there any jQuery/AJAX functions that when a form (or anything for that matter) is displayed, upon pressing a button the div containing the original form is replaced by a new form? Essentially, a multi-part form without having to reload the page.
Can I use something like this?
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
//somehow repopulate div with a second form?
}
})
return false;
});
I've used this before for adding items to a list, but I've never used it to totally repopulate it with different content. How can I direct it to the second form?
edit - I got it to work, but only when I write '#form2' for the replacement. I alerted the response and I get {"formToShow":"show2"}. I tried doing response.formToShow but it's undefined.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
<div id="divName">
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1" value="1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2" value="2"/>
<input type="submit" name="submit2"/>
</form>
</div>
<script>
$('form#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'JSON',
url: 'receiving.php',
data: $(this).serialize(),
success: function(response) {
$('#form1').hide(); //hides
//$('#form2').show(); //this will show
$(response.formToShow).show(); //this does not display form 2
}
})
return false;
});
</script>
Here is receiving.php. When I view this page {"formToShow":"show2"} is displayed
<?php
echo json_encode(array("formToShow" => "#form2"));
?>
Check the JQuery Load Function
This is personal preference, but I'd never send HTML through the response and display it like that, what I'd do is:
Send a JSON array back from the server, such as { formToShow: "#form1" }
Then you can simply do this:
success: function(response) {
$('form').hide();
$(response.formToShow).show();
}
Obviously, using this method, you'd also have to have the second form in your markup like this:
<form method="POST" action = "#" id="form2" style="display: none">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>
You'd also have to change (to pickup the array):
$.ajax({
type: 'JSON'
try this
$('form#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
type: '',
url: '',
data: $(this).serialize(),
success: function(response) {
$('#divName').html(response);
$('#form1').hide();
$('#form2').show();
}
})
return false;
});
<form method="POST" action = "#" id="form1">
<input type="textbox" name="textbox1"/>
<input type="submit" name="submit1"/>
</form>
<form method="POST" action = "#" id="form2" style="dispay:none;">
<input type="textbox" name="textbox2"/>
<input type="submit" name="submit2"/>
</form>

Categories