Adding text to an array and displaying the array in php - php

I am trying to create a little php programme where I enter text into a text field. I then want the text to be added to an array. I do this by calling a function when the 'Add' button is clicked. After the button is clicked, I want the array entries to be displayed and the number of entries too. Here is the code I have so far, but it doesnt work :P
I have tried a few things, but nothing seemed to work.
I changed it to this now:
<form action="array.php" method="POST">
<fieldset>
<legend>Enter text here</legend>
<p>text: <input type="text" size="60" name="text"></p>
<p><input type='button' name='add' value='Add' onclick= "<?php add() ?>"></p>
</fieldset>
</form>
<?php
global $array;
$array = array();
function add()
{
if(isset($_POST['text']))
{
array_push($array, $_POST['text']);
}
return $array;
}
$arraystring = implode(", " , $array);
echo $arraystring;
?>

You have a couple of problems here. First:
<script>
function add_script(){
alert("<?PHP add(); ?>");
}
</script>
The alert does not make sense here. You cannot pass data between javascript and php like that. What you would need is AJAX. The easiest solution would be Jquery's ajax function. So you would need to set up a function to handle the data, a separate php script to receive it and process it and your safest bet is to return a JSON string which the initial script would process, read and return the data.
The second very big problem is the add() function - a function may not return more than one value. Whenever the interpreter sees
return $x;
The function will stop there and return whatever you've given it. The second will be ignored as the function has been terminated.
Your second option would be to post the entire form to the same script
<form method="post">
<!--the form inputs here-->
</form>
and when the "Add" button is clicked it will post the entire data to itself. and then in the PHP script you would need to add a condition to handle the case:
<?php
if($_POST && $_POST['text']) echo $_POST['text'];
?>

Related

How to call php function on html form submit - in the same page

Okay so I have an html form in Add.html. When I click submit, I would like the data to be added to my database via php and then return to the same form with "instance added" or "failed blah blah."
The only way I know how is to set the form action to a separate php file and call that - but then the php file renders and I do not return to the same form.
I would like to not have to add a "return to form" button and would prefer to return to the form on submit with a status message.
Any better ways to do this?
A very simple way to do is to do following :
yourpage.php
<?php
if(isset($_POST)){
//data posted , save it to the database
//display message etc
}
?>
<form method="post" action="yourpage.php" >....
You can do a redirect in php, to the html form - and you can set a "flash message" - to show "instance added" by saving "instance added" to the session and showing that value when you redirect to html.
you can use this trick
<?php if (!isset $_POST['Nameofyourinput']){
?>
<form method="post" action="add.html">
// your inputs here along with the rest of html
</form>
<?php
}
else
{
// Update you database and do your things here
//in your request variable you can add the error you want if things didn't go well, for example
$result = mysqli_query($connection, $sql) or die('Instance not added !'.$req.'<br>'.mysql_error());
// and then
echo (" instance added")
};
The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".
Just give nothing to the action attribute. It will refer to your current page.
<form method="post" action="">
Other way to do this are:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Or just add '#'
<from method="post" action="#">
To handle php code. Write your code inside it.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// write your code here.
}
You should change your file extension from .html to .php .
Well you can employ old school AJAX. For instance,let's say we have a form that takes in a number N,and once we click the calculate button we should see the result the of 2^N displayed on the same page without the page being refreshed and the previous contents remaining in the same place. Here's the code
<html>
<head>
<title> Simple Math Example</title>
<script type="text/javascript">
var request = new XMLHttpRequest();
function createAjaxObject(){
request.onreadystatechange = applyChange;
request.open("POST","calculate.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("N="+document.getElementById('N').value);
}
function applyChange(){
if(request.status == 200 && request.readyState == 4){
document.getElementById('resultSpace').innerHTML = request.responseText;
}
}
</script>
</head>
<body>
<fieldset>
<legend>Enter N to get the value of 2<sup>N</sup> ::: </legend>
<input type="text" name = "N" id = "N">
<br>
<input type="button" value = "Calculate" onclick="createAjaxObject()">
</fieldset>
<div id="resultSpace">
</div>
</body>
The file calculate.php is the same file with the above code. When the calculate button is clicked, it calls a function createAjaxObject which takes in a value N and sends the value to the same file via the POST method. Once the calculation is done, a response will be sent. And if the response is successful, it will be sent to a function called applyChange which will render it to the same page via JavaScript.

pass the value inside php while loop to javascript using button onclick

I have a huge form and in part of the form I want to insert some value to database using js. I might not be clear about how to present the question but here my needs are:
suppose, I have two tables in database table1, table2. In a html form:
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1){ ?>
<option value"<?=$row['name']?>" name="option1"><?=$row['name']?></option>
<?php } ?>
</select>
<input type="file" name="file">
<input type="button" name="button" onclick="submit_form(true,'');">
Now, I want to pass the $row['name'] value to submit_form() function in javascript. The javascript code will check the value and return it to the form to submit it. My question is since the $row['name'] from table1 is inside the while loop, I cannot pass the value to javascript. If the form was small I could have done using submit button and check $_POST('submit') type. I want to insert the $row['name'] in this form to table2 as file name associated with the name.
As i understand you want to pass selected value from form to submit_form() function?
function submit_form(param1, param2){
var passedValue = document.getElementById('tab1').value;
// here is your old submit_form() function. passedValue contains
// your selected $row['name']
}
#Jhilke Dai, First of all your php code is little buggy, '=' sign must be in html not in php the correct code is
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1) { ?>
<option value="<? echo $row['name'] ?>" name="option1"><? echo $row['name'] ?></option>
<?php } ?>
</select>
<input type="file" name="file"> <input type="button" name="button" onclick="submit_form(true,'')">
You can use generic functions or even jQuery itenerations, to fetch form values
See the similar question answer : Get selected value/text from Select on change
function getDomValueByID( id ) {
return document.getElementById(id).value;
}
function submit_form( a, b ) {
var formValue = getDomValueByID( 'tab1' );
//OR
var jQueryFormValue = jQuery( "#tab1" ).val();
//Do what u want here.
}
In fact several consider it a very bad idea to pass the option data over via javaScript, if its already generated on page for the following reasons
Duplicate data, wasted bandwith.
Less portable code, non-OOP.
Harder to maintain, changes in your php code, requires changes in your javaScript code.
Also if you are really interested (this practice is sometimes frowned on). You can use the following as PHP code somewhere in the header. To pass PHP variables to JavaScript. However there are lots of better ways to do this, from JSONS to XML.
<?php optList = ['one', 'two', 'three']; ?>
<script type="text/javascript">
//Window represents the global variable space, and doing this is really bad practice as listed above.
window.optionList = [ <?php echo( implode(' , ', optList) );?> ];
</script>

