Want to auto refresh my form without page reload - javascript

I have a Ask Question form by which client can ask any question to us. While client submit the form we will give him a thanks message for 5 seconds then hide the message and show again the Ask Question form in that div.
But while the from comes after successful message, form input values is still there. I want a fresh from without any input value like the form before submitting.
Here is my ajax code
$.ajax({
url:"{{ url('/ask_question_form') }}",
type: 'GET',
data: {_token :token, name : name, email : email, contact : contact, question : question},
success:function(msg){
// console.log(msg);
$('.question-modal .textwidget').hide();
trHTML = "";
trHTML += "<div id='user-question' style='margin-top:50%; color:#0071BC'>";
trHTML += "Thanks for your question. We will save your question for further query and give a feedback as soon as possible.";
trHTML += "</div>";
$('.question-modal').append(trHTML);
setTimeout(function() {
$('.question-modal #user-question').remove();
$('.question-modal .textwidget').show();
}, 5000);
}
});
Where textwidget is the class name of that form

The best solution is-
$("#form")[0].reset();
use this code when your success message comes.

After completing 5 seconds and when you hide the "success message" at that time you can reset your form
$("#formId").get(0).reset();
Here "formId " id of your form.

Erase values of all fields once you successfully submit the form.
document.querySelector('get-your-field1').value = '';
document.querySelector('get-your-field2').value = '';
document.querySelector('get-your-field3').value = '';
document.querySelector('get-your-textarea').value = '';
Or you can use form reset.
const form = document.querySelector('form');
const btn = document.querySelector('button');
btn.addEventListener('click', event => {
event.preventDefault();
form.reset();
});
<form>
<input />
<input />
<button type="submit">submit</button>
</form>

Here is an example to do a form reset function:
function reset(){
setTimeout(function(){
var form = document.getElementById('myForm');
form.reset();
}, 1000);
}
var btn = document.getElementById('btn');
btn.onclick = function(){
reset();
}
<form id="myForm">
<input value="" />
<br />
<input value="" />
<br />
<input value="" />
<br />
<input value="" />
<br />
<button id="btn" type="button">reset</button>
</form>

Please note, that it seems that you are using some token along with the form.
This means, that if you reset the values, this token will still be there,
and maybe the server will not accept the next form submission, due the duplicate use of that token.
You will need to set a new token, when the server respond.

Related

How to redirect users based on what they type in an input?

I have a form like this:
<form method="POST">
<input type="url" placeholder="Enter URL Address">
<input type="submit" value="go!">
</form>
And I want users to be redirected to a URL based on what they wrote in the URL input when they click the submit button.Is it possible?
Like this
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
var url = this.url.value;
if (url) location=url;
return false;
}
}
using
<form id="form1">
<input type="url" placeholder="Enter URL Address">
<input type="submit" value="go!">
</form>
You can check out the window.location for this specific case. You can throw any string in there and the browser will redirect to that page.
EDIT:
You do not need a whole form for that. The form is used to send data to the server - the thing you want here is client-sided and does not require a form. You can use a simple input field with a simple button that fires a bit of javascript code.
Yes jane it is possible. You can do that by javascript or php.
example on javascript:
// Put an id on your form and change the id below accordingly
var idForm = 'form';
var form = $('#' + idForm);
form.submit(function(e) {
e.preventDefault();
var redirectTo = form.find('input').val();
switch(redirectTo) {
case "INPUT_VALUE_EXAMPLE":
window.location = 'YOUR URL HERE';
break;
case "google"
window.location = 'http://www.google.com'
break;
}
});

Can't set the submit type input in a form created with Java Script

