onclick jquery to submit form without reloading the page - javascript

hey guys so this page im trying to create has tabs with the names of months for each tab and the content of the tabs is a form and a submit button. The problem im facing is, for example, if im on the February tab and i have filled in the form and when i click submit the page reloads(the data inserted into database) and goes back to the first tab which is January. how do i stop that from happening? meaning after clicking on submit and data is inserted successfully it still stays on the February tab. i read that i have to use tag with onClick attribute but thats it. my knowledge of javascript is minimal.
part of the tab with content:
<div class="tabContent" id="feb">
<form method="post" action="income.php">
<input type="hidden" name="feb" value="February">
<center><h2>February </h2></center>
<div>
<div style="height:0px;">
<div class="rmtotal">
<h3>Your Total Income :</br> RM <input type="text" id="febtotal"
name="febtotal" size="11" readonly value="<?php if(#$fsql) {echo
htmlentities(#$fprev['total']);} if(isset($_POST['febtotal']))
{echo htmlentities($_POST['febtotal']);}?>" ></h3>
</div>
<input type="submit" value="Save" class="save" name="febsave">
<button type="submit" class="prev" name="febprev" id="button"
onClick="">Select from previous Month</button>
</div>
<table border="1" rules="groups" cellpadding="10px;" class="tableincome">
<thead>
<th>Monthly Salary</th>
<th></th>
<th>RM</th>
</thead>
<tr>
<td>Basic Salary</td>
<td></td>
<td><center><input type="text" class="feb" placeholder="0"
name="febbasic" size="11" value="<?php if(#$fsql) {echo
htmlentities(#$fprev['basic']);} if(isset($_POST['febbasic'])){echo
htmlentities($_POST['febbasic']);}?>"></center></td>
</tr>
</table>
</form>
</div>
</div>

You can write a custom function that will be executed when someone clicks the submit button.
That function needs to return false to prevent the default behavior.
For the function itself I would use Ajax to send an asynchronous request to the server that can store the data in the database. If you use jQuery it will be very easy to use Ajax:
function handleClick(){
//send the data to the server
$.post(/*...see jQuery documentation*/)
//prevent the form from submitting and the page from reloading
return false;
}
EDIT: Or just follow the posted link :D, just saw it has the same solution

Related

Update table as soon as a new database table row is inserted

So I want to know how I should make a table, written in PHP 8, that updates as soon a new insert has been made in the database table (SQL Server 2019). I've created a simple table like this:
<table>
<thead>
<tr>
<th>header1</th>
<th>header2</th>
<th>header3</th>
</tr>
</thead>
<tbody>
<tr>
<td>text1.1</td>
<td>text1.2</td>
<td>text1.3</td>
</tr>
</tbody>
</table>
Then I've added a button that creates some input fields, and when these are submitted, the data is inserted into the database. But the only way I know to update the table is to reload the page so the table now has the new row. But I've seen websites that do this without reloading the site, and want to know how? My guess is to make some kind of listener, but how I dont know.
the submit button with some inputs could be something like this:
<form>
<input type="text" id="html" name="fav_language" value="">
<label for="html">HTML</label><br>
<input type="text" id="css" name="fav_language" value="">
<label for="css">CSS</label><br>
<input type="text" id="javascript" name="fav_language" value="">
<label for="javascript">JavaScript</label>
<input type="submit" value="Submit">
</form>
All this should just be pure self written code, not JQuery or something like that.
If you want your forms to submit without reloading, you should use AJAX.
E.g. Almost all of the chat boxes in the websites use AJAX to submit information.
I think this question will help you.
If you want to use AJAX with PHP you can simply make AJAX to call your PHP file for submitting information.
Look at this page to learn more.
If you want to use AJAX without any library you can do that with XMLHttpRequest. more info

How to create redirect link in html or php with hidden constant credential?

Please help me to make redirect link or link which will perform the following activities.
The given code is:
<html>
<body>
<div class="loginDiv">
<div id="divack"></div>
</br>
<form id="login" onsubmit="return submitForm();" name ="login" >
<table>
<tr>
<td>Username </td><td><input type="hidden" id="txtUsername" name = "username" value="guest" />
</tr>
<tr>
<td>Password </td><td><input type="hidden" id="txtPassword" name= "password" value="guest1234"/>
</tr>
<tr><td><input type = "submit" id="btnSubmit" name="Login" value ="Login"/></td></tr>
</table>
</form>
</div>
</body>
</html>
In the code on button click event it will redirect to some other page after checking credential from the database.
But I want to open direct on login page with particular fix credential which display some data in a grid.
So let consider the given code of login.html
when page is loaded on button click event it will redirect to some other page like home.html after checking credential from the database. According to the user access it will display some information.
Suppose, guest is one user and his password is guest1234
So instead on two manual redirection, I want all on one link.
So please help me to solve this problem.

Redirecting after form submission in Javascript

I hope someone can assist with this. I dont have access to the website backend, so I cant change the js script uploaded there. What I am trying to achieve is make a simple form to submit an issue report and then display a "Thank you" popup and redirect back to main page of the account on our page.
So I can make a form no problem. I copied one of the functioning forms by going to Edit link and clicking on Show Source in Page Body. But I can't stop the default behavior of it going to another page after Submit button is pressed. I suspect it is in js script on the back end. I'll copy code below.
<center>
<b>App Issues Report Form</b>
<br>
</center>
<form action="/Modules/SendForm" method="post" class="form" id="NewForm">
<input name="formFields" value="CONTACTID,AgentName,Notes" type="hidden">
<input name="formLabels" value="Contact ID:,Agent Name:,Notes:" type="hidden">
<input name="fromAddress" value="no-reply#callcenter.com" type="hidden">
<input name="toAddress" value="name#CallCenter.com" type="hidden">
<input name="subject" value="A new message about app" type="hidden">
<input name="emailMsg" value="The following data has been collected:" type="hidden">
<input name="CONTACTID" value="##CONTACTID##" type="hidden">
<input name="companyId" value="##COMPANY_ID##" type="hidden">
<div class="clearfix">
<label>Agent Name:</label>
<div class="input"><input id="AgentName" name="AgentName"
class="validate[required] xlarge" value="##LOGGEDIN_AGENT_FIRST_NAME##
##LOGGEDIN_AGENT_LAST_NAME##" type="text">
</div>
</div>
<div class="clearfix">
<label>Notes:</label>
<div class="input"><textarea id="Notes" name="Notes"
class="validate[required] xxlarge"></textarea>
</div>
</div>
<div class="clearfix grey-highlight">
<div class="input no-label">
<input class="button blue" value="Submit" type="submit">
<input class="button grey" value="Reset" type="reset">
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("NewForm").click(function( event ) {
alert( "Thank you for your feedback" );
event.preventDefault();
});
});
</script>
It used to have only this at the end when I copied the code:
<script type="text/javascript">
$(document).ready(function () {
new setupAjaxForm('NewForm'); });
</script>
I tried searching and suggestions here didnt seem to work:
How to redirect user to another page after Ajax form submission
How to redirect user to another page after Ajax form submission?
http://learn.jquery.com/about-jquery/how-jquery-works/
The first thing you have to look at is action="/Modules/SendForm" - this is what does the redirection. If you don't want to redirect, set this to the name of the page you have the form. Obviously there is a whole lot more to forms and redirection (and some other js code might influence this too, nonetheless we don't see what the function setupAjaxForm is supposed to do here), but this is really the first thing to check / get right.
EDIT: I think I understand it more now: basically if you don't have access to the /Modules/SendForm page (where most probably, among others, like form validation, the redirection also happens, then you can't do much to change the redirection.

