Submit button with POST instead of using HTML form - javascript

I have a form inside a form and this makes the top form unresponsive. When I take off the second form (which is inside the first form), the first form works. This is the second form I have:
<form action="imgupload.php" method="post" enctype="multipart/form-data">
<h3>Upload a new image:</h3>
<input type="file" name="fileToUpload" id="fileToUpload">
<br>
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid">
<input type="hidden" value="User" name="user">
<input type="submit" value="Upload Image" name="imgup">
</form>
Since this makes the first form not work, I was wondering if I can take off the form fields and then the submit button can send the form data to the imgupload.php like this.
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid">
<input type="hidden" value="User" name="user">
<input type="submit" value="Upload Image" name="imgup" action="imgupload.php" method="post" enctype="multipart/form-data">
This does not work now. Is there a way I can get this working? If not, what's an alternative way to send this data to the other php?

Since you are uploading files, have a look at Ravi Kusuma's Hayageek jQuery File Upload plugin. It's simple, it's a Swiss Army Knife, and it works.
Study the examples.
http://hayageek.com/docs/jquery-upload-file.php
Ravi breaks down the process into three simple steps, that basically look like this:
<head>
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet"> // (1)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2)
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3)
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
The final step is to have the PHP file specified in the jQuery code (in this case my_php_processor.php) to receive and process the file:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename specified in the jQuery code block.
Don't forget to check out the server-side code from the Server Side tab -- you need both parts (js and php).
Looking at your question again, you will probably want to use this functionality as well:
dynamicFormData: function()
{
var data ={ location:"INDIA"}
return data;
}
or
dynamicFormData: function(){
return {
newID: $("#newNID").val(),
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
formRole: $('#formRole').val()
};
These will appear on the PHP side, thus:
$newID = $_POST['newID'];
$subj = $_POST['newSubj'];
etc
As with any plugin, resist the temptation to just plop it into your code. Do a couple of quick-and-dirty tests with it first. Kick its tires. Fifteen minutes will save you two hours.
And don't forget to verify what was uploaded. You never know when a developing country black hat might be trying to get a new account.

Related

Displaying results on separate page

I have a beginner question. What is the easiest way to take data from a form on one html page and display it on another when the user clicks submit? I have two functions, a Submit() that calls the display() function (the display function displays the data on the page). I first displayed the result on the index.html page but realized it was too cluttered so I opted to print the results to a separate html page. However, I cannot recall the proper way of doing this. I tried putting location.href='results.html' inside my display() function by it didn't work.
You can use just HTML + Javascript to achieve this.
Just create a form with method="get". So the values will be passed by querystring to the another page.
Example:
index.html
<html>
<form method="get" action="results.html">
<input type="text" name="age" />
<input type="submit" value="Send" />
</form>
</html>
results.html
<html>
<h1></h1>
<script>
document.querySelector("h1").innerHTML = window.location.search.substring(1);
</script>
</html>
Whilst technically this is possible using HTML5 local storage, the best solution to your question is to use a server side language such as PHP, which you can read up on here as a beginners tutorial, or in more detail on the PHP Manual
Hope this helps
Here is an example. Write your html page (e.g. "index.html") like
<html>
<head>
<title>form with output</title>
</head>
<body>
<form target="out" action="tst.php">
<input type="text" name="a">
<input type="text" name="b">
<input type="submit" name="sub" value="OK">
</form>
</body>
</html>
and, assuming you have PHP available on your webserver you can write a second (php) script (filename: "tst.php") like this
<?php
echo json_encode($_REQUEST);
?>
(The php script simply outputs all passed variables as a JSON string). The important thing that will redirect your form's output into a separate window is the target="out" part in the <form> tag.

HTML file input with possibility to input several files one after another

I'm looking for a possibility to input several files in a row in an HTML form. It strikes me that there seems to be no easy solution for this (or at least I haven't been able to find it despite several hours of searching). If I use the multiple attribute in an <input type="file" name="myFiles[]" multiple />, I can choose several files at a time holding Ctrl, but if I choose one file at first, then click the input field again and choose another one, the second file seems to overwrite the first one.
So I thought I might try to use javascript to add more <input type="file" name="myFiles[]" /> fields (with the same name), since I have seen something similar somewhere. I tried the following:
JavaScript:
function addInputFileEle() {
var field = document.getElementById("filesField");
var row = '<input type="file" name="myFiles[]" onchange="addInputFileEle();" />';
field.innerHTML += row; // add one more <input type="file" .../> element
}
HTML:
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesField"> <!--for adding more file-input rows-->
<input type="file" multiple name="myFiles[]" class="multi" onchange="addInputFileEle();" />
</fieldset>
<input type="submit"/>
</form>
The document indeed does create additional file-input elements whenever I click on one of them and select a file, BUT: The file does not get uploaded! I mean, after I select the file, the file name does not get displayed, instead, it still says "Choose a file" (or "Select a file", not sure about English). So apparently my onchange="addInputFileEle()" overwrites the normal reaction (the file getting 'loaded' into the input element)? Even though this does not seem logical to me. Can anyone help? Why does the file not get selected in the end? Or maybe there is a simpler solution than mine, which would of course be very welcome. Thanks in advance!
Ok I will just post my solution in case anyone else is searching for a way to select several files for upload one by one. As #CodingWithClass pointed out, I was resetting the input field by using something like parentElement.innerHTML += additionalInputElement;. Instead, I should have used appendChild as #JoshuaK suggested:
<html>
<head>
<meta charset="UTF-8">
<script>
function addFileInput(fieldsetName, firstInputId) {
var fs = document.getElementById(fieldsetName);
// only add one if the last file-input field is not empty
if(fs.lastElementChild.value != '') {
var firstInputFile = document.getElementById(firstInputId);
var newInputFile = document.createElement("input");
newInputFile.type = firstInputFile.type;
newInputFile.name=firstInputFile.name;
newInputFile.multiple=firstInputFile.multiple;
newInputFile.class = firstInputFile.class;
newInputFile.onchange=firstInputFile.onchange;
fs.appendChild(newInputFile);
}
}
</script>
<title>MultiFile-Testing</title>
</head>
<body>
<?php print_r($_FILES); // see if files were uploaded in the previous round ?>
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesFS">
<input type="file" multiple name="myFiles[] id="firstInputFile" onchange="addFileInput('filesFS', 'firstInputFile');" />
</fieldset>
<input type="submit"/>
</form>
</body>
</html>

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