I am working on a project where I have to carryout CSRF on a web page. So when the user is logged in and when he clicks on my webpage, I have to post with his username(derived from the cookie) .
I tried creating my own form using the following code , So that when the user clicks my webpage, this form will post into post.php(target webpage)
<html>
<script language="javascript">
function blah() {
alert();
var theForm, newInput1, newInput2, newInput3;
var bla = "Aaada";
var bla2 ="POST";
// Start by creating a <form>
theForm = document.createElement("form");
theForm.action = "http://targeturl/post.php";
theForm.method = "post";
newInput1 = document.createElement("input");
newInput1.type = "text";
newInput1.name = "username";
newInput1.value = bla;
newInput2 = document.createElement("textarea");
newInput2.name = "message";
newInput2.value = bla;
newInput2.id = "message";
newInput3 = document.createElement("input");
newInput3.type = "submit";
newInput3.name = "post_submit";
newInput3.value = bla2;
newInput3.id = "post_submit";
theForm.appendChild(newInput3);
theForm.appendChild(newInput2);
theForm.appendChild(newInput1);
theForm.submit();
}
blah();
</script>
</html>
Title, Message and Submit button are the three inputs in the target form.
When I try running this form, the submit button alone is not set. I am not able to understand why. I tried an actual form in html (with ) and posted it to the target URL, it works .
But since I have to be stealthy, I have to manually build the form , like the code I have posted. I tried all posssibilites and I am not able to nail the actual reason why this variable is not setting.
PS:
if (isset($_POST['post_submit'])) {
is the check in target page
and below id the target form :
<form method="post" action="post.php">
Title: <input type="text" name="title" maxlength="50"/>
<br />
<br />
Posting:
<br />
<br />
<textarea name="message" cols="120" rows="10" id="message"></textarea>
<br />
<br />
<input name="post_submit" type="submit" id="post_submit" value="POST" />
</form>
(It posts to itself, I have not included the remaining code of target)
Any help would be appreciated
Thanks
If you trigger the click event instead of the submit event, you'll get the submit button as well, so replace
theForm.submit();
with
newInput3.click();
add document.body.appendChild(theForm); in java script
before submit and enclose your function call as :
window.onload = function() {
blah();
}
else you will get document.body is null error in js

Prepopulate and submit hidden form

I have a form and here's the handler for the submit button:
$( '#submit_btn' ).click( function( data ){
theForm = document.getElementById( 'realForm' );
theForm.meetingName.value = document.getElementById( 'meeting_name' ).value;
theForm.meetingId.value = '';
theForm.description.value = document.getElementById( 'mtg_description' ).value;
theForm.startTime.value = startDate + ' ' + startTime;
theForm.endTime.value = endDate + ' ' + endTime;
theForm.loginName.value = participants;
theForm.role.value = roles;
theForm.docRights.value = docRights;
theForm.submit();
});
This handler basically pre-processes some data and sends to a hidden form, this:
<form id="realForm" style="visibility:hidden" action="/app/meeting/create" method="post">
<input name="loginName" type="text">
<input name="meetingName" type="text">
<input name="meetingId" type="text">
<input name="startTime" type="text">
<input name="endTime" type="text">
<input name="description" type="text">
<input name="roles" type="text">
<input name="docRights" type="text">
</form>
Problem is that the request isn't hitting the endpoint defined in the hidden form. What am I doing wrong here?
I've changed to make the input types hidden instead of the form. The submit handler certainly executes and, using FireBug, I don't see the request going out under the NET tab.
I'm using this dummy data to try and trigger the request but it's still not working:
theForm.meetingName.value = "MY MTG";
theForm.meetingId.value = '';
theForm.description.value = "DESC";
theForm.startTime.value = "2013-05-25 00:00:00";
theForm.endTime.value = "2013-05-25 02:00:00";
theForm.loginName.value = "foo#frr.com";
theForm.role.value = "M,M";
theForm.docRights.value = "CRUT,CRUT";
I'd try this out:
document.forms.realForm.submit()
2 tips:
use this for fetching variable from input.
$("#NAME_OF_YOUR_INPUT_ID").val();
use hidden input instead and identify each one with ID.
<input id="docRights" type="hidden">
The problem is that my first form had a button with type = "submit"...so that was submitting the form even though I didn't want it to.
I had to change the type to "button" in order to prevent that from happening.
Thanks for all the prompt responses.
Your input name is roles not role.
Change your line of JS to:
theForm.roles.value = roles;
See JS Fiddle: http://jsfiddle.net/jav6s/

Jquery post function not working with two forms and two post requests

I was trying to add a second form to a javascript/jquery script that I wrote, however, when i implemented and began testing it, when I would try to send the firm form via a jquery post request, it would instead send a get request. I know that this has to do with the second form, because commenting the script out for the second form makes the site work again. Hopefully a pair of fresh eyes can help!(the loadpage function works as well)
The register function seems to be where the problem is:
//when the user first goes to the page
$(document).ready(function(){
var user = $("#username");
var pass = $("#password");
var submit = $("#submit");
//both of these methods work, I'm not sure if one is better than the other
//$("#submitbutton").click(function(event){
$("#loginform").on('submit', function(event){
event.preventDefault();
$('.loginerror').remove();
$.post("login.php", {username:user.val(), password:pass.val()}, function(data){
if(!data)
{
$("#login").append("<h3 class='loginerror'>Incorrect Username or Password</h3>");
}
else
{
loadpage();
}
}, "json");
});
//if the user clicks the username prompt him with the login div
$("#registerbutton").click(function(event){
register();
});
});
function register()
{
$("#login").hide("slow");
$("#registerdiv").css("display", "block");
//initiate some variables
var regusername = $("#regusername");
var reg1password = $("#reg1password");
var reg2password = $("#reg2password");
var regemail = $("#regemail");
var regfirstname = $("#regfirstname");
var reglastname = $("#reglastname");
//TODO: check to make sure form is filled out properly
$("#registerform").on('submit', function(event){
event.preventDefault();
//send post request
$.post("register.php", {regusername:regusername.val(), password1:reg1password.val(), password2:reg2password.val(), email:regemail.val(), firstname:regfirstname.val(), lastname:reglastname.val()}, function(data){
if(!data)
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
else
$("#registerdiv").hide("slow");
$("#loginiv").slidedown("slow");
}, "json");
}
And here's the HTML with the two forms:
<body>
<Div id="welcome"> Welcome </div>
<Div id="login">
<br><br><h2>Welcome to QuotesLib</h2>
<br><br><br><form id="loginform"> Username:
<input type = "text" name = "username" id ="username"> <br> Password:
<input type = "password" name = "password" id = "password"> <br>
<input type = "submit" name="submitbutton" id="submitbutton" class = "bluebutton">
</form>
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
</Div>
<Div id="registerdiv">
<br><br><h2>Sign Up For QuotesLib</h2>
<br><form id="registerform"> Username:
<input type ="text" id="regusername"> <br> Password:
<input type ="password" id="reg1password"> <br> Repeat Password:
<input type ="password" id="reg2password"> <br> First Name:
<input type ="text" id="regfirstname"> <br> Last Name:
<input type ="text" id="reglastname"> <br> email:
<input type ="text" id="regEmail"> <br>
<input type ="submit" id ="registersubmitbutton">
<br> </form>
</Div>
It would be super helpful if someone could give me an answer to this question!
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
should be
$("#registerdiv").append("<h3 class='loginerror'>Server error, retry</h3>");
see the difference:
<h3>... and <h3 ...
The code has some mistakes,
first,
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
You are having a form open tag but not a close tag, the form tag even not needed for this button, and that was the main reason for the problem
second, the end of the JS code,
}, "json");
}
should be
}, "json");
});
}​
I'm not sure whether you missed while copying,
Third,
The <h3> tag within the append method, though it is not the matter for the problem you are having.
It is better to use some text editors which hi-lights the code open, end tags, braces.
Here the working code

