Execute PHP function with Javascript onClick without page refresh - javascript

My research is pointing me to Ajax and/or JQuery, but I wanted to ask to make sure I understand and move in the right direction.
I've been looking to use a javascript onclick function to create a popup(alert) asking to confirm that I want to proceed and show the changes I'm about to make.
I hoped that I could use PHP $_POST or GET to echo the change in the popup/alert window. However without the page refresh it appears I can't do this, but looking for a confirmation? Should I be looking for Ajax to do this? Any thoughts/suggestions would likely give me a head start as php/ajax is sort of foreign to me.
Sample code:
<script>
function clicked() {
if (confirm('Do you want to submit? <?php if(isset($_POST['city'])){$city = $_POST['city'];echo $city;}?>'))
{
yourformelement.submit();
} else {
return false;
}
}
</script>
</head>
<form action="output.php" method="post">
<input name="city">
<input type="submit" onclick="clicked();" value="Button" />
</form>
</html>

You can get the input value with jQuery before submitting:
<form action="output.php" method="post" id="form">
<input name="city" id="city_input">
<input type="submit" value="Button" />
</form>
<script>
$('#form').submit(function(e) {
e.preventDefault();
let cityInputVal = $('#city_input').val();
if (confirm('Do you want to submit ' + cityInputVal + '?'))
{
this.submit();
} else {
return false;
}
});
</script>
The preventDefault() function stops the form submission and therefore, page refresh.

Related

fill and submit form using javascript from console

Here is my form:
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" >
</form>
And need to fill it from console.
just to use it in my app,
Will inject javascript with data to local html file.
I tried to make the form without a submit button like so:
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
</form>
<script>
htmlString.oninput = function(){
///do some stuff
}
</script>
</body>
Expecting that :
document.getElementById('htmlString').value="moo" ;
It automatically submit the form, because here oninput used.
But it just stayed filled with inputs and not proceed further.
Tried with other solution:
form = document.getElementById("myForm")
form.submit()
But it just refreshed the page and not submitted the form.
The need is just one filed without else, and inject my string to it with javascript to run functions embedded in the html.
Try making the input button hidden.
<body>
<form id="myForm">
<input id="htmlString" type="text" name="htmlField" ><br>
<input type="Submit" value="Submit" style="display: none" >
</form>
<button onclick="simulateConsole()">Try it</button>
<script>
htmlString.oninput = function(){
if(this.value === "moo") {
myForm.submit();
}
}
// This event will be triggered even if you use console
htmlString.onsubmit = function(){
if(this.value === "moo") {
// do something onSubmit
}
}
function simulateConsole() {
// you can simulate this in console
htmlString.value = "moo";
myForm.submit();
}
</script>
</body>
I hope it helps.
You need to supply an action to the form, otherwise it will just reload the page.
See more here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

Avoid multiple onload submit

I'm trying to use function onload="submit()" on my form, but when the page loads, it does it multiple times. The result is there, but how can I stop the loop? How can I use it only once? Here's my code:
<script type="text/javascript">
function submit() {
if (!sessionStorage.getItem("submitted")) {
sessionStorage.setItem("submitted", "true");
document.post.submit();
}
}
</script>
<body onload="submit()">
<form method="post" id="post" name="post">
//stuff here
<input id="submit" type="submit" value="Valider" name="test" class="submit">
</form>
Is there anything i'm doing wrong? Or there's any better way to make it?
Thank you for your time and help!
Use sessionStorage to remember if you've already submitted the form, so you don't do it again.
function submit() {
if (!sessionStorage.getItem("submitted")) {
console.log("submitting");
sessionStorage.setItem("submitted", "true");
document.getElementById("post").submit();
} else {
console.log("already submitted, not repeating");
sessionStorage.removeItem("submitted");
}
}
Also, don't use name="submit" and id="submit" for the submit button. See "Submit is not a function" error in JavaScript

cancel in confirm function submitting form in javascript

