PHP not posting textbox values produced by jQuery - php

What I have:
I have a form with two normal text boxes and two disabled text boxes.
The disabled elements receive their values from the enabled elements via jQuery.
The values of the four elements are then posted via PHP
Note: My form is being used as part of acustom WordPress page.
The problem:
The disabled elements (i.e. values derived via jQuery) are not posting via PHP.
Visual:
My code:
PHP:
<?php
if(isset($_POST['submit'])) {
echo 'a= '.$_POST["textbox_a"].'<br />';
echo 'b= '.$_POST["textbox_b"].'<br />';
echo 'c= '.$_POST["textbox_c"].'<br />';
echo 'd= '.$_POST["textbox_d"].'<br />';
}
?>
jQuery:
<script type="text/javascript">
jQuery(document).ready(function($) {
// Code here will be executed on document ready. Use $ as normal.
// alert("jQuery is working fine :-)");
$( "button" ).click(function( event ) {
event.preventDefault();
$('[name=textbox_c]').val($('[name=textbox_a]').val());
$('[name=textbox_d]').val($('[name=textbox_b]').val());
});
});
</script>
HTML:
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<input type="input" name="textbox_a" />
<input type="input" name="textbox_b" />
<button>[jQuery] Click me to transfer</button><br />
<input type="input" name="textbox_c" disabled="disabled" />
<input type="input" name="textbox_d" disabled="disabled" />
<input type="submit" name="submit" value="[PHP] Click me to post" /><br />
</form>
My question:
Why isn't PHP treating my jQuery derived values as regularly inputted values? Though I've never used Ajax, am I correct in assuming that Ajax is the solution? The examples I've seen for Ajax seem a little overkill for what I'm trying to achieve but I'm happy to delve into it if it's the only way forward.

use readonly instead of disabled
From Mozilla:
Disabled
This Boolean attribute indicates that the form control is not available for interaction. In particular, the click event will not be dispatched on disabled controls. Also, a disabled control's value isn't submitted with the form.

Disabled inputs will not be submitted with the form; that's part of the defined behaviour of disabled.

The disabled elements (i.e. values derived via jQuery) are not posting via PHP.
Disabled elements do not get sent to the server. You can use readonly instead of disabled, the difference is readonly inputs are sent to the server.

I don't believe disabled form elements actually ever get posted (regardless of being dynamically created by jQuery). I would use the readonly="readonly" attribute instead.

Related

Passing variable from html input to included php file