jQuery (or just JS) choosing from multiple form submit buttons in onSubmit function

I've got a form that has multiple submit buttons. One for changing data in a database, one for adding, and one for deleting. It looks like this:
<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)">
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()">
<!-- Here I have a php code that produces the listing menu based on a database query-->
</select>
<br />
Price: <input type="text" name="price" id="price" value="0"/><br />
Remarks: <textarea name="remarks" wrap="soft" id="remarks"></textarea><br />
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/>
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/>
<br />
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/>
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/>
</form>
There are actually more elements in the form, but that doesn't matter. What I want to know is, for my validation method, how can I check which submit button has been clicked?
I want it to do the following:
function validate(form){
if (the 'add new listing' or 'update listing' button was clicked'){
var valid = "Are you sure the following information is correct?" + '\\n';
valid += "\\nPrice: $";
valid += form.price.value;
valid += "\\nRemarks: ";
valid += form.remarks.value;
return confirm(valid);}
else {
return confirm("are you sure you want to delete that listing");
}
}
I assume there must be some way to do this relatively easily?
Why don't you set a global variable specifying which button was last clicked? Then you can check this variable in your validate method. Something like:
var clicked;
$("#upbtn").click(function() {clicked = 'update'});
// $("#delbtn").click(function() {clicked = 'delete'});
// ...
function validate(form) {
switch(clicked) {
case 'update':
break;
// more cases here ...
}
}
You can, for example, attach a click event to every submit button that will save a pointer to it in a variable or mark it with a specific attribute / class (it that case you will have to remove that marker from all other submit buttons in the event handler) and then in the submit callback you will know which one was clicked
I think it's easier to just use a click event on each button and handle it individually.
$(function() {
$('input[name=someName]').click(someFunc);
});
function someFunc() {
// Your validation code here
// return false if you want to stop the form submission
}
You could have a hidden field on a form and set the value of that field on clicking the button and then pick it up in your validation routine. You can use jquery to achieve this, let me know if you require an example.
You can use ajax submission with jQuery, you can try something like this:
$('form#addform input[type="submit"]').on('click',function(e){
e.preventDefault();
var current = $(this); //You got here the current clicked button
var form = current.parents('form');
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:form.serialize(),
success:function(resp){
//Do crazy stuff here
}
});
});

Categories