I have the below code that is supposed to autosubmit(save) a form with the name "project" when the user is idle. This is code I found on a tutorial website(forget the name), I tried it and it only refreshes the page?
<!-- Set auto save timeout in milliseconds
<script type="text/javascript">
attachEvent(window,'load',function(){
var idleSeconds = 5;
var idleTimer;
function resetTimer(){
clearTimeout(idleTimer);
idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
}
attachEvent(document.body,'mousemove',resetTimer);
attachEvent(document.body,'keydown',resetTimer);
attachEvent(document.body,'click',resetTimer);
resetTimer(); // Start the timer when the page loads
});
function whenUserIdle(){
document.project.submit();
window.location = location.href;
}
function attachEvent(obj,evt,fnc,useCapture){
if (obj.addEventListener){
obj.addEventListener(evt,fnc,!!useCapture);
return true;
} else if (obj.attachEvent){
return obj.attachEvent("on"+evt,fnc);
}
}
</script> -->
Form Code :
<form name="project" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="invoice-form" method="post" class="invoice-form" role="form" novalidate>
This is the code that is refreshing the page window.location = location.href; Try removing it.
And you also need to make sure your form's attribute name is replacing "project" in document.project.submit();.
For example
<form name="test_form"></form>
document.test_form.submit();
Edit:
Alright, the the function should just be
function whenUserIdle() {
document.project.submit();
}
Rather than doing an actual form submission, consider doing an AJAX request:
function whenUserIdle(){
var formData = {}; // assemble the form data here
$.post( "/form-submission-route", formData, function( responseData) {
// do something with result, if you like
// perhaps clear the form or throw up a notification
});
}
Related
This question already has answers here:
Form Submit Execute JavaScript Best Practice? [closed]
(3 answers)
Closed 11 months ago.
When I press the Submit button of a form it runs a php file which stores the answer to a db.
Is it possible to use the Submit button of a form to submit the user's choice and immediately after that run a function without further actions from the user?
For example, in the following simple form and php, how can I run a function when the user presses Submit?
<form action="db.php" method="post">
A:<input type="radio" name="answer" value="A">
B:<input type="radio" name="answer" value="B">
<input type="submit" name="submit value="submit">
</form>
<?php
$con = mysqli_connect('localhost','my user id','my password');
if(!con) {
echo 'not connected to server';
} else {
echo 'something else is wrong';
}
if(!mysqli_select_db($con,'my user id') {
echo 'Database error selection';
}
if (isset($_POST['submit'])) {
$answer=$_POST['answer'];
$sql = INSERT INTO test1 (columnName) VALUES ('$answer');
mysqli_query($con,$sql); // Execute query
}
?>
As an example let's take the following function which is a part of a larger file.
function next() {
var qElems = document.querySelectorAll('#questions>div');
for (var i = 0; i < qElems.length; i++) {
if (qElems[i].style.display != 'none') {
qElems[i].style.display = 'none';
if (i == qElems.length - 1) {
qElems[0].style.display = 'block';
} else {
qElems[i + 1].style.display = 'block';
}
break;
}
}
}
You can add an onsubmit event handler to the form
<form action="db.php" method="post" onsubmit="functionToCall()">
which will call the given function when the form is submitted. If you want to stop the form from being submitted, return false from the function. As #JokerDan said, you can also use AJAX within your function and omit the form action altogether.
function functionToCall() {
// Do something before you submit your form (save data locally or whatever)
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200) {
//Do something after submitting the form (if you want to change the page or redirect)
}
};
http.open('POST', 'db.php');
http.send(/*send post data here*/);
}
If you want to send data with the AJAX request, you will have to pull it from the form and put it in the http.send() line in the same format you pass data in the URL (data=answer&submit=true)
The proper way to do this, is to first select your form using something like document.querySelector or document.getElementById (only possible if the form element has an id).
var form = document.querySelector('[action="db.php"]');
After you selected your form, use the addEventListener of your form to add an evenListener.
form.addEventListener('submit', myListener, false);
Now you'll just need to create a function that looks like this :
function myListener(event) {
// DO STUFF
}
Here, event is an object of type Event that provides more information about the form you submitted. This function will be called every time you try to submit your form!
I am having a page with a form on it that should use AJAX to save and load data to a file.
JavaScript
This is the java script I am using:
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
$.get( "showForm.php", { loadConfig: this.text} )
.done(function( data ) {
$('#configFormContainer').html(data);
});
});
HTML for a-tags
The class .configFile in the second function refers to a list of a-Tags. When I click on of of those, the script successfully loads the content from a file and displays it. This is the html for the mentioned a-Tags:
<div class="list-group">
<a href="#" class="configFile>config.json</a>
<a href="#" class="configFile>config_1504987517.json</a>
</div>
This part is working fine: The javascript-function is triggered. In showForm.php the config file is loaded. It is re-building the complete form with the content from the file.
HTML for the form
Whats not really working is the trigger on the submit-function. This is the form-html
<form id="saveConfigForm" method="POST">
<a bunch of form elements />
<button name="submit" class="btn btn-success" type="submit" id="saveConfig">Speichern</button>
</form>
Whats the problem
So, whats happening now:
When I load the page initially, I click the submit-Button and get the alert. This trigger .submit() is working.
When I click one of the a-tags to load a config-file, the file is being loaded without refreshing the page. This trigger .click() is working, too.
After that: When I click the submit-button, the page is being reloaded. The trigger .submit() is not working.
And after this "unwanted" reload of the page, the .submit()-trigger is working, again.
I have no clue what it is wrong here. Hope someone can help
cheers
Though this isn't your whole code set, I took what you posted and made a page. I could click either of the .configFile links, then click the submit button and I get the alert.
However I did close both class attributes of the .configFile elements with a ". I don't know if that's the difference. But, if it isn't then it's something that's occurring after the ajax request which of course I can't simulate with this code.
<html>
<body>
<div class="list-group">
config.json <!-- //added " to end of class attribute -->
config_1504987517.json <!--//added " to end of class attribute -->
</div>
<form id="saveConfigForm" method="POST">
<a bunch of form elements />
<button name="submit" class="btn btn-success" type="submit" id="saveConfig">Speichern</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
if (window.XMLHttpRequest)
{
// AJAX for IE7+, Chrome, Firefox, Safari, Opera
xmlhttp = new XMLHttpRequest();
} else {
// AJAX for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
$('#configFormContainer').html(xmlhttp.responseText);
}
}
xmlhttp.open("GET","showForm.php?loadConfig=" + this.text, true);
xmlhttp.send();
});
});
</script>
</body>
</html>
The other thing that would be curious to me: Open the browser's developer console and paste in your submit binder again:
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
If your submit works after that, I'd suggest either binding the click event again after the new html is rendered. Or, binding the event to $(document) like:
$(document).on('submit', '#saveConfigForm', (e) => {
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
As a final note, I'm not trying to augment your code any more than necessary to help with the specific issue you're having. As another user commented, it would be cleaner to use the jQuery functions since you're using jQuery. But I don't take that as part of your question.
I kind of found out whats causing the problem: The ajax-call returns the html-form and put it to the form-container.
After this, the trigger to that form is gone, because the trigger was connected to the form, that I am overwriting with the ajax-data.
Quick'n'dirty
It will work, when I reset the trigger like that. But this looks more like quick'n'dirty
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
$.get( "showForm.php", { loadConfig: this.text} )
.done(function(data) {
$('#configFormContainer').html(data);
// re-init the trigger on "submit" here
// ------------------------------------
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
});
});
});
Clean-Fix
I needed to adjust the the showForm.php. If it's being called from the ajax-method, it will only return the form elements, not the form itself.
If it is being called from the scratch, it returns the complete form.
Furthermore, the java script now replaces the content of the form-element, not it's container. This way the trigger does not get lost.
$(document).ready(function(){
$("#saveConfigForm").submit(function (e)
{
e.preventDefault();
var formData = $(this).serialize();
alert(formData);
});
$(".configFile").click(function() {
if (this.text == '' && this.text == 'undefined')
{
return;
}
$.get( "showForm.php", { loadConfig: this.text} )
.done(function(data) {
$('#saveConfigForm').html(data);
});
});
});
Just for the sake of completeness, this is the main part of the showForm.php now:
<?php
if (!isset($_GET['loadConfig']))
{
// do not return the complete form to prevent losing the trigger on it
echo '<form id="saveConfigForm" method="POST">';
}
echo '<a bunch of form elements />';
if (!isset($_GET['loadConfig']))
{
echo '</form>';
}
i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>
Tried to retrieve page url (Jforms EMAIL option) after form submission but form_data:page_url
variable doesn't produce any output at the email.
form_data:page_title doesn't either. There is a Javascript which I believe retrieve URL. I have tried to use Alert(vhref) at the bottom of the script and it return URL pointing to the existing form at the popup window. I need it to be URL of submission result form which is automatically appear (Redirect to->Submitted data 'event') on the screen after form submission. My objective is to have this URL to be included into the email sent. Joomla 3.4.3 , JForms 0.4.4
BR
oleg
<script language="javascript" type="text/javascript">
//Secure the user navigation on the page, in order preserve datas.
var holdForm = false;
window.onbeforeunload = function closeIt(){ if (holdForm) return false;};
jQuery(document).ready(function(){
jQuery("#<?php echo $formHash ?>").validationEngine();
/* var vhref = jQuery(location).attr('href',"submission/submissiondetails/"+"&cid"), */
var vhref = jQuery(location).attr('href'),
vtitle = jQuery(this).attr('title'),
hrefInput = jQuery("#<?php echo $formHash ?>").find('[name="jform[page_url]"]'),
titleInput = jQuery("#<?php echo $formHash ?>").find('[name="jform[page_title]"]');
if(hrefInput.val() == ''){
hrefInput.val(vhref);
}
if(titleInput.val() == ''){
titleInput.val(vtitle);
}
});
So I have this code to POST data with PHP and AJAX without redirecting page, I'm using the same script on the login page. The login page works like a charm but the other pages don't. The only diffeence between these is that login php script page uses if (empty($_POST) === false) {} and the other pages use if (isset($_POST['save-settings'])) {}. I don't know what do to.. Here below is the script I'm using.
HTML BUTTON
<input id="save-settings" class="submit" type="submit" name="save-settings" value="Save" onclick="return false;" />
JS SCRIPT
$(document).ready(function() {
$("#save-settings").click(function() {
var name = $("#webname").val();
var charset = $("#webchar").val();
var meta = $("#webmeta").val();
var description = $("#webdesc").val();
var startsite = $("#webstartsite").val();
var starturl = $("#webstartsiteurl").val();
var footer = $("#webfooter").val();
$.post("../lib/action.php", {
name: name,
charset: charset,
meta: meta,
description: description,
startsite: startsite,
starturl: starturl,
footer: footer
}, function(data) {
$("#gy-main-notification-bar").hide().html("<h1>!</h1><h2>" + data + "</h2>").slideDown(500);
setTimeout(function() { $("#gy-main-notification-bar").slideUp(500) }, 2500);
});
});
});
PHP SCRIPT
if(isset($_POST['save-settings'])) {
$updatesettings = "UPDATE `settings` SET
`name`='".escape($_POST['webname'])."',
`charset`='".escape($_POST['webchar'])."',
`meta`='".escape($_POST['webmeta'])."',
`description`='".escape($_POST['webdesc'])."',
`startsite`='".escape($_POST['webstartsite'])."',
`starturl`='".escape($_POST['webstartsiteurl'])."',
`footer`='".escape($_POST['webfooter'])."'
WHERE `id`= 1";
if ($update_settings = $db_connect->query($updatesettings)) {}
echo 'Success!';
}
I don't really want to change the isset to empty in the script due the fact that I have all my "onclick" script in one action.php file. When I remove onclick="return:false;" from input it works.. I'm so confused I appriciate any help!
Click event handler function can have event argument. When you catch this argument you can use preventDefault() method. With this method default action of click will be prevented and page won't be refreshed.
Change
$("#save-settings").click(function() {
var name = $("#webname").val();
to
$("#save-settings").click(function(ev) {
ev.preventDefault();
var name = $("#webname").val();
You Forgot to include the post save-settings. You probably should've included it with the ajax post like this:
$.post("../lib/action.php", {
'name': name,
'charset': charset,
'meta': meta,
'save-settings': true,
'description': description,
'startsite': startsite,
'starturl': starturl,
'footer': footer
},
change this in your sql statement for the correct posts
`name`='".escape($_POST['name'])."',
`charset`='".escape($_POST['charset'])."',
`meta`='".escape($_POST['meta'])."',
`description`='".escape($_POST['description'])."',
`startsite`='".escape($_POST['startsite'])."',
`starturl`='".escape($_POST['starturl'])."',
`footer`='".escape($_POST['footer'])."'
WHERE `id`= 1";
writing onclick="return false" in HTML cancels the execution of the javascript code. just delete this onclick="..." and add preventDefault() like this to prevent form submittion
$("#save-settings").click(function(e) {
e.preventDefault();
.....