Got a form that requires users to input an amount to donate. On clicking submit, a function is called and the function is meant to display the amount specified and prompt the user to confirm if the amount typed is the actual amount or not.
The Cancel option in the Confirm() keeps submitting the form instead of returning false.
function donationFormSend(){
get_donation_amount = document.getElementById("get_donation_amt").value;
if(get_donation_amount != ''){
return confirm("You have specified "+get_donation_amount+" as the amount you wish to donate. \n\n Are you sure you want to proceed with the donation?");
}
else{
alert("Amount must be specified to process your donation.");
return false;
}
}
<form method="post" action="">
<div>
<div>Donation Amount:</div>
<input name="amount" type="text" id="get_donation_amt" required="required" />
</div>
<input name="donation_submit" type="submit" id="Submit" value="Proceed" onclick="return donationFormSend();" />
</form>
Jsfiddle link
Would be pleased getting help with this.
I updated your jsfiddle so it's in the expected format (loading the js in the head) and returning the confirm result
return confirm('blah blah')
works perfectly well for me in FF! Just make sure you clear your cache and reload your page.
A way to do do it might be:
form :
<form id='test' method="post" action="">
<div>
<div>Donation Amount:</div>
<input name="amount" type="text" id="get_donation_amt" required="required" />
</div>
<input type="submit" value="submit" onClick="form_submit(this.value)">
<input type="submit" value="cancel" onClick="form_submit(this.value)">
</form>
javascript:
document.getElementById('test').addEventListener('submit',function (event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
})
form_submit= function (submited_by) {
if(submited_by == 'submit'){
alert('Submited')
}else if (submited_by == 'cancel'){
alert('cancelled')
}
}
I'd rather use a switch statement to make it expandable in the future but this should work.
Also I'm using jquery mostly because I'm not sure how to stop default action without it.
here's a JSFiddle with the code running.
EDIT: Updated to not use Jquery.
EDIT: well, I feel stupid now, realised it wasn't cancel button in a submit form but in a confirmation form.
In your HTML use : onclick="return donationFormSend();"
In Your Javascript: return confirm("Are you sure ....blah blah blah")

onsubmit not called via onclick script

I have looked carefully through other questions to find an answer, and I haven't had any luck, so if this has already been asked and I've missed it, my apologies in advance. I have a very simple page:
<script type="text/javascript">
function setFormField(data) {
document.getElementById('searchTextField').value = data;
document.getElementById("lookupForm").submit();
}
function formSubmit() {
alert('in');
var proceed = false;
return proceed;
}
</script>
</head>
<body>
<form action="page2.php" method="post" id="lookupForm" name="lookupForm" onSubmit="return formSubmit();">
<input type="text" name="location" id="searchTextField" >
<input type="submit" value="Submit">
</form>
click me
</body>
The idea is that when you click the "click me" link, it enters some data into the form and then submits the form, which should then call the onSubmit script - but the formSubmit() function never gets called - the form just submits itself.
Why doesn't the formSubmit() function get called? Seems like it should...?

Submitting forms using JavaScript

I have been battling for the past two days with the evil onbeforeunload function in JavaScript. I have a function that warns the user when they are about to close a page.
However before the page close I would like to submit the form using JavaScript's .submit().
This is my code:
function setPopUpWindow(submitForm){
window.onbeforeunload = function () {
if (submitForm == false ) {
//alert("It worked"); --This code gets called so I know it works
document.getElementById("CancelScripting").submit();
//return "Unsaved Data would be lost";
}
}
}
In my html I have two buttons, one is (supposed to) trigger the .submit() and the other will just ignore it.
<body>
<form action=tett.html id="popUpForm" method=POST>
<script>setPopUpWindow();</script>
<input type="submit" id="submit_button" onclick="setPopUpWindow(true);">
<input class=b1 type=submit id="CancelScripting" style="visibility:hidden" value="CancelScripting" >
</body>
The `setPopWindow value for the second input is not defined so it would be false.
For some reason the submit is not working well.
------------------------Edit to my question-----------------------------------------------
I would like to submit the form even if the user leaves the page by closing the X button on their window. This is the reason why I have the hidden button... Looks like people misunderstood my question.
The only thing you can do is to ask the user if they really want to leave the page:
<head>
<script type="text/javascript">
var submitForm = false;
window.onbeforeunload = function () {
if(submitForm == false){
return 'You have an unfinished form ...';
}
}
function setPopUpWindow(type){
submitForm = true;
}
</script>
</head>
<body>
<form action="" method="post" name="SubmitForm" id="SubmitForm">
<input type="submit" id="submit_button" onclick="setPopUpWindow(true);">
</form>
</body>
I think that what you want to do is submit the form rather than the button by doing something like:
document.forms["formId"].submit();
where formId is the id of the form.
Also, I dont see anywhere in your code where your form is but your buttons should be inside of form tags.
For example, it should look like this:
<body>
<script>setPopUpWindow();</script>
<form id="formId" action="" method="post">
<input type="submit" id="submit_button" onclick="setPopUpWindow(true);">
<input class=b1 type=submit id="CancelScripting" style="visibility:hidden" value="CancelScripting" >
</form>
</body>

Categories