Receive form input data with PHP POST - php

I'm using the jQuery tag-it plugin, which basically has an input field. Everything works well, but I am unable to receive the input field value by submitting the form with PHP.
Here's the form part:
<form action="<?=$PHP_SELF?>" method="post">
<div class="line">
<label for="tags">Tags</label>
<ul id="mytags"></ul>
</div>
<input name="submit" value="Submit" type="submit" />
</form>
Here is PHP part:
<?
if ($_POST[submit]) {
$tags = $_POST[mytags];
echo $tags;
}
?>
The demo of the plugin is here: http://levycarneiro.com/projects/tag-it/example.html
and the javascript code is here: http://levycarneiro.com/projects/tag-it/js/tag-it.js
I'll be thankful for any help.

in tpl
<script type="text/javascript">
$(document).ready(function() {
$("#tags-input").tagit({
fieldName: "tag[]",
availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"]
});
});
</script>
use fieldName: "tag[]" attribute, in backend print_r($_POST) and check what it will display

ul is not a form element which would be submitted, it's a UI element. And you need to use quotes around your array indexes, like this:
if (isset($_POST['submit'])) {

the code should look like this:
<?
if ($_POST['submit']) {
$tags = $_POST['mytags'];
echo $tags;
}
?>
you forgot the enclosing '
if you forget that php treats the submit in $_POST[submit] as a constant
EDIT:
try this:
<?
var_dump($_POST);
?>

The acutal tags are stored in this form field which is created for each tag:
function create_choice (value) {
// some stuff
el += "<input type=\"hidden\" style=\"display:none;\" value=\""+value+"\" name=\"item[tags][]\">\n";
// some other stuff
}
So you must look out not for 'mytags' but for $_POST['item']['tags'] in your PHP Code which will then give you an array of the tags.

There should be NO posted data
your code does not use any input fields!

Looking at your plugin, it seems to create hidden input fields on the fly as you add tags.
Assuming that part of the code is actually working, put the following into your PHP code.
<?php
var_dump($_POST); //this has to be in the page you POST to
?>
See if all your tags are showing up. If it is, then your JS works and your PHP is at fault. As user #ITroubs mentions, you should quote your array indices. See if that fixes it.
If no data is displayed, then your JS plugin is not working properly.
Using firebug, add a couple of tags and inspect inside the LI element of your list and see if any hidden INPUTS are being created.
Also check if there are any JS errors being reported.

Tested and solved:
<form action="<?=$PHP_SELF?>" method="post">
<div class="line">
<label for="tags">Tags</label>
<ul id="mytags" name="item[tags][]"></ul>
</div>
<input name="submit" value="Submit" type="submit" />
</form>
Here is PHP part:
<?
if ($_POST[submit]) {
$tags = $_POST["item"]["tags"];
foreach($tags as $i=>$v)
{
$tagsf .= $v;
if($i < (count($tags)-1))
$tagsf .= ",";
}
echo $tagsf;
//This shows the tags with ",". Example: dog,cat,bird,onion
}
?>

Related

How do you style input that PHP posted with a CSS selector?

I want to create a webpage that posts onto itself text inserted into an input field, using CSS to stylize said text once it becomes part of the page. However, I don't know how to refer to it with a CSS selector. I've done what every HTML-newb tries when encountering a problem and wrapped both the form code and PHP statement in classified DIVs, however, the computer visibly doesn't know what I'm trying to address. Likewise, wrapping the PHP statement in paragraph tags doesn't apply to it the stylization said tags are associated with.
For Reference, Form & PHP Code:
<form method = "post">
<textarea name="input"></textarea>
<input type="submit">
</form>
<?php echo $_POST['input'];?>
My apologies if the solution to this is obvious; I can't find information addressing it.
you could inline style it or with a class.
<form method = "post">
<textarea name="input"></textarea>
<input type="submit" name="submit">
</form>
<div class="input-value">
<?php
if(isset($_POST['submit])) {
echo $_POST['input'];
}
?>
</div>
use .input-value class in css
Please try this!
<form method = "post">
<textarea name="input"></textarea>
<input type="submit">
</form>
<?php echo "<div style='color:red;font-family:verdana;font-size:300%'>" .
$_POST['input'] . "</div>" ?>
Are you looking for this? Please let me know! Thanks!

How to show/hide textareas in a loop with jQuery?

In the following example i have a script with a loop that fetches comments from database, and gives every comment a form with a textarea and submit button so that users can interact with every comment separately.
The follow code makes the page looks a big mess and disturbing due to the repetition of the texareas.
What i need is a jQuery code that will hide the textareas and allow me to show a selected textarea individually when a link or div is clicked. I will simplify what i want in the following code.
<?php
$comments = array('comment1','comment2','comment3','comment4','comment5','comment6','comment7','comment8','comment9');
$c_count = count($comments);
for($i=0; $i<$c_count; $i++){
$comment = $comments[$i];
echo $comment;
?>
<hr />
<div style="border:1px solid #999; width:200px;">Click Here to Show Reply Form</div>
<div class="comment_box">
<form action="path/to/insert_reply.php" method="POST">
<textarea name="reply" cols="47" rows="4"></textarea>
<input type="submit" name="submit" value="Post Reply">
</form>
</div>
<?php
}
?>
This can be done quite easily with JQuery. http://api.jquery.com/ will be helpful.
In this example, the client can click on the comment_header div to view or hide the comment box. Note I added an additional identifier to the divs. There are many different ways to select individual div elements - you might consider wrapping both the comment_header and comment_box divs under a container div with a unique id attribute. Here, I choose to use the .data() JQuery capability.
PHP:
<?php
$comments = array('comment1','comment2','comment3','comment4','comment5','comment6','comment7','comment8','comment9');
$c_count = count($comments);
for($i=0; $i<$c_count; $i++){
$comment = $comments[$i];
echo $comment;
?>
<hr />
<div data-index="<?= $i; ?>" style="border:1px solid #999; width:200px;">Click Here to Show Reply Form</div>
<div id="<?= $i; ?>" class="comment_box">
<form action="path/to/insert_reply.php" method="POST">
<textarea name="reply" cols="47" rows="4"></textarea>
<input type="submit" name="submit" value="Post Reply">
</form>
</div>
<?php
}
?>
JS/JQuery:
$(document).ready(function(e) {
$('.comment_box').hide();
$('.comment_header').on('click', function(e) {
$('#' + $(this).data('index')).toggle();
});
});
Hope this is helpful. Here is the JSFiddle: http://jsfiddle.net/EUQG2/
To hide unselected textarea when a particular textarea is focused
$(document).ready(function(){
$('textarea').focus(function(){
$('textarea').not(this).hide();
});
});
You can play around this. I hope it helps
At its simplest, assuming that all you want to do is to hide the textarea elements (in this case by hiding the parent .comment_box element), and to show them by clicking the preceding div element:
$('.comment_box').hide().prev('div').on('click', function(){
$(this).next('.comment_box').toggle();
});
JS Fiddle demo.
If you want only one .content_box/textarea visible at any given point:
$('.comment_box').hide().prev('div').on('click', function(){
var target = $(this).next('.comment_box');
$('.comment_box').not(target).hide();
target.toggle();
});
JS Fiddle demo.
References:
hide().
next().
not().
on().
prev().
toggle().

How can I send contents of a div as a POST parameter?

I have this Code:
<div contenteditable="true"><p><?php echo $row[1]; ?></p></div>
Can I take the contents of the div and send them as a POST parameter in order to use them in the PHP. It would be good if I can use: onchange="this.form.submit()".
Thanks!
It is not possible to post contents of div tags, as this is only possible on form elements. The workaround for this would be to use some Javascript that populates a hidden field when a form is submitted, and the hidden field is posted instead.
Observe the following HTML. See that there is an onsubmit event attached to the form element. What we're saying to the browser here is when the form is submitted, first call the Javascript function process, and only submit if said function returns true:
<form method="post" action="process.php" onsubmit="javascript: return process();">
<input type="hidden" id="hidden" name="content" vlaue="<?php echo $row[1] ?>">
<div contenteditable="true" id="content"><p><?php echo $row[1] ?></p></div>
<button type="submit">Post</button>
</form>
This would be your Javascript. What you're doing is getting the innerHTML of the element with the id content and assigning it to the value of the element with the id hidden and return true so the form can be successfully submitted:
<script>
function process() {
document.getElementById("hidden").value = document.getElementById("content").innerHTML;
return true;
}
</script>
And in the process.php file, just output the posted content:
var_dump("Posted content: " . $_POST['content']);
Hope this helps!

Questions regarding forms and php (clearing form, live refresh, multiline)

I have several questions regarding forms and PHP but if I should put them into different posts then I will.
Here is my form code:
<form id="t-form" name="tForm" action="translate.php" method="POST">
<div id="t-bar">
<div class="t-select">
<select name="start-lang" id="choice-button">
<option value="english">English</option>
</select>
<label>into</label>
<select name="end-lang" id="choice-button" onChange="document.forms['tForm'].submit();">
<option value="caps"<?php if ($resLang == 'caps') echo ' selected="selected"'; ?>>CAPS</option>
<option value="lowercase"<?php if ($resLang == 'lowercase') echo ' selected="selected"'; ?>>lowercase</option>
</select>
<input type="submit" id="t-submit" value="Translate">
</div>
</div>
<div id="t-main">
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onChange="document.forms['tForm'].submit();"><?php echo $source; ?></textarea>
<input type="button" id="t-clear" onclick="this.form.elements['t-src'].value=''">
<textarea id="txt-result" name="txt-result" readonly disabled="disabled" placeholder="result..."><?php echo $result; ?></textarea>
<input type="button" id="t-copy" name="t-copy">
</div>
</form>
Question 1: I currently have onclick="this.form.elements['t-src'].value=''" which clears one textbox when the button is pressed. Is it possible to have the same attribute clear both textareas in my form? I can't seem to find an answer anywhere for clearing 2 elements with 1 button. I do not want to clear the form as I would like to keep the selected dropdown values so that is why I'm doing it this way.
Question 2: How would I go about implementing a live refresh of the results textarea so they user can simply type and see the result? I've look at the ajax and jquery required and am confused as most don't show how to output to a form element and only to a div. (Similar to google's translate)
Question 3: I realized that if a user does a new line in the textarea, when they submit for translate, it gives them a php header error. Any ideas how I can avoid this? This is my header for the translate.php file used in the form:
header("location: /?txt-result=$result&t-src=$textSource&end-lang=$outputLang");
I am merely trying to do this as a learning excersise and would really appreciate any guidance or answers to the three questions. Many thanks for your help!
question 1
you should have:
onclick="clearTextboxes();"
and in javascript something like:
//if you want to delete all the inputs that are of type text
function clearTextboxes(){
var inputs = document.getElementById('t-form').getElementsByTagName('input');
for (var control in inputs){
if(inputs[control].getAttribute('type') == 'text'){
inputs[control].value = '';
}
}
}
question 2
it is far too broad to put here as an answer, you should really look at jQuery's $.ajax, and create a different question with specific doubts.
question 3
use the PHP urlencode() function
Answer 1: Have your onclick event call a function which clears those values for you:
<script type="text/JavaScript">
function clearTextareas()
{
this.form.elements["t-src"].value = "";
this.form.elements["txt-result"].value = "";
}
</script>
<input type="button" id="t-clear" onclick="clearTextareas()">
Answer 2: Add an onkeydown event in the source textarea that peforms the translation (or whatever it needs to do) and then puts the result in the result textarea:
<script type="text/JavaScript">
function translateText()
{
var text = this.form.elements["t-src"].value;
// do something
this.form.elements["txt-result"].value = text;
}
</script>
<textarea id="txt-source" name="t-src" autofocus="autofocus" placeholder="Type in what you would like to convert…" onkeydown="translateText()"><?php echo $source; ?></textarea>
Answer 3: Perhaps an onsubmit event in the form element that will sanitize the input from the text area. Have a look at JavaScript's encodeURIComponent. Perhaps this will work for you:
<script type="text/JavaScript">
function sanitize()
{
this.form.elements["t-src"].value = encodeURIComponent(this.form.elements["t-src"].value);
}
</script>

Form: POST a string & get the result in the same form field?

Is to possible to POST a string in the form field and get converted string result in the same form field?
I use the code:
<?php
$string='';
if (isset($_POST['string']))
$string=$_POST['string']
if (isset($_POST['DoStuff']))
{
$string = doStuffWithThisString($string);
}
if (isset($_POST['DoOtherStuff']))
{
$string = doOtherStuffWithThisString($string);
}
?>
<form action="" method="post">
<!-- blank action attribute will post form to the current page-->
<input type="text" value="<?=$string?>" name="string" />
<!-- <?=$string?> is the same as <?php echo $string; ?> -->
<input type="submit" value="Do Stuff" name="DoStuff" />
<input type="submit" value="Do Other Stuff" name="DoOtherStuff" />
</form>
but get the result above form field...
Are you sure short tags are enabled?
See: http://php.net/manual/en/ini.core.php
If they are not, just use:
<?php echo $string; ?>
I don't see why it wouldn't work.
Depending on the browser, the button names may not be "DoStuff" and "DoOtherStuff". For example, in IE it will be $_POST['DoStuff_x'] and $_POST['DoStuff_y'].
do a print_r($_POST); to see what the form data is being posted as.
If you would use the same name in the submit fields, upon page reload in $_POST['name'] you would get the value you clicked on.
I think that's the solution to the issue, but can someone confirm this ?

Categories