I have situation where I have an accordian and I am referencing a php file gridlist.php within another php file displayvar.php. In other words the context of displayvar.php are shown in the webpage gridlist.php. Now gridlist.php has a checkbox input:
<input type="checkbox" id="foodlike" value="icecrm">I like ice cream</input>
<input type="checkbox" id="foodlike" value="pizza">I like pizza</input>
<input type="checkbox" id="foodlike" value="soda">I like soda</input>
Now when I check on the checkboxes in the table referenced by gridlist.php displayvar.php should be able to display a list of the items checked. For instance it should display if all three checkboxes are checked:
icecrmpizzasoda
If the last one is checked then only soda should be displayed. Keep in mind because this displayvar.php is displayed within the context of the website gridlist.php I used the following command in gridlist.php:
<?php include 'displayvar.php'; ?>
I tried in the displayvar.php to obtained the variables foodlike (as defined by the variable id in the checkbox gridlist.php) from gridlist.php and then echo them based on this snippet of code:
<?php
$like=$_POST['foodlike'];
echo "$like";
?>
How can I tweak this code to get my desired result?
You can achieve this with :
gridlist.php
<form method="post" action="displayvar.php">
<input type="checkbox" name="icecrm" value="icecrm">I like ice cream</input>
<input type="checkbox" name="pizza" value="pizza">I like pizza</input>
<input type="checkbox" name="soda" value="soda">I like soda</input>
<input type="submit" value="Submit">
</form>
displayvar.php
<?php
$icecrm = isset($_POST['icecrm']) ? $_POST['icecrm'] : null;
$pizza = isset($_POST['pizza']) ? $_POST['pizza'] : null;
$soda = isset($_POST['soda']) ? $_POST['soda'] : null;
echo is_null($soda) ? $icecrm.$pizza : $soda;
?>
As you mentioned you did not want a submit button, you'll probably want some sort of "interactive", instant solution and bypass going to the server, i.e. bypass PHP. Since the include 'foo.php'-statement effectively dumps all contents of foo.php into the current file (you could say it "merges them into one"), all interactions happen on the same page. Thinking about your setup as "file A is communicating with file B via the server" is wrong - there is only one file/page.
So, having said all this, my proposed solution uses Javascript and the seemingly omni-present jQuery library, which you will have to include in your page. The snippet below binds an event-handler to the inputs' change-event, which is triggered when a checkbox or radio are checked or the value of a text-input is changed. Then, we append the checked value to a dummy container for display.
$(function() {
var $likes = $('#likes');
// bind event handler to all input-elements
$('input').on('change', function() {
var $input = $(this),
oldText = $likes.text();
if ($input.is(':checked')) {
$likes.append($input.val());
} else {
$likes.text(oldText.replace($input.val(), ''));
}
});
});
label {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="icecream">
<input type="checkbox" name="icecream" id="icecream" value="icecrm">I like ice cream</label>
<label for="pizza">
<input type="checkbox" name="pizza" id="pizza" value="pizza">I like pizza</label>
<label for="soda">
<input type="checkbox" name="soda" id="soda" value="soda">I like soda</label>
<span id="likes"></span>
Edit: This is how I would lay out the "root" file containing the two gridlist.php and displayvar.php, along with the Javascript required to manipulate the DOM:
<html>
<head>
<title>Test</title>
<style>
label {
display: block;
}
</style>
</head>
<body>
<!-- This will be in a file you called 'gridlist.php' -->
<label for="icecream">
<input type="checkbox" name="icecream" id="icecream" value="icecrm">I like ice cream</label>
<label for="pizza">
<input type="checkbox" name="pizza" id="pizza" value="pizza">I like pizza</label>
<label for="soda">
<input type="checkbox" name="soda" id="soda" value="soda">I like soda</label>
<!-- // -->
<!-- This will be in a file you called 'displayvar.php' -->
<span id="likes"></span>
<!-- // -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $likes = $('#likes');
// bind event handler to all input-elements
$('input').on('change', function() {
var $input = $(this),
oldText = $likes.text();
if ($input.is(':checked')) {
$likes.append($input.val());
} else {
$likes.text(oldText.replace($input.val(), ''));
}
});
});
</script>
</body>
</html>
Edit 2:
You still seem to be having problems, so I shall try to clarify why I think you are not succeeding.
Using only PHP, it is not possible to access the value of a checked checkbox without submitting the form back to the server.
To retrieve the value of a checkbox that has been checked by the user, you essentially have only two possibilities.
Option 1: Submit the form using POST/GET
This entails you having a <form> element enclosing the inputs along with a submit button for submitting the form. This is how (probably) 98% of forms on the Internet work. The data in the form is sent, using either the POST or GET method, to the script you specify in the form-tag. Consider this as an example (text omitted):
<form action="handler.php" method="get">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<button type="submit"></button>
</form>
When the user clicks the submit-button, the form is sent to handler.php via the GET method. There, the form data will be available in the $_GET array. Same applies for POST. Now, an often-used approach is to submit the form to the same script via action="#", meaning you need not have a dedicated handler, but can process data within the same script as your form. Obviously, you will have to distinguish two cases: one initial case where no data is set in $_GET/$_POST, and one submission-case when the data is set.
The same applies to data stored in the $_SESSION, btw: again, you will have to tell a server-side script to put the data you want in the user-session; only then will you be able to retrieve it again.
A similar approach I would call "Option 1 b)" is submission via AJAX. This is basically form submission without leaving/reloading the page. Sending the data is done via Javascript and an "XMLHttpRequest". An XHR lets you send any type of data, not only XML. Again, similar logic applies: you serialize the data in some way, provide an endpoint, usually a script, to talk to, and communicate the data to that script via POST/GET. Then your script can handle the data and return a response, which will be available in the JS that initiated the AJAX-request.
Option 2: By accessing the DOM directly
The DOM is the "tree" that is made up of the HTML-elements of your page. Using Javascript, one can access and modify these elements, remove specific ones or add new ones. This API used to be implemented quite differently across browsers, which is why libraries like jQuery or Prototype were created: they provide a unified API across different user agents.
We can use two features of these libraries:
respond to (user-triggered) events
access elements and data stored therein
This is the approach I used in my answer, which I will not repeat here and you can read above. We respond to the event of the user clicking on a checkbox, and access that very checkbox to retrieve the value-data and process it further.
TL;DR
You have two options: submit the form to a script and process the data there; or, manipulate the DOM to catch user-events and pull out the values.
Credit: this is summing up every answer and comment in this thread, especially those of Obsidian Age and Valentin Papin, who both gave great answers that would lead to a clean and functional result.

