change the way the form is submitted without using javascript - javascript

I have a form that is used for search on a website.
<form method="get" action="example.com/search">
<input type="text" name="search"/>
<input type="submit"/>
</form>
Lets say that I searched for "stack" when submitting I want the user to get redirected to example.com/search:stack
right now when submitting user gets redirected to : example.com/search?search=stack
How can I achieve that and allow it on devices that does not support javascript!?

You could set up your search page to redirect your users from /search?search=stack to /search:stack.
PHP:
if(isset($_GET['search']))
{
$search = $_GET['search'];
header('Location: /search:'.$search);
}
else
// no query handling

You'll need Url rewriting to do that.
URL Rewriting for Beginners

You cannot. Submitting a form in the way you describe, i.e. with the GET method, encodes the content of the form as a query string, which has this form:
?search=stack
See section 4.10.22 of the HTML5 Living Standard or section 17.13.3 of the HTML 4.01 Specification.
Correction: I'm sorry, I did not understand your question correctly. You indeed cannot change how the form is submitted, but you can redirect afterwards as you suggest.
Álvaro Martínez suggests a good way to accomplish that in his answer.

Related

How to Redirect to a URL in PHP from with Post Data as URL String

I have searched a lot but did not find any answer...
My Question is, let's say I have a random page and user click on the download button to download a file, and the html in the button is:
<form action="http://seconddomain.com/thanks-for-downloading/" target="_blank" method="post">
<input type="hidden" name="FileID" value="dYnte-m9bZ4">
<div align="center">
<input alt="Download Movie" src="image url here" type="image">
</div>
</form>
This data is submitted to the next page with post method using in the form, as you can note the value is defined as "dYnte-m9bZ4"
In this case, this value is the file download link, eg: downlaodfile.com/dYnte-m9bZ4
I want that when this data is submitted with post method on the next page there should be some PHP code that will automatically attach the defined value to the server URL/link as downlaodfile.com/dYnte-m9bZ4 and the user will be automatically redirected to the download page.
If this is not possible with post form method, then please suggest any other method...
Please tell me how can I do it.
Thanks...
Add this line,from where you want to redirect in your post handler php file.
$var = $_POST["FileID"];
// do input validation ,type-check etc on $var.
header("Location: http://downlaodfile.com/".$var);
I have done same thing of redirecting after form submission
you can check my code # Bitbucket line no 459 of link
Never use user input directly. Never.
Sanitize and validate before using user input.
Escape data when necessary (when data switches execution contexts).
Note: This does not include error handling. This is just a skeleton.
$filteredPost = filter_input_array(INPUT_POST, $filterRulesArray); //Sanitize
$validatedPost = filter_var_array($filterdPost, $validationRulesArray) //Validate
$fileId = urlencode($validatedPost['FileID']); //Potentially, an important step in this case.
header("Location: http://downloadfile.com/{$fileId}");
PHP Manual: filter_input_array()
PHP Manual: filter_var_array()
PHP Manual: urlencode()

Can I force a page in history to be removed?

