I have a PHP snippet which generates the required output in a variable $ans1. What I want to do is print this variable $ans1 in a <textarea>. I tried to write the following code but it generates the output as usual and not in the textbox. The following is my PHP code:
while($row = mysqli_fetch_array($result)) {
if($submit3 == "Positive") {
$ans1 = $row['reply_yes'];
echo $ans1;
} else if($submit3 == "Negative") {
$ans1 = $row['reply_no'];
echo $ans1;
}
echo "<br/>";
break;
}
And following is my HTML code:
<form method="post" action="fetch_page.php">
<input type="submit" name="submit1" value="Positive" onclick="enter()"/>
<input type="submit" name="submit2" value="Negative" onclick="enter()"/>
<textarea name="txt1" cols="66" rows="10" id="txt1"> </textarea>
<script>
function enter()
{
document.getElementById('txt1').value= <?php echo htmlspecialchars($ans1);?>;
}
</script>
</form>
Please tell me where am I going wrong.
Adding quotes like this isnt working either
document.getElementById('txt1').value= "<?php echo htmlspecialchars($ans1);?>";
As you can see in the following image, the answer(the not bold part) should get printed in the textbox also according to my html code
You can add the text you want to be displayed in the textarea between the <textarea> tag.
<textarea name="txt1" cols="66" rows="10" id="txt1">
<?php echo $ans1; ?>
</textarea>
If the text still doesn't appear or you get an error then make sure you access variables from the global scope. Like below.
<textarea name="txt1" cols="66" rows="10" id="txt1">
<?php echo $GLOBALS['ans1']; ?>
</textarea>
You need to add quotes around the echoed value:
document.getElementById('txt1').value = "<?php echo htmlspecialchars($ans1);?>";
And your script should be situated in <head>
Edit
What about using this:
document.getElementById('txt1').value = "<?php Print($ans1); ?>";
You didn't surround the php with quotes. The following works:
<form method="post" action="fetch_page.php">
<input type="submit" name="submit1" value="Positive" onclick="enter()"/>
<input type="submit" name="submit2" value="Negative" onclick="enter()"/>
<textarea name="txt1" cols="66" rows="10" id="txt1"> </textarea>
<script>
function enter()
{
document.getElementById('txt1').value = "<?php echo htmlspecialchars($ans1); ?>";
}
</script>
</form>
Your question is not a PHP problem. You can't see any output from the function because your script is halted upon submission! So change the submit buttons to type="button" and add a ID, then use the script below. Using jQuery (to minimize t he code you need to write) and use a timeout to actually have time for the function be able to display the results.
$(".button").click(function() {
var buttonName = $(this).attr('name'),
elm = $(this);
$('#txt1').val( buttonName + ' was clicked.' ); // Add response
setTimeout(function(){
elm.get(0).form.submit(); // Submit form
}, 5000); // After 5 seconds
});
JSFIDDLE
Related
I have a code which its simplified version could look like this :
file1.php
$array = array();
$array = new randomObject(1);
$array = new randomObject(2);
require('file2.php');
file2.php
<form method="post" action="?">
<?php
foreach ($array as $a) {
<p><?php echo $a->getAValue();
<textarea rows="5" cols="70" name="textbox[]">
</textarea>
</p>
<?php } ?>
<input id="isTrue"> //true or false
<input type="submit" >
</form>
The user is supposed to write answers in the textarea and click on submit then his answers are compared to the randomObject values. Then it shows if it's true or false next to each textarea
You are looking for something that the fron-tend will handle for you and an AJAX call is exactly what you need.
First of all, name your form
<form id="myForm" method="post" action="?">
<?php
foreach ($array as $a) {
<p><?php echo $a->getAValue();
<textarea rows="5" cols="70" name="textbox[]">
</textarea>
</p>
<?php } ?>
<input id="isTrue"> //true or false
<input id="submitButton" type="submit" >
</form>
Now you have proper id's both on the submit button and on the form itself.
<script>
let submitB = document.querySelector("#submitButton");
submit.addEventListener("click", function(e) {
e.preventDefault();
});
</script>
From now on you just have to write a proper ajax call to the url you wanted to access and you will be set to go.
If you need help with that let me know and I will throw something your way.
I am guessing you want to retain the values entered by the user, since they go away if you submit the form. (Page reloads)
This can be done by altering the input fields. If a value was submited pass that value to each corresponding input field.
Something like that:
<textarea rows="5" cols="70" name="textbox[]" <?php if(isset(value[SOMETHING])){?> value="<?php echo value[SOMETHING]; ?>" <?php } ?> >
This is just an example of how it would work. Make sure you adapt it to your code!
I have a form which contains one text field. Now, I'm trying to echo out the contents of that input after the form was submitted. Here's my code for the same:
<script>
function postResultss()
{
document.write("<?php echo ($_POST['tweet1']); ?>");
}
</script>
<form method = "POST">
<input type = "text" name = "tweet1">
<br>
<input type = "submit" onclick = "postResultss()" />
</form>
The above code is inside a PHP file. However, nothing gets echoed out on submitting the form. The function does get called as expected, because I have tried echoing custom messages while debugging. However, nothing gets echoed out when I try to echo the value of $_POST['tweet1'], where tweet1 is the name of the input text field whose contents I'm trying to display.
What seems to be wrong here?
You do a submit and onclick. That goes wrong. Further, don't do a document.write!
Do this as better alternative (no php in js):
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') // check if post
echo htmlentities($_POST['tweet1']);
?>
<form method="post">
<input type="text" name="tweet1">
<br>
<input type="submit" value="Tweet!">
</form>
Rather than use javascript to write the content which, in your example wouldn't work, use php to generate the response for the user to see
<form method = "POST">
<input type = "text" name = "tweet1">
<br>
<input type = "submit" value='Submit' />
<div id='msgs'>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['tweet1'] ) ){
echo $_POST['tweet1'];
}
?>
</div>
</form>
The problem is that the javascript function is called before the form submits (so before php can print out the echo), and since the page updates the document.write is being overwritten from the new request.
Why dont you try something like this?
<form method = "POST">
<?php echo ($_POST['tweet1']); ?>
<input type = "text" name = "tweet1">
<br>
<input type = "submit"/>
</form>
or:
<script>
var text = "<?php echo ($_POST['tweet1']); ?>";
if(text != ""){
alert(text);
}
</script>
<form method = "POST">
<input type = "text" name = "tweet1">
<br>
<input type = "submit"/>
</form>
Hi i am trying to save value and alert them using ajax which i am insert using php in my sql table but my alert is not working
Here is my code
demo.php
<html>
<head>
<script>
function my(){
var name = document.getElementById("name").value;
var last_name = document.getElementById("last_name").value;
document.getElementsById('div1').style.backgroundColor = green;
var dataString = 'name='+name+'&last_name='+last_name;
$.ajax({
type:'POST',
data:dataString,
url:'demo.php',
success:function(data) {
alert(data);
}
});
} </script>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" onclick="my();" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
echo $name;
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
}?>
demo.html
<html>
<head>
</head>
<body>
<div id="div2" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
here i want when i submit form them div color should change which is in demo.html
where i am wrong in this code
and how can i achieve my goal
Any help will be appreciated
changes you need to make:
add jquery as a dependency as you are using $.ajax utility function which is provided by Jquery.
As you are using Jquery, you could use its selectors for getting values of elements and binding functions to dom elements. I have commented it in the source code.
You are using a form with a submit button and executing the ajax call on click of it. But you need to prevent the page from submitting the form by preventing the default behavior of the submit button. Refer event.preventDefault();
Move the php ajax response part to the top and call exit() once your response is complete. Else your ajax response will include the whole page html source also.
.
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
//Call exit as your ajax response ends here. You dont need the html source along with it.
exit();
}
?>
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
<!-- include jquery dependeny before your js code block -->
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$("#update").on("click",function(event) {
//Prevent Default submit button behavour. Prevent the form from submission.
event.preventDefault();
// using Jquery selectors for better readability of code.
var name = $("#name").val();
var last_name = $("#last_name").val();
$("#last_name").css("background-color","green");
$.ajax({
type:'POST',
data:{name:name,last_name:last_name,Update:true},
url:'demo.php',
success:function(data) {
alert(data);
}
});
});
</script>
</body>
</html>
You send two parameters in "dataString" variable, and then in php check undefined variable "Update"
So, just replace string
if (isset($_POST['Update'])) {
to
if (isset($_POST['name']) && isset($_POST['name'])) {
And add this line to tag
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
I am trying to place the PHP variable $e into HTML textbox id="textid" upon a button onclick. I have played around with various syntax, but I cannot seem to get it to work. What am I doing wrong?
<script type="text/javascript">
function ElementContent(id,content)
{
document.getElementById(id).value = content;
}
</script>
<input type="text" name="" value ="" id="textid" ;"/>
<?php
$e = "test";
echo '<button value="" class="button" onclick="ElementContent(\'textid\',\'$e\')" />';
?>
echo '<button value="" class="button" onclick="ElementContent(\'textid\',\''.$e.'\')" />Button Name</button>';
You have to concat the string, as php doesn't automatically recognise dollars+some name as a variable in single quote strings.
PHP variables will only be interpreted in strings constructed with double-quotes ("). Update your code as follows:
<button value="" class="button" onclick="ElementContent('textid', '<?php echo $e ?>')" />
As you can see, there's no need to output the whole button markup in PHP. Thus, your final code should be:
<script type="text/javascript">
function ElementContent(id,content) { document.getElementById(id).value = content; }
</script>
<input type="text" name="" value ="" id="textid" />
<?php $e = "test"; ?>
<button value="" class="button" onclick="ElementContent('textid', '<?php echo $e ?>')">Button</button>
I also took the time to fix a few issues with your markup, too.
I'm sure this has been asked befor but I can't seem to find it in a search
I have multiple forms on a page generated by php all with onCick event
The problem is it only picks up the first event after that any other clicks produce same result from first click
Here is javascript
function CompareScores(form)
{
var scoreA = document.getElementById("score_A").value;
var scoreB = document.getElementById("score_B").value;
if(scoreA > scoreB){
alert('Score A is Larger ' + scoreA)
}else{
alert('Score B is Larger ' + scoreB)
}
}
And the php generating forms
<?php
while($i<=$numPrelimTeams) {
if($i!=$e) {
?>
<form action="processScores.php" method="post"><p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_A" name="score_A" size="1"></u></p>
<input type="hidden" name="team_A" value="<?php echo $prelimTeam[$i]; ?>">
<input type="hidden" name="game" value="<?php echo $game_num; ?>">
<p class="right">Game # <?php echo $game_num; ?> ) <input type="button" value="Enter Scores" onClick="CompareScores(this.form)"></p>
<?php
}else{
?>
<p><u><?php echo $prelimTeam[$i]; ?> --> SCORE : <input type="text" class="small" id="score_B" name="score_B" size="1"></u></p>
<input type="hidden" name="team_B" value="<?php echo $prelimTeam[$i]; ?>">
</form><br><br><br>
<?php
$game_num++;
$e=$e+2;
}
$i++;
}
?>
Without knowing the inputs or seeing the result, it's hard to tell for sure, but it looks like you might be generating multiple instances of this form on the same page, giving you multiple page elements named "score_A" and "score_B". document.getElementById will then become a bit ambiguous.
Since you're already sending the form object, use that instead:
var scoreA = form.score_A.value;
...
There is essentially a single problem with your code. You have multiple instances of the same ID.
To fix it, try something like this.
<input type="text" class="small score_A" name="score_A" size="1" />
Similarly
<input type="text" class="small score_B" name="score_B" size="1" />
Now, you can write a querySelector in your JS
function CompareScores(form) {
var a = form.querySelector('.score_A').value;
var b = form.querySelector('.score_B').value;
//do something
}