How to not refresh page's previous field input values after press submit

I have an input like this:
<input value="<?php echo $formdata['title'] ?>" type="text" name="title" id="Editbox2">
This is an edit page, I load database data into fields with echo, replace them, and hit submit to update them.
But when I hit submit it refreshes the old data onto browser's fields, how can I prevent this?
Submit your form using ajax request with jquery submit.
Use action="javascript:;" for the form tag
You need to handle the script with javascript, then prevent the default behaviour, which is refreshing the page. Here is an example:
*I haven't tested this, but from what I recall this is what I used to do. Let me know if it doesn't work, I'll give other suggestions.
<form>
<!-- elements inside -->
<input type="submit" id="submit-btn" value="Submit"/>
</form>
and in your javascript have the following:
<script>
$("#submit-btn").click(function(e){
e.preventDefault();
// handle form here with your JS
});
</script>

How to change a PHP variable with a HTML button click?

I am trying to change a PHP variable with either a HTML button click, or another appropriate way.
Unfortunately, I am unable to post a majority of my code here, but I'll supply as much as possible.
Firstly, I have two buttons on my site. They each call two different javascript functions, but they load the same HTML form. The form is then submitted to a MySQL database, depending on which button was clicked at the beginning.
Instead of having both the buttons load the same form, I would like them to load different forms. I would like to do this by saving a PHP variable when the user clicks on either button.
I have searched online quite a bit, but I found no direct answer to my question.
Here is a slight example:
HTML button to add a quiz:
<h2>
<button id='opener' class='roundButton add' value='' onClick="OpenNewQuizDialog();">
</button>
Create Quiz
</h2>
HTML button to add a presentation:
<h2>
<button id='opener' class='roundButton add' value='' onClick="OpenNewPresDialog();
</button>
Add Presentation
</h2>
Both Javascript functions:
function OpenNewQuizDialog()
{
$( "#dialog" ).dialog( "open" );
$('#dialog').dialog({title:"Create Quiz"});
$('#dialogtype').val("addquiz");
}
function OpenNewPresDialog()
{
$( "#dialog" ).dialog( "open" );
$('#dialog').dialog({title:"Create Presentation"});
$('#dialogtype').val("addpres");
}
The HTML Form that is being opened:
<div id="dialog" title="Edit Settings">
<form name="editForm" method="post" action="createplay.php">
<input type=hidden id='dialogid' name='dialogid' value=''>
<input type=hidden id='dialogtype' name='dialogtype' value=''>
<input type=hidden id='uid' name='uid' value='<?php echo $userid; ?>'>
<div>
Name: <input type='text' id='nameEdit' name='nameEdit' value=''>
</div>
<div>
Data: <textarea id='textEdit' name='textEdit' row='10' cols='50'></textarea>
</div>
<input type="submit" class="roundButton upload" value="" />
</form>
</div>
What I have tried:
I tried adding the following into the onClick part within the HTML buttons:
quiz button: <?php $create_type = 'createquiz' ?>
presentation button: <?php $create_type = 'createpres' ?>
I then tried to make an 'if' statement to see which button was clicked, so I could show the appropriate form. Although, the value of $create_type was always 'createpres' since it was being called last on the page. It was like the PHP was being called, even though the HTML onClick was not being called.
Is there a better way to approach this?
PHP is a server side language while Javascript runs in client. That means they both run separately. But if you would like them to process together, such as getting data to be displayed using javascript, you will have to use AJAX.
There is no need for the extra variables as you set a form control with the appropriate value
$('#dialogtype').val("addquiz");
The form will receive this value:
<input type=hidden id='dialogtype' name='dialogtype' value=''>
Now it is up to your php script (createplay.php) whether the $_POST['dialogtype'] == 'addquiz' ) or the other value and process the data as intended
You can't create a php variable via html as php is server side and html is client side. :)