Re editing... this question has NOT been answered before!
I had understood that changing the contents of a current page with window.location replaced the cached version of the original page ( from the "last" history), so that you really couldn't go back with the browser BACK button. I had even seen this posted as a solution to preventing a malicious visitor from using the BACK button to to re-submit a mail form many times. But it is NOT workable because in the case of a mail form, the BACK button will just take the user back to the pre-POST version of the page.
So, I can use javascript to reset the form, disable the SUBMIT button, change to another page after success, or do whatever I want to the page. But its all for nothing if a simple click of the BACK button followed by SUBMIT causes the form to post again with just 2 clicks.
I know there are a lot of solutions to preventing malicious form resubmissions I can try, but I've had trouble getting them to work, and so I'd just like to know if removing the last history is a dead end. If there is a way, and it is pretty cross browser friendly, then I can just make it part of my scripted actions once my form is successfully processed, and my "thank you" page displays. Basically I'd want my "thank you" page's 'onload' event to either erase the last history, or in a browser compatible way disable the BACK button!
For what its worth, I've included code from simple test I've been working with. You can put some junk in the fields and hit submit. The vars are cleared in the PHP, the form fields are force cleared in javascript, and a new 'location' is invoked. Unfortunately, hitting BACK button will take you back to the "pre-posted" form, with all the strings you added still intact.
<!DOCTYPE HTML>
<html>
<head>
<title> Form Behavior Test</title>
</head>
<!--
<?php
$name = $email = $comments = "";
$formDone = false;
if ($_SERVER["REQUEST_METHOD"] == "POST" )
{
$formDone = true;
$name = $email = $comments = "";
}
?>
-->
<body >
<table border="1"><tr><td style ="text-align:right;" width=100%>
<form name="contactform" id="contactform" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" id="name" value="<?php echo $name;?>"><br>
Email: <input type="text" name="email" id="email"value="<?php echo $email;?>"><br>
<br>
<div align="center"> ---- <span class="error">*</span> Message ---- <br>
<textarea name="comments" id="comments" wrap="physical" cols="40" rows="10" ><?php echo $comments;?></textarea>
</div>
<input name="submit" id="submit" type="submit" value="Submit" >
</form>
</td></tr></table>
<script language="JavaScript">
if (<? echo ($formDone == true) ? 'true' : 'false'; ?>)
{
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("comments").value = "";
document.getElementById("submit").value="Disabled";
document.getElementById("submit").disabled=true;
// substitute with a thank you page
window.location = "http://google.com";
}
</script>
</body>
</html>
After searching pretty exhaustively, I don't believe there is any way to remove a page from history, except on the very latest browsers that support newer HTML-5 history methods. I'm still open to solutions but at this point I think the easiest thing will be for me to set a cookie anytime a successful email is processed by my PHP code. Then, I can also make the PHP or a javascript snippet look for the cookie and if found, I can take all kinds of actions... wipe out all filled in fields (as they would be if the BACK button is pressed), block the email, politely inform the user that he/she must wait (until my cookie expires) to send another email though the form, etc.
I didn't want to do this originally because the BACK button doesn't actually re-load the page, it just displays it. If there were a universal browser compatible way to make pages reached by back buttons actually re-load, this would never have been a problem to begin with. So even with a cookie, my defensive actions couldn't activate until the SUBMIT button is pushed. I guess I can live with that. Also, even today, some people are paranoid about cookies and turn them off. But if I want to be adamant about it, I can just detect when I can't set a cookie, and inform the user that cookies are required to use my email form. If that's too big a deal, oh well!
Thanks to those that contributed. The fact is, the LACK of answers is really a very useful answer sometimes. When I post on any stackoverflow forum and don't get any answers pretty quickly, its a good red-flag that things are going to get convoluted really fast if I don't consider an alternate approach! :-)

client-side form validation after clicking SUBMIT