Html form button functionality to single button

I got a script on a website that reads html from a text file each time I press a button. The text file is chosen depending on what name of the page is given. It works fine and dandy with a tag and working as a button inside of it.
The problem I have is that I do not want the and tags at all if I want only one button, I have tried to call the script with jQuery and ajax in various ways without any luck.
Heres the website(its real basic for testing purposes):
<html>
<head>
<title>PHP Flat File Test</title>
</head>
<body>
<?php include("savedinfo.php"); ?>
// This is how it works, its fine for multiple buttons in a row
<form method="get">
<button type="submit" name="page" value="index" action="savedinfo.php">Index</button>
<button type="submit" name="page" value="page1" action="savedinfo.php">Page1</button>
<button type="submit" name="page" value="page2" action="savedinfo.php">Page2</button>
</form>
//But this is the way I'd like to create a button(not exact properties but in one line)
<input id="pageBtn" type="button" page="page1" value="page1" />
</body>
What it does is simply update an region of the website with html from different text files without reloading the page.
The script that loads the html:
<?php
//the script gets a name for a file(page) to load
$page = $_GET["page"];
//if it got no parameters(i.e. first load of the page, goto index)
if($page == null){
$page = "index";
}
//check if the file/page exists, othervise display error page
if(file_exists($page.".txt"))
$filename = $page.".txt";
else
$filename = "404.txt";
$f = fopen($filename,"rt");
$content = fread($f, filesize($filename));
// send back the read html
echo $content;
#fclose($f);
?>
The text file page is just a plain tag and some text that differs from page to page.
Now is it even possible to use a script or something to get rid of the tags if you want to create a button that sends the name data to the script and updating the current page with the new info?
Attribute action belongs to element form
<form action="savedinfo.php">
Form element input has to be inside of form
<form method="get">
<button type="submit" name="page" value="index" action="savedinfo.php">Index</button>
<button type="submit" name="page" value="page1" action="savedinfo.php">Page1</button>
<button type="submit" name="page" value="page2" action="savedinfo.php">Page2</button>
<input id="pageBtn" type="button" page="page1" value="page1" />
Instead of opening, reading and closing of file you may use file_get_contents. It will give you content of chosen file too.
If you need only change and then export content of chosen file somewhere to screen, use
description of page
and then you need to make process of manipulation with chosen file safe. But it is something you should do by yourself.
But really, nobody cannot make anything instead you. We (at least me) may help with great many things, but ... this is all I can help with.
BTW: It is better to have content of pages in any DB, than in files - if it is not really needed to have it in file.
Best regards.