Current tab is moving to first tab after page refresh or form submitting

How can I stop to redirect other tab when refreshing the browser?
<div class="tab1">User Details
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</table>
</div>
<div class="tab2">Add User
<form action="" method="post">
<p><label for="name">Name</label><input type="text" name="username"></p>
<p><label for="email">Email</label><input type="email" name="email"></p>
<input type="submit" name="submit" value="add"/>
</form>
</div>
When I click on the submit button, Form is submitting but redirecting to the first tab.
Please suggest appropriate JavaScript or jQuery code.
Without a server side script this would not be realizable. Another way would be to not refresh the page while submitting the form:
How to enable the second tab after the completion of the first tab validation
Prevent form redirect OR refresh on submit?
Submitting a form without refreshing the page
I'm not sure which exact JavaScript you use to make the second tab visible in the first place (because you're not saying what library you use), but if you're reloading the page anyway, you can use a flag in the URL to indicate that you want to end up on tab 2.
<form action="#tab2" method="post">
(and you should also have an id="tab2" in the right place to prevent confusion for some browsers)
Then in the onload function of the page, check if the href contains '#tab2' and if so, make tab 2 visible.

Form not submitting when pressing enter

I have the following HTML/JS/jQuery Code. This code represents a login form that is presented modally to the user to allow them to login. The problem is, when I hit enter, the form does not seem to execute the "onsubmit" event. When I click the button as the bottom of the form (which has virtually the same code as the onsubmit event), it works perfectly. I am wondering if anyone can tell me why this form isn't submitting..? Any assistance would be appreciated.
jQuery Code to Show Login Modal:
showDivAndFocus('loginModal','loginaccount');
function showDivAndFocus(v,t){
if (api)
if (api.isOpened)
api.close();
api = $('#'+v).overlay({
mask: {color: '#000000'},
top:'0px',
api: true,
autoScrollToActive: false,
autoScrollOffset: 0
}).load();
document.getElementById(t).focus();
}
HTML Code
<div class="modal" id="loginModal">
<h2>User Login</h2>
<br />
<form action="javascript:void(0);" onsubmit="return(doLogin());" name="loginForm" id="loginForm">
<table width="95%" cellpadding="4" cellspacing="4">
<tr>
<td class="regw" align="left"><b>Account Number:</b></td>
<td class="regw" align="left"><input type="text" maxlength="10" size="10" name="loginaccount" id="loginaccount" /></td>
</tr>
<tr>
<td class="regw" align="left"><b>Username:</b></td>
<td class="regw" align="left"><input type="text" maxlength="20" size="20" name="loginusername" id="loginusername" /></td>
</tr>
<tr>
<td class="regw" align="left"><b>Password:</b></td>
<td class="regw" align="left"><input type="password" maxlength="20" size="20" name="loginpassword" id="loginpassword" /></td>
</tr>
<tr>
<td class="regw" align="left"><b>Remember Me:</b></td>
<td class="regw" align="left"><input type="checkbox" name="loginremember" id="loginremember" /></td>
</tr>
<tr><td colspan="2">
<div>
<center>
<table><tr><td width="50" valign="middle">
<div id="loginLoading" style="height:24px;width:24px;"></div>
</td><td>
<button onclick="doLogin();" type="button" class="ok">Submit</button>
</td><td>
<button onclick="api.close();" type="button" class="cancel">Cancel</button>
</td><td width="50"> </td></tr></table>
</center>
</div>
</td></tr>
</table>
</form>
</div>
AJAX Call
function doLogin(){
var ajax = getXmlObject();
var f = getFormVariables();
var url= '/login.php?f=' + encodeURIComponent(f);
if (ajax.readyState == 4 || ajax.readyState == 0) {
ajax.open("POST", url, true);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
var a = ajax.responseText;
if (a=="OK"){...} else {...}
}
};
ajax.send(null);
}
return false;
}
I was struggling with this same issue; one of my forms was submitting when pressing "enter" in the text fields with no problem; another, similar, form on the same page wouldn't submit at all, for the life of me.
Neither field had a submit button, and neither was using javascript to do any submission.
What I found, is that when there is only a single text field in a form, pressing 'enter' in the text field will automatically submit; but if there is more than one (regular (i.e. single-line) text input) field, it does nothing, unless there is also some kind of 'submit' button.
Apparently this is part of the HTML 2.0 specification:
When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.
An old, but apparently still valid, and interesting, further discussion here.
... evidently meant as a convenient way to submit simple queries, but reducing the risk, on a complex form, of prematurely submitting it while trying to fill it in. Numerous browser implementers (e.g Netscape, Opera, various versions of Lynx,...) followed this advice, though it seems with slightly different interpretations.
I made a JSFiddle to demonstrate. As far as I can tell (lazily just testing with Chrome), the form will submit on "Enter" if there's only one text field, or if there's a submit button, even if it's hidden.
(EDIT: I later found that it also does seem work if there are other input fields which are not a regular, single-line text input ... e.g., textareas, selects, etc. -- thanks to #user3292788 for that information. Updated the JSFiddle to reflect this).
<h2>Form with one text field only, no submit button</h2>
<p>Seems to submit automatically when pressing 'enter' in the first text field</p>
<form action="" method="post">
<div>
<label for="pt-search-input">Search</label>
<div>
<input name="term" type="text" placeholder="Example: budapest amsterdam" /> cancel</div>
</div>
</form>
<h2>Form with two text fields, no submit button</h2>
<p>Won't submit when pressing 'enter' in the forms ...</p>
<form action="" method="post">
<div>
<label for="pt-search-input">Search</label>
<div>
<input name="term" type="text" placeholder="Example: budapest amsterdam" />
<input name="term2" type="text" placeholder="Example: budapest amsterdam" /> cancel</div>
</div>
</form>
<h2>Form with two text fields and a submit button ...</h2>
<p>Now it submits with 'enter' key</p>
<form action="" method="post">
<div>
<label for="pt-search-input">Search</label>
<div>
<input name="term" type="text" placeholder="Example: budapest amsterdam" />
<input name="term2" type="text" placeholder="Example: budapest amsterdam" /> cancel
<input type="submit" />
</div>
</div>
</form>
<h2>Form with two text fields and a HIDDEN submit button ...</h2>
<p>Seems to work, even with submit hidden ...</p>
<form action="" method="post">
<div>
<label for="pt-search-input">Search</label>
<div>
<input name="term" type="text" placeholder="Example: budapest amsterdam" />
<input name="term2" type="text" placeholder="Example: budapest amsterdam" /> cancel
<input type="submit" />
</div>
</div>
</form>
<h2>Form with no action or method attribute, HIDDEN submit button ...</h2>
<p>Even this seems to work.</p>
<form>
<div>
<label for="search-input">Search</label>
<div>
<input name="term" type="text" placeholder="Example: budapest amsterdam" />
<input name="term2" type="text" placeholder="Example: budapest amsterdam" /> cancel
<input type="submit" />
</div>
</div>
</form>
<h2>Form with multiple fields, but only one text input, no submit button.</h2>
<p>This seems to work as well.</p>
<form action="" method="post">
<p><input type="text" ></p>
<textarea name="" id="" cols="30" rows="10"></textarea>
<p>
<select name="" id="">
<option value="">Value</option>
</select>
</p>
</form>
You have two choices:
Create an event handler for the enter button and add it to your bindings.
Use an <input type=submit> in the form somewhere, which is what gets the automatic Enter Key behavior you're after.
It can also come from a javascript bind to a <button> in your form. For exemple, if you have
<button id='button'>Reset</button>
<span id="textToReset">some info</span>
<script type="text/javascript">
$('#button').bind('click', function(){
$('#textToReset').text('');
return false;
})
</script>
Your Enter button will be caught somewhere by the return falseand your form won't submit under Enter key. The correct way is to specify that the <button> ACT as a button. This way :
<button id='button' type="button">Reset</button>
and drop the return false you've putted there to prevent that button from submitting a form. ;-)
For the sake of learning, <button> type is by default submit. If you want them to act as control for your form, you must specify the type="button" or type="reset" See w3.org about it
Just in case someone makes the same mistake as me and also comes here looking for an answer:
If you have two (or more) submit buttons1 in your form, hitting enter will only trigger the first submit and not the second.
1 as indicated by #paul-daoust in his comment on the answer of #g-d-d-c: Both <input type=submit> and <button type=submit> will work as a submit button
If you have correct input-submit-button but use (click) event on that button, it will not trigger it on enter. It will submit form but not trigger click event on button, obviously. Putting functionality to form itself and it's submit event will make it work.
I also want to add, that if you have nested <form>'s, then only <input> directly in form will fire submit on enter, input's in nested forms does not work.
<form submit="onSubmit">
<input type="text" name="submits-on-enter" />
<form submit="onSubmitNested">
<input type="text" name="DOES-NOT-submit-on-enter" />
</form>
<button type="submit">SAVE</button>
</form>
Also, make sure there is one and only one submit button in the form.
i.e. a single
<input type="submit">
statement
This is applicable even if you are hiding or showing it using JavaScript.
If for some reason you have multiple submit buttons in your form, the only available approach is to listen to submit events using JavaScript.
When you have more than one button specified in your form, if they dont have the attribute type specified but they have a tabindex with higher precedece, the first of those buttons will be triggered them before thebutton[type=submit]. Therefore, you should add the type=button to such buttons. Ex.:
<!-- inputs -->
<button type="button">action 1</button>
<button type="button">action 2</button>
<button type="submit">Submit form</button> <!-- With "Enter" this one will be triggered-->
There's another reason that's not mentioned in the other answers.
In Google Chrome (but not iOS Safari, etc.) it triggers the click event on buttons and inputs that have type="submit", and if any handler on that event calls preventDefault() (or return false; in jQuery) then it actually cancels the form submit!!
So when you press <Return> while focused in an input element, that's inside a form that has a such a button, please go to the developer console and check out all the Event Listeners. Remove them one by one, and try to press <Return>. If this fixes the issue, you know which event handler messed it up for you.
Took me an hour of debugging to realize this!!

Categories

Resources