form fields not passing through when submit is done via javascript - javascript

I can't seem to figure out why this is happening. Any help would be appreciated. I have an html form with two fields. When I run the page and submit the form with a submit button, the field values pass through ok. But if I run the same page and submit with javascript as I show here, the receiving file shows null values for both x and y.
Source File:
<html>
<head>
<script>
document.invoice.x.value = "1";
document.invoice.y.value = "2";
</script>
</head>
<body>
<form method="post" name="invoice" id="invoice" action="process_payment.php">
X: <input type="text" name="x"> Y: <input type="text" name="y">
<script>document.forms["invoice"].submit();</script>
</form>
</body>
</html>
Target File (process_payment.php):
<?php
session_start();
print "<pre>"; print_r($_POST); print("</pre>");
?>
Output I am getting:
Array
(
[x] =>
[y] =>
)

you can set your value in javascript like this:
document.getElementsByName("x").value="1";
document.getElementsByName("y").value="2";
and to submit the form use:
document.forms["invoice"].submit();

Please check this
Use below BEFORE body Close tag check This
<script>
document.invoice.x.value = "1";
document.invoice.y.value = "2";
</script>
OR use jQuery
<script>
$("[name='x']").val("1");
$("[name='y']").val("2");
</script>

Related

clearing textarea from outside php file doesn't work

I've looked around trying to find a solution to clear a textarea from an outside php file.
Basically this is my form:
<iframe name="post_target" style="display:none;"></iframe>
<form action="post_status.php" method="post" target="post_target">
<div class="status_update">
<div id="update_type"></div>
<?php load_picture($_SESSION['profile_picture']); ?>
<textarea class="scrollabletextbox" placeholder="Share your thoughts" onkeyup="textAreaAdjust(this)" name="status_update" id="status_update"></textarea>
</div>
<div id="update_options">
<button id="post" name="post" onclick="javascript:postUpdate()">Post</button>
</div>
</form>
And it calls post_status.php who's structure is basically:
<?php
function post_status($conn, $status){
// function
}
$status = $_POST['status_update'];
post_status($conn, $status);
?>
<script type="text/javascript">
// clear textarea
document.getElementById('status_update').value = "";
alert("passed clear");
</script>
What happens is the following : the php function executes properly, but the JS part doesn't. If I leave out ' .value = "" ' it works fine, if I don't then the alert never shows.
Does anyone have any idea concerning this issue ?
You use status_update on class attribute (div) and id attribute (textarea)
you need to make a choice.

Form post on run time doesn't work - jQuery / AJAX / Post [duplicate]

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed last year.
I am trying to post a data on run time and I want to see this data same time. But I don't understand clearly how can I do. I think my problem is I could not choose the element correctly. What is wrong on my code ? Thanks all from now :)
My Error is : Notice: Undefined index: username in C:\wamp\www\eva\check.php on line 3
Line 3 : echo $username = $_POST["username"];
form.php
<html>
<head>
<title>jQuery</title>
</head>
<body>
<div class="formwrapper">
<form method="post" action="" name="form">
<input type="text" id="rname" class="inputa" name="uname" placeholder="Username">
<div id="feedback"></div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="myScript.js"></script>
</body>
</html>
check.php
<?php
echo $username = $_POST["uname"];
?>
myScript.js
$(document).ready(function() {
$("#feedback").load("check.php").show();
$("#rname").keyup(function() {
$.post("check.php", { username: uname.value },
function(result){
$("#feedback").html(result).show();
})
});
});
You are POSTing the value as username and trying to retrieve it as uname. Rename your key in PHP:
$username = $_POST['username']
It's probably also a good idea to check if the value exists and return a nice error message instead of letting your code fail.

jQuery.get to read a file and use the data into a form

I want the script to do the following:
On page load, read a text file with a number (just one line)
Increment the number by 1
Insert the number in an <input> box of the form
Once <form> is submitted, write the number to the text file
When the form gets loaded again, it will rerun the code and the number will increment by 1. This is basically to pre-populate a field with a unique and progressive number prior to form submission.
I am currently using jQuery, PHP and of course HTML:
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js">
$.get("http://www.domain.com/tools/formdata.txt");
function test(){
$.get('http://www.domain.com/tools/formdata.txt', function(data){
x = data++;
});
}
</script>
</head>
<body onload="test()"/>
<form action="save_json.php" method="post">
Contract: <input type="number" name="contract" id="contract" value="x" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
PHP
<?php
if(isset($_POST['contract'])) {
// if form fields are empty, outputs message, else, gets their data
if(empty($_POST['contract'])) {
echo 'All fields are required';
}
else {
// adds form data into an array
$formdata = $_POST['contract'];
if(file_put_contents('/var/www/domain/tools/formdata.txt', $formdata)) echo 'Data successfully saved';
else echo 'Unable to save data, try again or contact IT';
}
}
else echo 'Form fields not submitted';
?>
First: I recommend that instead of javascript, you do this with PHP file_get_contents('formdata.txt') at the start of your file, and then you echo it in. That way, the value will be there on load, rather than having to wait for the HTML to render and the javascript to run. Also, it is a much better practice and will let you do a lot more things if you choose to expand the page.
However, here's the solution to the issue presented:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
var x;
function test(){
$.get('file.txt', function(data){
console.log('data',data);
var x = ++data;
console.log('x',x);
$('#contract').val(x);
});
}
</script>
</head>
<body onload="test()"/>
<form action="aoeu.php" method="post">
Contract: <input type="number" name="contract" id="contract" /><br />
<input type="submit" id="submit" value="Invia" />
</form>
</body>
</html>
The things to note:
Close off your <script> tag including the jquery library, then open another one after it.
No need to do the first $.get() you have - save it for the function.
var x = data++; - this increments data AFTER its value has been assigned to x. So, it will never increase. Do ++data instead, and it increments before.
You need to place it somewhere afterwards. How you had the input (value='x') is just trying to put the character "x" into the input. Use javascript to edit the functions value, as in my example.
Your PHP works fine.