Javascript redirect based on form input

I need to redirect one page to another page using the form value.
I have this code, which i think is fine for first page and what should i put in the other page where i want to show the data ??
<meta http-equiv='refresh' content='0;url=http://site.com/page.php'>
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php echo $url; ?>">
<script language="JavaScript">document.myform.submit();</script>
</form>
Regards
You can't mix a meta-refresh redirect with a form submission per se.
Also, meta-refreshes are terrible anyway. Since you are already in control of the receiving page, and it's using PHP, use that to accomplish the redirect. Try this:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="submit" value="Go!" />
</form>
Then, in page.php:
<?php
// Act on the input, store it in the database or whatever. Then do the redirect using an HTTP 302.
header('Location: http://example.com');
?>
If you need the form to pass the destination along to page.php, you'll want to sanitize it to prevent a LOT of security problems. Here's a rough outline.
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="destination" value="http://example.com" />
<input type="submit" value="Go!" />
</form>
Then, in page.php (copied re-encoding from answer https://stackoverflow.com/a/5085981/198299):
<?php
$destination = $_POST['destination'];
$url_parsed = parse_url($destination);
$qry_parsed = array();
parse_str($url_parsed['query'], $qry_parsed);
// Check that $destination isn't completely open - read https://www.owasp.org/index.php/Open_redirect
$query = parse_url($destination);
$destination = "{$url_parsed['scheme']}{$url_parsed['host']}{$url_parsed['path']}?" . http_build_query($query);
header('Location: ' . $destination);
?>
I haven't double-checked that code (just wrote it here in the browser), but it should suffice as a rough sketch.
in site.com/page.php
<script>window.location.href = 'newPage.php';</script>
You will have to write this outside the php tags though.
To redirect a page in PHP, use:
<?php
header('Location: url/file.php');
?>
To refresh to a different page in HTML, use:
<meta http-equiv='refresh' content='0;url=http://url/file.php'>
In the content attribute, 0 is the amount of seconds to wait.
To refresh to a different page in JavaScript, use:
window.location.href = 'url/file.php';
When none of these work, follow an anchor link, using HTML:
Click here to go now!
To answer your question, it can be done several ways:
1) Very bad, requires two files, super redundant
HTML file:
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Submit the form
document.forms['myform'].submit();
</script>
Page.php:
<?php
// Catch url's value, and send a header to redirect
header('Location: '.$_POST['url']);
?>
2) Slightly better, still not recommended
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Set form's action to that of the input's value
document.forms['myform'].action = document.forms['myform'].elements['url'].value;
// Submit the form
document.forms['myform'].submit();
</script>
3) Still very redundant, but we're getting better
<form action="http://site.com/page.php" method="post" name="myform">
<input type="hidden" name="url" value="<?php=$url?>">
</form>
<script type="text/javascript">
// Simply refresh the page to that of input's value using JS
window.location.href = document.forms['myform'].elements['url'].value;
</script>
4) Much better, save yourself a lot of trouble and just use JS in the first place
<?php
// Start with a PHP refresh
$url = 'url/file.php'; // Variable for our URL
header('Location: '.$url); // Must be done before ANY echo or content output
?>
<!-- fallback to JS refresh -->
<script type="text/javascript">
// Directly tell JS what url to refresh to, instead of going through the trouble to get it from an input
window.location.href = "<?php=$url?>";
</script>
<!-- meta refresh fallback, incase of no JS -->
<meta http-equiv="refresh" content="0;url=<?php=$url?>">
<!-- fallback if both fail (very rare), just have the user click an anchor link -->
<div>You will be redirected in a moment, or you may redirect right away.</div>
Save that with a .php extension, and you should be good to go.

Categories

Resources