I have 2 php files "source.php" and "target.php". In the source.php part I have,
<form method="POST" id="form1" action="target.php">
...
<input type="submit" name="submit" value="Submit"/>
</form>
When I click on submit it goes to the "target.php" (even if I have errors in the form), but I want that, only after all form fields are validated it will go to the target page, else it shows some kind of warning message and stays on the same page. Please help! Maybe this is a stupid question for some but I am a beginner. (I know how to do all the field validations and its working fine).
Duplicate of duplicate questions.Please search throughly before you post next time.
Generally javascripts are used for validation.But there are cases when javascripts become inefficient,for example when you need to validate country and its states.Its not practical to send the entire list of countries and states to the client. In such scenarios AJAX is used.By using AJAX the client sends the data to server immediatly after the user enters it.then it fetch only the required data.Its a simultaneous two way communication between client and server.for example if the user enters country name as INDIA,using AJAX states of INDIA are loaded for validation,thus saving bandwidth.
JavaScript and AJAX are not easy to learn,you must research try and correct different codes.Just google "JavaScript form validation"...
This is from w3Schools...
Required Fields
The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The function above could be called when a form is submitted:
Example
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
here is more basic examples http://www.w3schools.com/js/js_form_validation.asp
Good Luck
You can use AJAX to validate your form. JavaScript is not recommended for form validation.
A simple tutorial for AJAX Validation is available here
But be aware, even if you are validating your form before submission to target.php, always make sure that you check the data in target.php too. This is because JavaScript can be changed (thanks to the modern DOM interpreters) in the browser. It can be made so that the form is submitted without AJAX verification. So you should check it twice, before and after submission.
Also make sure to escape the data, as user input can never be trusted.
You should also user strip_tags($string) to prevent use from inserting php code.
JavaScript is most likely the easiest way to do this (read the other posts).
However, if you don't want to use JavaScript you could always check if all forms are set using isset() or something similar and then passing on the $_POST variables in the URL and grabbing those using $_GET. Of course make sure there isn't any sensitive information in the URL. In addition: you could always work with global variables.
Another way to do this without JavaScript is submit to a database after several checks (like escaping the strings etc.), perhaps even encrypt, but I don't suggest this since this is the long way around.

getting value of input box on another page

I have two pages; page1 and page2. page1 holds a form while page2 has some images. I want to enter a sentence into the form on page1 and get the value of that text box on page2.
the form on page1
<form name="input" action="page2.html" method="get">
<input type="text" name="textbox" id="textbox">
<input type="submit" value="Submit">
</form>
what would be the proper way to go about this?
Would I use the get method along with the action method to send the value through the url and then extract it using window.location.href then splitting the text after the ? or is there a simpler way of achieving this?
Thanks
Just send it in the query string and read it in page2, as you said.
See this to have an idea of how to read the query string parameter:
How can I get query string values in JavaScript?
Your way of doing this would work, although it's certainly not a good long term solution. If your site is going to get more complicated, it would be better to use a server-side language like .NET, PHP, Ruby, etc.
If you have to get thed data using only JS, then you need to use URL. Otherwise you can use server side script like jsp.
When you use URL, make sure the text is URL-encoded before appending to the URL.

Thank you alert upon form submission

I have a very basic form at http://www.happyholidaylites.com/contact.html and it is working great. When you submit the form, the user is brought to the index.html with no message that the form has been sent. I am looking to initiate an alert that says, "your form has been submitted" with an x button. My code looks like this:
<form method="post" id="myForm" action="dynaform.php">
<input type='hidden' name='rec_mailto' value='JBIRD1111#gmail.com'>
<input type='hidden' name='rec_subject' value='New Contact Form'>
<input type='hidden' name='rec_thanks' value='index.html'>
so on and so forth.....
The last line is what is telling the form what to do after the submit button is pressed, but I dont want it to point the browser to the index, rather I want a javascript popup with a success message. Any ideas?
Why not a simple onSubmit?
<form method="post" id="myForm" action="dynaform.php" onSubmit="alert('Thank you for your feedback.');" >
To be honest you are better re-directing to another page in order to avoid the user re-submitting the page on a refresh. Have a look at Post/Redirect/Get Pattern.
Popups can be extremely annoying on websites. You should create a page called "thank-you.html" that you can re-direct the user to on successful submission which has access to the site navigation options or even just do a re-direct back to the form page after a few seconds.
Instead of redirecting to index.html, redirect to thanks.html; your users will thank you because everybody hates popups!
Sounds like your PHP script handles the form submission by processing the input and redirecting the browser to the value in the rec_thanks field.
You can add something like onsubmit="YourJavaScriptFunction()" to the form tag to add client-side behavior prior to actually submitting the form. Within that function you can perform validation, use alert('Thank You!'), etc..

Categories

Resources