Form submitting when clicked - javascript

I am having an issue with this login system, when ever I click the log in button, or the sign up button it re-directs me to a white page with writing on it, That being said it is interfering with my log in action.
Here is the code that I think is causing the issue,
<form method="POST" action="" accept-charset="UTF-8">
on line 16 of the HTML code, I tried to take that code out and it stopped the re-directing but the text boxes went out of place, and the white background/background-box was not there either,
Link, HERE

You want to use preventDefault() if this is a purely Javascript: you should be able to pass the button press event into the listener when you create it:
$('.login').on('click', function(e) {
e.preventDefault();
// Will be executed on press
}
<form method="POST" class="login" accept-charset="UTF-8">
If there's no JS involved in this scenario, then you want to get rid of the action parameter entirely – leaving it as the empty string will still cause it to redirect in some cases.

As Jonathan Lonowski explained above, when the log in / sign up button is clicked, the form will post the data to the page mentioned in the action= attribute. Since this attribute is empty in your form tags, it will re-load the same page, posting the data to itself.
The data will arrive in key=value variable pairs. The variable value will be the contents of the field, the variable name will be the value of the name="" attribute on the element.
For e.g., for this field:
<input id="fname" name="first" value="Bobby" />
The data will be received like this:
$fn = $_POST['first']; //value is Bobby, or whatever user enters
On your page containing the form, add a section at the top like this:
<?php
if (isset($_POST['fname']) == true){
$fn = $_POST['fname'];
echo "Received First Name: " . $fn;
die();
}else{
?>
//Your current page, in its entirety, goes here
<?php
} //close the PHP if statement
?>
That is how you deal with a normal HTML <form> construct.
However, if you wish to use AJAX to communicate with a PHP file without changing the page, then:
(1) There is no need to use a <form> construct, just use a DIV with an input button: <input type="button" id="sub_btn" value="Submit" />
(2) Trap the button press using standard js/jQuery:
$('sub_btn').click(function(){
var fn = $('#first').val();
//etc.
$.ajax(function(){
type: 'post',
url: 'my_php_processing_file.php',
data: 'fname=' +fn+ '&lname=' etc
});
});
In your PHP processor file, the data will be received thus:
<?php
$fn = $_POST['fname'];
$ln = $_POST['lname'];
//Do your MySQL lookup here...
echo 'Received ' .$fn. ' ' .$ln;
(3) IF you do use the form construct, you can still do everything as above, but you will need to suppress the default form action of navigating to the page specified in the action= attribute (an attribute setting of action="" will post data to and reload the same page you are on).
To suppress navigating to the page specified in action= (involves page refresh, even if just action=""), use event.preventDefault(), as follows:
$('#buttonID').click(function(event){
event.preventDefault();
//remainder of button click code goes here
});

Related

Reload url with variable from form field PHP/HTML/Javascript [duplicate]

Consider this form:
<form action="http://www.blabla.com?a=1&b=2" method="GET">
<input type="hidden" name="c" value="3" />
</form>
When submitting this GET form, the parameters a and b are disappearing.
Is there a reason for that?
Is there a way of avoiding this behaviour?
Isn't that what hidden parameters are for to start with...?
<form action="http://www.example.com" method="GET">
<input type="hidden" name="a" value="1" />
<input type="hidden" name="b" value="2" />
<input type="hidden" name="c" value="3" />
<input type="submit" />
</form>
I wouldn't count on any browser retaining any existing query string in the action URL.
As the specifications (RFC1866, page 46; HTML 4.x section 17.13.3) state:
If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then appends the form data set, encoded using the "application/x-www-form-urlencoded" content type.
Maybe one could percent-encode the action-URL to embed the question mark and the parameters, and then cross one's fingers to hope all browsers would leave that URL as it (and validate that the server understands it too). But I'd never rely on that.
By the way: it's not different for non-hidden form fields. For POST the action URL could hold a query string though.
In HTML5, this is per-spec behaviour.
See Association of controls and forms - Form submission algorithm.
Look at "4.10.22.3 Form submission algorithm", step 17. In the case of a GET form to an http/s URI with a query string:
Let destination be a new URL that is equal to the action except that
its <query> component is replaced by query (adding a U+003F QUESTION
MARK character (?) if appropriate).
So, your browser will trash the existing "?..." part of your URI and replace it with a new one based on your form.
In HTML 4.01, the spec produces invalid URIs - most browsers didn't actually do this though...
See Forms - Processing form data, step four - the URI will have a ? appended, even if it already contains one.
What you can do is using a simple foreach on the table containing the GET information. For example in PHP :
foreach ($_GET as $key => $value) {
$key = htmlspecialchars($key);
$value = htmlspecialchars($value);
echo "<input type='hidden' name='$key' value='$value'/>";
}
As the GET values are coming from the user, we should escape them before printing on screen.
You should include the two items (a and b) as hidden input elements as well as C.
I had a very similar problem where for the form action, I had something like:
<form action="http://www.example.com/?q=content/something" method="GET">
<input type="submit" value="Go away..." />
</form>
The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something also worked. I also could have used a node number (i.e. /node/123).
If you need workaround, as this form can be placed in 3rd party systems, you can use Apache mod_rewrite like this:
RewriteRule ^dummy.link$ index.php?a=1&b=2 [QSA,L]
then your new form will look like this:
<form ... action="http:/www.blabla.com/dummy.link" method="GET">
<input type="hidden" name="c" value="3" />
</form>
and Apache will append 3rd parameter to query
When the original query has array, for php:
foreach (explode("\n", http_build_query($query, '', "\n")) as $keyValue) {
[$key, $value] = explode('=', $keyValue, 2);
$key = htmlspecialchars(urldecode($key), ENT_COMPAT | ENT_HTML5);
$value = htmlspecialchars(urldecode($value), ENT_COMPAT | ENT_HTML5);
echo '<input type="hidden" name="' . $key . '" value="' . $value . '"' . "/>\n";
}
To answer your first question yes the browser does that and the reason is
that the browser does not care about existing parameters in the action URL
so it removes them completely
and to prevent this from happening use this JavaScript function that I wrote
using jQuery in:
function addQueryStringAsHidden(form){
if (form.attr("action") === undefined){
throw "form does not have action attribute"
}
let url = form.attr("action");
if (url.includes("?") === false) return false;
let index = url.indexOf("?");
let action = url.slice(0, index)
let params = url.slice(index);
url = new URLSearchParams(params);
for (param of url.keys()){
let paramValue = url.get(param);
let attrObject = {"type":"hidden", "name":param, "value":paramValue};
let hidden = $("<input>").attr(attrObject);
form.append(hidden);
}
form.attr("action", action)
}
My observation
when method is GET and form is submitted, hidden input element was sent as query parmater. Old params in action url were wiped out. So basically in this case, form data is replacing query string in action url
When method is POST, and form is submitted, Query parameters in action url were intact (req.query) and input element data was sent as form data (req.body)
So short story long, if you want to pass query params as well as form data, use method attribute as "POST"
This is in response to the above post by Efx:
If the URL already contains the var you want to change, then it is added yet again as a hidden field.
Here is a modification of that code as to prevent duplicating vars in the URL:
foreach ($_GET as $key => $value) {
if ($key != "my_key") {
echo("<input type='hidden' name='$key' value='$value'/>");
}
}
Your construction is illegal. You cannot include parameters in the action value of a form. What happens if you try this is going to depend on quirks of the browser. I wouldn't be surprised if it worked with one browser and not another. Even if it appeared to work, I would not rely on it, because the next version of the browser might change the behavior.
"But lets say I have parameters in query string and in hidden inputs, what can I do?" What you can do is fix the error. Not to be snide, but this is a little like asking, "But lets say my URL uses percent signs instead of slashes, what can I do?" The only possible answer is, you can fix the URL.
I usually write something like this:
foreach($_GET as $key=>$content){
echo "<input type='hidden' name='$key' value='$content'/>";
}
This is working, but don't forget to sanitize your inputs against XSS attacks!
<form ... action="http:/www.blabla.com?a=1&b=2" method ="POST">
<input type="hidden" name="c" value="3" />
</form>
change the request method to' POST' instead of 'GET'.

How to allow a user to resubmit a form without a warning

I believe it will be a poor question, because most people wants to prevent a form from beeing resubmited but I'll need the exact opposit of it.
That means a user should be allowed to reload a page and the form values have to be posted each time (Session Variables are not possible in this cenario)
Normally the user gets the annoying warning message of the browser.
Is it possible to turn this warning off or simply resubmit the form (eg. with jQuery)
Thanks a lot for your help!
You could overwrite alert and empty the function with alert = function(){}. Check this example:
alert("test");
alert = function(){};
alert("test2");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You cannot turn off this alert (in a good way), but you can redirect to the same form, with all fields auto-compiled, so if you re-do a submit, it won't ask you a confirm.
You can redirect with a _GET parameter, and if your code detect this, it will check for all values to insert in the form.
Something like this:
form.php
<?php
if(!empty($_GET['param'])) {
/* Pseudo code */
$data = query_and_fetch("select 'value_1' as field_1 from yourtable WHERE wfield='".escape($_GET['param'])."' ;");
}
?>
<form method='post' action='process.php'>
<input name='field_1' value='<?=isset($data['field_1']) ? $data['field_1'] : ''?>/>
<input type='submit' value='submit'/>
</form>
process.php
<?php
header("location: form.php?param=123");
?>

javascript submit() command not sending my post data

From this earlier thread I thought I learned that form data could be sent by POST method using javascript submit() command. But I can't get it to work. This demo doesn't make obvious sense with respect to purpose but bear with me. I just wanted to test this specific command which doesn't seem to work for me. Can you please help me? Clicking the regular submit button sends the post data ok but activating the javascript via the link does not.
<html><body>
<?php
$self = $_SERVER['PHP_SELF'];
$posttext = file_get_contents('php://input');
echo "Received input: ".chr(34).$posttext.chr(34)."<br><br>";
echo "<form id='test' action='{$self}' method='post'>";
?>
Please fill in the fields with any text:<br><br>
foo: <input type="text" name="foofield"><br><br>
bar: <input type="text" name="barfield"><br><br>
<input type="submit" value="Submit button works"><br><br>
Submitting by JS not working – why?
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
$(document).ready(function(){
$("a#submitlink").click(function(){
alert("Yes, the link has been clicked. It is not that.");
$("form#test").submit();
});
});
});
</script>
</body></html>
You need to: event.preventDefault(); the default behaviour from the <a>. The problem is if you don't do that, the page reloads cause that is what the <a> tag does. So even you submit the data you also refresh the page where the submitted data gets lost.
$("a#submitlink").click(function(event){
event.preventDefault();
$("form#test").submit();
});
The other solution is to add # in the href of the <a> tag like:
Submitting by JS not working – why?
this will also prevent the <a> tag from doing a refresh.