header('Location: ) in php switch to execute url with onclick function

To put it simply I have this variable which carries a hyperlink:
$test3 = 'Move to Quotes';
and what I need is to execute this variable inside a switch case like below:
switch ($_POST['dropdown']) {
case "Select Folder":
echo "Please select";
break;
case "One":
exec($test3); <-- //here i want to run (if this is not execute, my misunderstanding) the link.
break;
case "Two":
header('Location: http://www.facebook.com/'); <-- //this is just a test
break;
default:
echo "<br></br>";
echo "Move multiple files:";
echo "<br></br>";
}
?>
<form method="post" name="theform" action="">
<select name="dropdown">
<option value="Move to Folder">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<input type="submit" value="Move"/>
</form>
I'd like know how to execute the ahref link without the user clicking it, but simply set this link as a case and when the user submits the form, the selected case actions the hyperlink.
Any help appreciated.
MORE DETAIL
I understand that javascript and php are both seperate languages and that a better option would be to use Ajax, but my understanding of Ajax is limited.
To explain it better, this is what's going on in its entirety:
1) I have a mailbox with a selection of messages.
2) You are able to check these messages and then click a link "Trash Selected" which deletes the selected messages. This the link:
Trash Selected
The javascript function actions the php function in $muldel for all selected messages and updates the database.
This is the javascript function in question:
function inboxDelete(url) {
document.messages.action = url;
document.messages.submit();
}
archiveMove() is exactly the same, just duplicated temporarily to make things clear.
3) I have now re-used the ahref code to do the same procedure, but this time, for moving the selected messages into folders.
4) These folders can be selected from a drop down box - this is where the form comes in.
5) So although I can get it to work by adding a link like such:
$test3 = 'Move to Quotes';
echo $test3;
6) I now need this to work the same way but the link being changed, depending on which folder is selected.
That's the full extent to my problem, I hope this is more clear.
I am aware you can send variables into javscript using GET or POST and then carry out the function entirely through javascript. I have tried something like below, but to no avail:
<form method=post name="myform" action="<?php echo $PHP_SELF;?>">
<input type="hidden" name="formVar" value="">
<input type="text" value="Enter Text Here" name="myText">
<input type="text" value="Enter Text Here" name="myText2">
<input type="submit" value="Send form!" onClick="readmove()">
</form>
<?php
// Retrieve the hidden form variable (using PHP).
$myvar = $_POST['formVar'];
if ($myvar == "$mulmov"){
echo $mulmov;
}
?>
<script language="JavaScript">
<!--
function setText(){
document.myform.myText.value = document.myform.myText.value.toUpperCase();
}
function readmove(){
document.myform.myText.value = "<?php echo $myvar; ?>" ;
readmove2();
}
function readmove2(){
if (document.myform.myText.value == "$mulmov"){
document.myform.myText2.value = "<?php echo $mulmov; ?>" ;
<?php exec ('archiveMove(\''.$mulmov.'\'); return false;'); ?>
} else if (document.myform.myText.value == "$mulmov2"){
document.myform.myText2.value = "<?php echo $mulmov2; ?>" ;
}
}
</script>
First of all, you can't execute JavaScript from within PHP like this. At this point, the control has already moved to the server and JavaScript is run on the client-side.
Second of all Im assuming you dont want to just follow the link, you want to run the link's onClick event, since the href is just a hashtag. So you are trying to run a JavaScript function with PHP. You cant call a function in one language from a function in another language.
Its hard to tell what exactly you are trying to do, but if you want to run a function when a user selects a certain dropdown, write a php function that does what archiveMove() does. If you want this to happen without a page refresh, you can stop the submit process and call your archiveMove() function with javaScript and Ajax.
If elaborate on what exactly you are trying to do, maybe we can help more.
Ok, so the only difference between your working code and the not working code is that you want to dictate the submitted URL based on what is selected in the dropdown?
So you can use JavaScript to set the form action when the dropdown is selected.
BUT, It might be a better idea to submit the form with the same action everytime, and then use PHP to decide what to do. It seems like this is where you were headed initially. Just get the folder id in the switch statement and call a function to make your edits:
The PHP can be similar to the way you had it:
switch ($_POST['dropdown']) {
case "Two":
// set folder id
$folder_id = 2;
break;
}
moveMessages($_POST['Messages'], $folder_id);
function that moves the messages where they need to go.
function moveMessages($messages, $folder_id){
// depending on your form setup
foreach($data as $id => $value ){
if($value){
// code to move to folder
}
}
return true;
}
If there are other factors involved, let me know.
You can write JavaScript code that request a url using window.location.href in click hadler.
window.location.href="http://example.com";
Ok this was my solution but thank you also for your solution Jeff Ryan, this worked also.
<script language="javascript">
function buttons(str)
{
document.getElementById("txtHint").innerHTML = str;
if (document.f1.users.options[1].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
else if (document.f1.users.options[2].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov2; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
}
function submit_mes(str)
{
document.messages.submit();
}
</script>
<form name="f1">
<select name="users" onChange="buttons(this.value)">
<option value="">Select a folder:</option>
<option value="Quotes">Quotes</option>
<option value="Projects">Projects</option>
<input type="button" value="Move" onClick="submit_mes(this.value)">
</select>
</form>
<div id="txtHint"><b>Folder will be listed here.</b></div>

How to run a PHP function from an HTML form?

I'm absolute beginner in web technologies. I know that my question is very simple, but I don't know how to do it.
For example I have a function:
function addNumbers($firstNumber, $secondNumber)
{
echo $firstNumber + $secondNumber;
}
And I have a form:
<form action="" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<p><input type="submit"/></p>
How can I input variables on my text fields and call my function by button pressing with arguments that I've wrote into text fields?
For example I write 5 - first textfield, 10 - second textfield, then I click button and I get the result 15 on the same page.
EDITED
I've tried to do it so:
$num1 = $POST['number1'];
$num2 = $POST['number2'];
addNumbers($num1, $num2);
But it doesn't work, the answer is 0 always.
The "function" you have is server-side. Server-side code runs before and only before data is returned to your browser (typically, displayed as a page, but also could be an ajax request).
The form you have is client-side. This form is rendered by your browser and is not "connected" to your server, but can submit data to the server for processing.
Therefore, to run the function, the following flow has to happen:
Server outputs the page with the form. No server-side processing needs to happen.
Browser loads that page and displays the form.
User types data into the form.
User presses submit button, an HTTP request is made to your server with the data.
The page handling the request (could be the same as the first request) takes the data from the request, runs your function, and outputs the result into an HTML page.
Here is a sample PHP script which does all of this:
<?php
function addNumbers($firstNumber, $secondNumber) {
return $firstNumber + $secondNumber;
}
if (isset($_POST['number1']) && isset($_POST['number2'])) {
$result = addNumbers(intval($_POST['number1']), intval($_POST['number2']));
}
?>
<html>
<body>
<?php if (isset($result)) { ?>
<h1> Result: <?php echo $result ?></h1>
<?php } ?>
<form action="" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<p><input type="submit"/></p>
</body>
</html>
Please note:
Even though this "page" contains both PHP and HTML code, your browser never knows what the PHP code was. All it sees is the HTML output that resulted. Everything inside <?php ... ?> is executed by the server (and in this case, echo creates the only output from this execution), while everything outside the PHP tags — specifically, the HTML code — is output to the HTTP Response directly.
You'll notice that the <h1>Result:... HTML code is inside a PHP if statement. This means that this line will not be output on the first pass, because there is no $result.
Because the form action has no value, the form submits to the same page (URL) that the browser is already on.
Try This.
<?php
function addNumbers($firstNumber, $secondNumber)
{
if (isset($_POST['number1']) && isset($_POST['number2']))
{
$firstNumber = $_POST['number1'];
$secondNumber = $_POST['number2'];
$result = $firstNumber + $secondNumber;
echo $result;
}
}
?>
<form action="urphpfilename.php" method="post">
<p>1-st number: <input type="text" name="number1" /></p>
<p>2-nd number: <input type="text" name="number2" /></p>
<?php addNumbers($firstNumber, $secondNumber);?>
<p><?php echo $result; ?></p>
<p><input type="submit"/></p>
You need to gather the values from the $_POST variable and pass them into the function.
if ($_POST) {
$number_1 = (int) $_POST['number1'];
$number_2 = (int) $_POST['number2'];
echo addNumbers($number_1, $number_2);
}
Be advised, however, that you shouldn't trust user input and thus need to validate and sanitize your input.
The variables will be in the $_POST variable.
To parse it to the function you need to do this:
addNumbers($_POST['number1'],$_POST['number2']);
Be sure you check the input, users can add whatever they want in it. For example use is_numeric() function
$number1 = is_numeric($_POST['number1']) ? $_POST['number1'] : 0;
Also, don't echo inside a function, better return it:
function addNumbers($firstNumber, $secondNumber)
{
return $firstNumber + $secondNumber;
}
// check if $_POST is set
if (isset($_POST['number1']) && isset($_POST['number2']))
{
$number1 = is_numeric($_POST['number1']) ? $_POST['number1'] : 0;
$number2 = is_numeric($_POST['number2']) ? $_POST['number2'] : 0;
echo addNumbers($_POST['number1'],$_POST['number2']);
}
You are missing the underscores in
$_POST['number1']
That's all.
maybe it's a little late
but could you set a parameter in the url of the php file to post example:
In the html :
...
<form action="Controllers/set_data.php?post=login" method="post" >
...
In the php :
...
$post_select = $_GET['post'];
switch ($post_select) {
case 'setup':
set_data_setup();
break;
...
You can always use this trick. But keep in mind that if the referrer is hidden it doesn't work.
header("Location: " . $_SERVER["HTTP_REFERER"]);
Just add to your PHP page at the point where there is no more code to be executed, but is still executed.

Surely a foolish error, but I can't see it

I have a form (greatly simplified):
<form action='http://example.com/' method='post' name='event_form'>
<input type='text' name='foo' value='3'/>
<input type='submit' name='event_submit' value='Edit'/>
</form>
And I have a class "EventForm" to process the form. The main method, process() looks like this:
public function process($submitname=false){
$success=false;
if ($submitname && isset($_POST[$submitname])){ //PROBLEM: isset($_POST[$submitname] is always FALSE for some reason
if($success=$this->ruler->validate()){//check that dependancies are honoured and data types are correct
if($success=$this->map_fields()){//divide input data into Event, Schedule_Element and Temporal_Expression(s)
$success=$this->eventholder->save();
}
}
} else {//get the record from the db based on event_id or schedule_element_id
foreach($this->gets as $var){//list of acceptable $_GET keys
if(isset($_GET[$var])){
if($success= $this->__set($var,$_GET[$var])) break;
}
}
}
$this->action=(empty($this->eventholder->event_id))? ADD : EDIT;
return $success;
}
When the form is submitted, this happens: $form->process('event_submit'); For some reason though, isset($_POST['event_submit']) always evaluates to FALSE. Can anyone see why?
ETA: after working through the suggestions, it appears that JQuery.validate() is having an unexpected effect on the form submission. All the fields are submitted except the submit button. This appears to be the fault of this JQuery:
$("form[name='event_form']").validate({
submitHandler: function(form) {
form.submit();
}
}};
Any thoughts on how to make sure the submit button value gets sent?
Change your JQuery to this:
$("form[name='event_form']").validate({
submitHandler: function(form) {
$("form[name='event_form'] input[name='event_submit']").click()
}
}};
do a print_r on the $_POST array and see whats being submitted - it should output the whole array e.g.
print_r($_POST);
I broke your code out into a even simpler PHP file:
<?php
function process($submitname=false){
echo 'erg<br>';
$success=false;
if ($submitname && isset($_POST[$submitname])){ //PROBLEM: isset($_POST[$submitname] is always FALSE for some reason
echo 'bwah';
}
}
process("event_submit");
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="event_form">
<input type="text" name="foo"/>
<input type="submit" name="event_submit" value="Edit"/>
</form>
"erg" and "bwah" displayed as expected. Make sure that your class is being instantiated properly, that you're actually passing "event_submit" to it, and that some other piece of code isn't wiping out $_POST before you get a chance to read it.

Categories