POST value in PHP when submitting onChange Javascript - javascript

I'm trying to submit an image file using javascript onChange, the thing is I don't know the value of the submitted POST form, and how can I set a custom POST value. Here is a simple example:
HTML:
<form id="form" action="upload.php" method="post">
<input type="file" id="file" name="image">
</form>
Javascript:
document.getElementById("file").onchange = function() {
document.getElementById("form").submit();
}
So after I submit the form I can only get the value $_POST['image']. Usually when receiving POST I check for the value of the submit button which I create uniquely for each form such as, updateform, updateclient. Now I want to do the same by creating custom messages, one page will send 'uploadclientimage' the other will say 'uploadshopimage' and so on. This way the upload.php file can process the status to decide what to do next.
In upload.php I want to do like this:
if(isset($_POST['uploadclientimage']))
{//Save in client uploads folder and update client info}
else if(isset($_POST['uploadshopimage']))
{//Save in shops uploads folder and update shop info}
else header("Location: login.php");
using submit button does that easily <input type="submit" name="uploadclientimage">
How can I do something like that with onChange form submit???

Just add a hidden field in the form. For example:
<input type="hidden" name="uploadclientimage" value="">

Related

Submit form and redirect not working

EDIT: I should mention the form submits fine manually but with the javascript nothing seems to happen
I'm trying to get a form to autosubmit on page load and then redirect the user. Reason for this is this is part of a PHP page and the data needs to go into my database but then also POST the variables to a 3rd party SMS platform then return to the users dashboard.
My form looks like this:
<html>
<form action="https://www.example.com" id="myForm" method ="POST">
<input type="hidden" name="apiKey" value="withheld">
<input type="hidden" name="message" value="<?php echo $club_name ?> have requested you to play for them this weekend. Please login to your account to see more information and accept.">
<input type="hidden" name="to" value="<?php echo $to ?>">
<input type="hidden" name="from" value="withheld">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</html>
This seems to work fine so I assume the Javascript is incorrect which is:
<script>
document.getElementById('myForm').submit();
window.location.replace("https://www.example.com");
</script>
You have to use a different name than
name="submit"
as all name attributes are set as properties on the form,
hence overriding the default "submit" property on the form,
and the default form method "submit()" is gone.
https://developer.mozilla.org/de/docs/Web/API/HTMLFormElement
"Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (eg a form with an input named action will have its action property return that input instead of the form's action HTML attribute)."
In your code window.location.replace("https://www.example.com"); line won't make sense because submit() function will try to submit the form and will change the page and then replace function will prevent submitting the form and will redirect the page. The right way to do this via js can be, submit the form via ajax and in the success callback of Ajax run document.getElementById('myForm').submit()

PHP: Using $_POST to display form values

I have a basic HTML form with one input text field, along with a submit button. Now, I want to use JavaScript to display the content entered by the user in the text field after form submission.
Here's the code of my form:
<form method = "POST">
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" onclick = "postResul()" />
</form>
On clicking the submit button, the postResul() function is called:
<script>
function postResul()
{
var htmlString="<?php echo $_POST['tweet1']; ?>";
alert(htmlString);
}
</script>
Now, both these code snippets are stored inside a PHP file. However, on submitting the form, the data entered in the input form field doesn't get displayed. I'm displaying the $_POST['tweet1'] variable in order to display the entry submitted by the user.
What seems to be wrong here? Am I using the $_POST variable in PHP the wrong way?
If you want to display the input's value BEFORE sending it to your server:
document.querySelector("form").addEventListener("submit", function()
{
var value = this.querySelector("input[name='tweet1']").value;
alert(value);
return false; //disable sending the data to the server
}, false);
<form id="myForm" method="post" action="index.php">
<input type="text" name="tweet1" />
<br>
<input type="submit" />
</form>
If you want to display the input's value AFTER sending it to your server:
<form method="post" action="index.php">
<input type="text" name="tweet1" />
<br>
<input type="submit" />
</form>
<?php echo htmlspecialchars($_POST["tweet1"]); ?>
These are different things. You can use $_POST only after you've sent some datas to the server. When you open yoursite.com/index.php in your browser, you make a HTTP GET request. In this case, $_POST will be an empty array, since it's a GET request, no data is sent to the server. When you submit the form, you make a HTTP POST request. Your PHP can access only that data you sent to the server. With Javascript, you work on the visitor's computer, not on the server. The only one way to send the data to the server without refresing the page, if you use AJAX, and make a new HTTP POST request, that'll run in the "background". But you do not need this if you just want to display the input's value, and you don't want to save it on your server. That can be done with Javascript, and without PHP.
The code you posted above would work like this:
You make a HTTP GET request to yoursite.com/index.php.
No data is sent to the server, $_POST will be empty.
var htmlString="<?php echo $_POST['tweet1']; ?>"; In this line, you try to echo an non-existing member of $_POST, you might see an error if display_errors is not disabled.
You click on the submit button.
It has an onclick attribute, postResul (a Javascript function) is called. If you open the page's shource, you'll see this:
function postResul()
{
var htmlString="";
alert(htmlString);
}
After an empty popup is shown, and you press OK, the browser send the data to your server, and you'll able to acess the input's value via $_POST.
If you press the submit button again, you'll see submited value (and not the input's actual value), because if you open the source code, you'll see this:
function postResul()
{
var htmlString="entered data";
alert(htmlString);
}
But that isn't want you want, so see the examples above depending on what you want (save the data, or just display it in the browser).
This should work:
function postResul()
{
var htmlString=document.getElementsByName("tweet1")[0].value;
alert(htmlString);
}
But you should really read more on how client-side and server-side languages work.
You cannot use $_POST['tweet1'] to get the value when you are invoking a Javascript function. Basically client side and server side are totally different.
You can obtain the result using Javascript as:
function postResul()
{
var htmlString= document.getElementsByName("tweet1")[0].value;
alert(htmlString);
}
In HTML:
<form method = "POST">
<input type = "text" name = "tweet1"/>
<br>
<input type = "submit" onclick = "postResul()" />
</form>
Note: The above function runs in client side and not in server side.
$_POST can be used to get values of the submitted form in a php page.
Cheers.
You have to make another file. Change your code to:
<form method="POST" action="another.php" >
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" />
</form>
In file another.php you can show the variable then:
<?php echo htmlspecialchars($_POST['tweet1'], ENT_QUOTES, 'UTF-8'); ?>
You should use the form in a different way
<form method="POST">
<input type = "text" name = "tweet1" />
<br>
<input type = "submit" />
</form>
test.php file
<?php
return json_encode([1, 2, 3]);
js
$('form').on('submit', function() {
$.post('test.php', {}).done(function(response) {
alert(response);
})
})
Something like this.
Hope it's useful.
if you are using jquery library you can do this
<form method="POST">
<input type = "text" name = "tweet1" class="tweet" />
<br>
<input type = "submit" class="submit" />
</form>
$('.submit').click(function(e){
alert($('.tweet').val());
e.preventDefault();
});
jsfiddel working example http://jsfiddle.net/mdamia/j3w4af2w/2/

Do a jQuery/ajax POST on form submit

I have an html form like this:
<form action="myServer.com/test.php" method="post">
...
</form>
When the form is submitted, the user should be redirected to myServer.com/test.php and ofc send the post data to the script. BUT at the same time (or before), I want to post the same POST data to another script "myServer.com/test2.php".
$.post("myServer.com/test2.php", variableWithTheFormPOSTData);
I tried to attach an EventListener to the form submit, but that doesn't seem to work, maybe the jquery post cant be submitted fast enough before the redirection?
I hope you can help me. :(
Whenever you use a method with onsubmit, make sure it returns true, otherwise it won't submit.
use a button as your submit button sothat the form doesnt get posted at the same time you click on it. And trigger the ajax function to post the data indirectly to the second page.
<form name="myform" action="myServer.com/test.php" method="post">
...
<button onclick="doIndirectPost();"></button>
</form>
and in the success callback of ajax posting function trigger your form post
function doIndirectPost() {
//initialize variableWithTheFormPOSTData here
$.post("myServer.com/test2.php", variableWithTheFormPOSTData,function(success,error) {
//ajax post is completed now we trigger the form post to test.php
document.myform.submit();
});
}
You can do it using ajax itself, which will avoid reloading the page
<form id="form1">
.....
<input type="text" name="email"/> <!--Example input text box-->
<input type="button" id="submit"/>
</form>
and the jquery code
$("#submit").click(function()
{
$.post("myServer.com/test2.php", $("#form1").serialize());//$("#form1).serialize() will get the data in the form automatically
$.post("myServer.com/test.php", $("#form1").serialize());
});
.serialize() will automatically serialize the data from the form that is to be posted
in your server side page use this
<?php
parse_str($_POST['serialize'], $data);
$name = $data["email"]
// do your code
?>
Hope this helps,Thank you

jQuery to submit form on file selection not working

I am trying to initiate upload of a file as soon as the user selects the file. The form should disappear replaced by the "Uploading your picture..." message.
So far, all I get is the form being hidden (and message showing), but the upload is not happening. The form is not being submitted. Any ideas why?
This is the JS
<script>
$(function(){
$("#file_select").change(function(){
$(this).parents("#upload_form").submit();
$("#upload_form_div").hide();
$("#loading").show();
});
});
</script>
and the HTML
<div class="float_left" id="upload_form_div">
<h3>Select a picture for your profile (4 MB max):</h3>
<form action="http://example.com/profile/upload_picture"
id="upload_form"
enctype="multipart/form-data"
method="post" accept-charset="utf-8">
<input type="file" name="userfile"
id="file_select" />
<input type="hidden" name="upload" value="upload" />
<button id="submit" type="submit"><img height="24" width="24"
alt="Upload" src="images/icons/small/white/bended%20arrow%20right.png">
<span>Upload</span>
</button>
</form>
<form action="http://example.com/profile/remove_picture"
method="post" accept-charset="utf-8">
<button type="submit"><img height="24" width="24"
alt="Remove" src="images/icons/small/white/trashcan.png">
<span>Remove</span>
</button>
</form>
</div>
<div id="loading" style="display:none;">
Uploading your picture...
</div>
It probably has something to do with this part:
<input type="file" name="userfile"
value="onchange="return validateFileExtension(this)""
id="file_select" />
An input type=file should not have a value= attribute (and even if it did, you shouldn't put javascript in there!)
You also have some javascript in the form:
onsubmit="return validateFileExtension(this.userfile)"
If the function validateFileExtension() returns false then the form will not submit.
However, the way you have written the jQuery means that the message will still appear.
EDIT:
Change the id on your submit button to something other than "submit".
In the jQuery docs:
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.
HOWEVER:
You should consider #Abdul's solution, since the working submit will take you away from your message.
If you are using CodeIgniter and you don't want to use Ajax, you should consider using the flash functionality to display the message to the user after the form submits.
You should think of using jquery form plugin to submit your form and jquery validate plugin to validate your form for file extensions and everything.Jquery form plugin submits your form using ajax. In that way you won't be redirected to form action. Also
if you want you can consider using jquery dialog to display the result.
$("#upload_form").validate({
rules: {
MyFile: {
required: false,
accept: "jpg|jpeg|png|gif"
}
}
});
$("#file_select").change(function(){
("#upload_form").ajaxSubmit();
$("#upload_form_div").hide();
$("#loading").show();
});
Submit form on file selection and validate for CSV file input
$('#file').change($('form').submit());
$('form').submit(function(){
if($('#file').val().toLowerCase().indexOf('.csv') != -1){
$('#spinner').show();
return true;
}
else{
alert('Invalid File format. Please, upload CSV file')
return false;
}
});

How do I submit a "file" input without submit button using JavaScript?

There is a way to automatically submit a form without clicking to a "submit" button?
I have a form with one "file" input. I would submit the form after the user have selected one file.
yes, you can use the form.submit() function. Add an onchange listener on the file input and link it to the form.submit() function, like so:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" onchange="this.form.submit()" name="myFile"/>
</form>
Yes, you can add the following to the onchange event of the file input:
<input type='file' .... onchange='this.form.submit();'>
this submits the form right after the user has picked a file.
However, the user can't correct a mistaken selection before submitting - be sure to check whether this is really wise.
This solution works for me.
<form enctype="multipart/form-data" method="POST" action="/upload">
<input id="myfilefield" type="file" name="file">
<input type="submit">
</form>
document.getElementById('myfilefield').onchange = function() {
this.form.submit();
};
By the way, you don't need to use flash. Gmail do it by XHR Level 2.
I don't believe you can do this. Browsers are very, very strict about what you can do to file upload fields, because of the potential for abuse. If the user accidentally selects a private file, they wouldn't want it to immediately start uploading that file to a random server.
I'm not sure what the restrictions are with doing this in an HTML form.
You can, however, do it with Flash. Gmail does it - when I click "Attach a file", I get prompted with a file browse dialog, and when I OK that dialog the upload begins immediately, and also gives me a progress bar.
Googling for "Flash uploader" will give you many options, but I don't have experience with any of them.
The solutions that were here to add an event listener in the input didn't work for me, so I found another solution, and I wanted to share it.
HTML:
<form id="attachUpload" method="POST" action="javascript:void(0)" accept-charset="utf-8" enctype="multipart/form-data">
<input id="uploadAttachment" type="file" name="files[]" placeholder="Computer" multiple />
</form>
The code to submit the form:
$(document).on('change', '#uploadAttachment', function() {
$('#attachUpload').trigger('submit');
});
And than if you want to post that data after the form is submitted:
$(document).on('submit', '#attachUpload', function(e) {
// code here
})

Categories