Check if the button has been pressed after js submit

I'm trying to check if a form type button has been pressed after i submit the form with javascript:
<script>
function DeleteIt(string){
var pattern = string.indexOf('_');
var prof_nr = string.substr(pattern+1);
var delete = confirm("Want to delete it?");
if( delete == true ){
document.forms['form'].submit();
}else{
alert('Cancel');
}
}
</script>
<form method="POST" name="form">
<input type="button" name="delete" value="Delete" id="prof_'.$row['code'].'" onclick="DeleteIt(this.id);">
</form>
if(isset($_POST['delete'])){
echo 'Pressed';
}
But it doesn't run into the condition though it has been pressed.
I can't use a submit type,because i already have one in the form , which is used for a search field.Whenever i type something and hit enter,it triggers the function,that's why i use button.
You have used so many language keywords as variable names in your code like delete, string.
You can not use reserved words of a programming language as your
variable names.
This is the working code-
<script type="text/javascript">
function DeleteIt(string1){
var pattern = string1.indexOf('_');
var prof_nr = string1.substr(pattern+1);
var delete1 = confirm("Want to delete it?");
if( delete1 == true ){
document.forms['form'].submit();
}else{
alert('Cancel');
}
}
</script>
<form method="POST" name="form">
<button name="delete" id="prof_'.$row['code'].'" onclick="DeleteIt(this.id);">delete</button>
</form>
<?php
if(isset($_POST['delete'])){
echo 'Pressed';
}
I guess a button, which is used to submit a form, will not submit its own value.
Since you do not want the form to be submitted by pressing the enter key, my idea is to add a hidden field which tells you what to do. The following code adds such a hidden field named specialAction, which is normally set to save. When the delete button is pressed, however, its value is changed to delete. In PHP, you would have to check the field's value then:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<script type="text/javascript">
function DeleteIt(id){
var pattern = id.indexOf('_');
var prof_nr = id.substr(pattern+1);
var deleteVar = confirm("Want to delete it?");
if( deleteVar == true ){
document.forms['form']['specialAction'].value = "delete";
document.forms['form'].submit();
}else{
alert('Cancel');
}
string
}
</script>
<form method="POST" name="form">
<input type="hidden" id="specialAction" name="specialAction" value="save">
<input type="text" name="testPurpose" value="Hit enter after focusing">
<input type="button" value="Delete" name="delete" id="prof_test" onclick="DeleteIt(this.id);">
</form>
<?php
if(isset($_POST['specialAction'])) echo $_POST['specialAction'];
?>
</body>
</html>
A side note: Do not use delete as a variable name, because it is already used as an operator. Also, you should tell the browser to interpret JavaScript using <script type="text/javascript"> and not just <script>.

dropdown on change submit not executing php code

I have a form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
the form has multipe input type text and 1 dropdown menu.
I also have a submit button called (submit1)
<input class="submit-button" type="submit" name="submit1" value="UPDATE MY INFORMATION" />
My PHP read like this :
if (isset($_POST['submit1']))
{ .... }
If I press the button, it works, no problem.
BUT I also want to submit the form from the dropdown menu change... so it can be executed by both the press of the button OR the change in dropdown... so I have the following for my dropdown
<select name="country" onchange="this.form.submit()">
when I select my dropdown, the page refreshed, but the code in my PHP is not executed... I figured it has to do with the name of $_POST['submit1']...
How can I change onchange="this.form.submit() for it to execute the code in if(isset($_POST['submit1']))...
Thank you
You should avoid inline javascript like that. It's ugly, and reduces readability. The easier way would be to give your elements IDs, like so:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" id="myForm">
But if you don't want to, you can use QuerySelector and grab the name attribute of your input.
var x = document.querySelector("[name='country']");
x.addEventListener("change",function() {
this.parentNode.submit(); //get form parent and submit
});
I'm a bit confused why you're checking the submit button for a value as well, wouldn't you want:
if (isset($_POST['country'])) { ... }
Instead?
You could just document.getElementById('submit1').click() after setting the id on your submit button the same as its name. Of course, you would also do this onchange. I would separate my JavaScript from HTML, so it's cached into your Browser memory. Give your inputs, selects and the like the same id as their name, with the exception of radio buttons, and possibly checkboxes.
Let's start with some common.js:
//<![CDATA[
var doc = document, bod = doc.body;
var IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function gteIE(version, className){
if(IE >= version)bod.className = className;
}
function E(e){
return doc.getElementById(e);
}
//]]>
Now for your otherpage.php:
//<![CDATA[
var cntry = E('country'), sub1 = E('submit1');
cntry.onchange = function(){
sub1.click();
}
// note that the format E('submit1').click(); would also work
//]]>
Of course, you should have:
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='otherpage.js'></script>
</body>
</html>
Check for isset($_POST['country'])
And onchange add this to the drop-down,
onchange= 'document.getElementsByName("submit1")[0].click();'

Categories

Resources