How to get a form name in php script?

For my php file, I need to grab the unique form name.
The php file is executed when a user clicks the submit button. However, there are multiple submit button each with the same id, but they all have unique names. I need the name when they click on the submit button.
you dont want elements in html with the same id - bad practice in general. Your page will likely load normally but an html validator will notice it as an error.
html validator: http://validator.w3.org/
without seeing your code, its difficult to give you a definitive answer. if you have miltuple forms you can use hidden inputs. e.g.
<input type="hidden" name="form_name" />
Otherwise you can use javascript to put data in the form when the button is clicked. example javascript using jquery
html:
<form id="formid" >
<button type="button" id="someid" onclick="submitForm('btn1')" />
<button type="button" id="someid" onclick="submitForm('btn2')" />
<input type="hidden" id="btnsubmitid" value="" />
</form>
js:
function submitForm(btnID){
$("#btnsubmitid").val(btnID);
$("#formid").submit();
}
1 way is to put a hidden input inside of your form.
<input type="hidden" name="formName" value="[name of form]" />
then in your php, you can get it using
$form-name = $_POST['formName'];
pretty sure there are other ways, but this came to mind first.

How to disable input field without affecting the value of the field in a PHP form?

I'm creating a demo page where certain setting fields have to be disabled. I have tried disabling the input with the value remaining intact, just greyed out. I have disabled the inputs using disabled="true". When submitting the form, the value disappears in spite of being there before. How do I prevent the value from disappearing whilst simultaneously disabling the said fields?
If you want the value to be displayed and and not changed , you can use readonly
<input type="text" name="xxx" value="xxx" readonly="readonly" />
If you want the value to be hidden and submitted to the action file you can use type =hidden
<input type="hidden" name="xxxx" value="xxx" />
More about HTML input tag can be found here
http://www.w3schools.com/tags/tag_input.asp
disabled form fields are not submitted under any circumstances.
The most common way to avoid this problem is making them readonly and adding an input[readonly] { ... } css rule to make the text gray like in a disabled field.
You might also want to use some JavaScript to prevent it from being focused; could look like this if you have jQuery:
$('input[readonly]').live('focus', function(e) {
$(this).blur();
});
use readonly attribute instead of disabling
another approach would be to store values in PHP session and keep them on the server.
Just throwing suggestions around here.
You could disable the field as normal with Javascript, but before the field get's disabled you could use Javascript to input the value of that field into a hidden field.
function runme() {
var newval = $('#field1').val();
$('#hiddenfield').val(newval);
$('#field1').attr('disabled', 'disabled');
}
<input id="field1" name="field1" type="text" value="this val" />
<input id="hiddenfield" name="hiddenfield" type="hidden" />
<input type="button" onclick="runme();" />
You could also use a hidden field of the same name with the correct value and retain your disabled field. Although do not trust 100% the data in a hidden / read only field as they could still be changed (through web dev tools or similar)
For input type="file" make sure you do this:
<style>
input[type=file][readonly] {
pointer-events: none;
}
</style>
<script>
$('input[type="file"]').prop('readonly', true);
</script>

Categories