Replace a php variable with textbox input

Ok I am confused with php, javascript and html and dont know what to do. On researching on the internet, i found js is client side and php is server side. when a php file is run on the browser, it converts everything into html and the page is loaded. Now let me tell you guys what i am doing.
I have a php file that give me some stats from a particular url (in the sample i am just showing url)
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Result URL = www.example.com
The above code echoes the url which is www.example.com. I added a textbox to this code which i believe is javascript+html
<script>
function myFunction() {
$url=myurl.value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Here the result is same. only difference is that it has a textbox and button above the result.
When I enter another url in the textbox and press submit, it does nothing probably because the page is already loaded. I want to replace the result of www.example.com to the one which is entered in the textbox without changing the .php file. There will always be a default url in the .php file. whenever the file is opened in the browser, the default statistics will be shown... only when the user enters new url and clicks submit, the stats should change.
How can I achieve this? I am behind this since more than a couple of hours now and not sure how to get this done. Please help me.... Thank you.
EDIT
Can I have two .php files? one for the user to enter url and submit and another one to get the entered url and echo it? If yes, how? If I understand this logic, i can get a start for what I am doing.
I think you are trying to do more with your js function, but syntactically it is combining js and php. It should look like this
function myFunction() {
var url = document.getElementById('myurl').value;
}
Although this doesn't really do anything other then assign the content of the text box to a variable.
EDIT
<script>
function myFunction() {
document.getElementById('url').innerHTML = document.getElementById('myurl').value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<? $url = "www.example.com"; ?>
URL = <span id="url"><?= $url; ?></span>
natzim is correct if you are wanting to write the url back to the php file. If you use javascript to change the action of the form, it will submit to a different page.
//javascript
function myFunction() {
//this should change the page that loads after submit.
//If you want to go to a new page that the user enters, leave this code in...
//If not, remove it
document.getElementsByTagName("form")[0].action = document.getElementById("myUrl").value;
}
That is assuming you have a form tag somewhere (which you will need to submit the page). Also I am not sure this code will run if you use a submit and not a button. If you used a button instead you could append this to the code above to submit the form:
//This would be part of your myFunction if you used a button instead of a submit input
document.getElementsByTagName("form")[0].submit();
as per my comment -
this code is your old php:
<?
$url="www.example.com";
echo "URL = " .$url;
?>
and this is the php I suggested:
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
this would check the myurl input from that was submitted to the server and set the value of $url to its value if it existed then the $url variable would be echoed to the page under the inputs.
This code is assuming you are using the POST method rather than the GET method when your form was submitted.
**EDIT: **
To clarify - here is your page with the modifications I am suggesting. (Please ignore the javascript above as it seems you will not need it):
<form action='www.example.com' method='post'>
<input type="text" name="myurl" id="myurl">
<input type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
</form>

Temporarily changing HTML structure on the same page in PHP when submit button is clicked?

I have PHP page that have submit button to another URL.
I want to reload the current page after the submit button clicked, and add div to the HTML.
My page url is: /foo.php, and in the HTML I have:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
As you can see the form sends request to /bar page.
I want to reload the /foo.php (the current page), and change the HTML to:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
<div>Thank you!</div>
My problem is how can I know that the user click on the button and the refresh was because the click, and not because just navigating.
Another thing, if it possible, I want that the new div will disappear if the user refresh the page again.
Why don't you just append the div in the success callback of the get function? You wouldn't have to reload the page.
<div id="btn_area">
<button onclick="$.get('/bar', function() { $('#btn_area').append($('<div>').html('Thank You');)})">Submit</button>
</div>
By the way, i hardly recommend to separate the javascript from the html and not put it directli in the DOM.
Another Method would be, to fire an additional form with a hidden parameter to the same side. After that, you check on the serverside the hidden parameter and display the div.
A third method is, to set a cookie in the Callback, reload the side, check the cookie, display the div and remove the cookie again.
In my opinion, the first mentioned option (add the div directly in the callback without reloading) would be by far the 'prettiest', but of course i don't know what else is going on on your site
Alternatively, you could simulate a flash session (one time use session) if you opt to do this in PHP. Consider this example:
foo.php
<?php session_start(); ?>
<form method="POST" action="bar.php">
<button type="submit" name="thank_you">Submit</button>
</form>
<?php if(isset($_SESSION['thank_you'])): ?>
<?php unset($_SESSION['thank_you']); ?>
<h1>Thank You!</h1>
<?php endif; ?>
bar.php
<?php
session_start();
if(isset($_POST['thank_you'])) {
$_SESSION['thank_you'] = true;
// processes
header('Location: foo.php');
}
?>
Demo
You can handle that in js side. Just make your request, and in callback, you can manipulate dom. You can see below;
<button>Submit</button>
$("button").on("click", function() {
var $button = $(this);
$.get("/echo/html", function() {
$button.after("<div>Thank you!</div>");
});
});

Categories