How to send both php and javascript variables as input field value? - javascript

I am sending multiple values from the input field with the same name.
It works fine when I just send the custom1 and var 2 but I want to add a javascript variable var3 as well but assigning the value by using document.getElemendById overwrites the input field completely and custom1 and var2 are lost. So how to add a javascript variable var3 at the end so it gets printed under the array index $pieces[2]; in the v.php file.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php $var2 = "custom2" ?>
<form action="v.php" method="POST" >
<input id="jsvar" type="text" name="custom" value="custom1,<?php echo $var2; ?>">
<input type="submit" name="" value="send">
</form>
<script type="text/javascript">
var var3 = "custom3";
document.getElementById("jsvar").value = var3;
</script>
</body>
</html>
v.php
<?php
$custom = $_POST['custom'];
$pattern = ",";
$pieces = explode($pattern,$custom, 3);
print_r($pieces);
$custom1 = $pieces[0];
$custom2 = $pieces[1];
echo '<br>';
echo $custom1.'<br>';
echo $custom2.'<br>';
echo $pieces[2];
?>

You could append the data rather than replace it with the new data.
var var3 = "custom3";
document.getElementById("jsvar").value += ","+var3;

Try this below . It's working fine. Review below screen Link
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php $var2 = "custom2" ?>
<form action="v.php" method="POST" >
<input id="jsvar" type="text" name="custom" value="custom1,<?php echo $var2; ?>">
<input type="submit" name="" value="send">
</form>
<script type="text/javascript">
var pre_value=document.getElementById("jsvar").value;
var var3 = "custom3";
var new_value = pre_value +','+var3;
document.getElementById("jsvar").value = new_value;
</script>
</body>
</html>

Related

Embedded JavaScript in PHP can not manipulate DOM in HTML

I have a PHP to verify the HTML form (post method). If the value doesn't match, the error message should be added at the HTML page. I test the embedded JS script in console, it works. But it doesn't work in PHP. How can I fix it? Thank you
Here is my code
<!DOCTYPE html>
<body>
<form action="http://localhost/submitTest.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<div id="submitField">
<input type="submit">
</div>
</form>
</body>
</html>
<?php
if ($_GET["name"] == 1 && $_GET["email"] == 2) {
header('Location: http://localhost/table.html');
} else {
$url = 'http://localhost/submitTest.html';
echo "<meta http-equiv='Refresh' content='0;URL=$url'>";
echo "
<script>
var messageP = document.createElement('span');
messageP.style.color = 'red';
var parent = document.getElementById('submitField');
parent.appendChild(messageP);
messageP.innerHTML = 'not match';
</script>";
}
?>
I want to do something like thiserror message

How to pass PHP variable value to html input box from external PHP file?

HTML FILE
<body>
<input type="text" id="name" class="form-control" name="name">
<label for="name">name</label>
<script type="text/javascript" src="PHPfile.php"></script>
</body>
Separate PHP FILE
I have done MySQL query, and I have query value in $row['name'].
How can I put this value in the HTML input box?
<?PHP
**some code here**
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo "<script>
var name = <?php echo $row['name'] ?>;
document.getElementById(name).value='name';
window.location.href='htmlpage.html';
</script>";
?>
I tried this but this didn't work. I got the following error
Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in...
I have tried to provide custom variable to var name and then document.getElementByID line. Still, it doesn't work.
Any Solution?
This should work.
<?php
/**some code here**/
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo '<script>
document.getElementById("name").value = "' . $row['name'] . '";
</script>';
?>
or same thing if more complex HTML/script needed:
<?php
/**some code here**/
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
?>
<script>
document.getElementById("name").value = "<?=$row['name'];?>";
</script>
<?php
/* more php code */
?>
If you still get the same error message, than the problem is somewhere else.
To echo a variable in a string ( in php ) we can use concatenation " . " $var['code'] ". " or template string { $var["code"] }
PHPfile.php
<?php
$row = ["name" => "something"];
echo "
let input = document.getElementById('name');
input.value = '{$row['name']}';
setTimeout(()=>{
window.location.href='htmlpage.html';
} ,2000)
"
?>
For echoing variables in string use {$var} instead of simple concatenation
Extended answer
index.php
<?php
// all querys here ... getting results from db
// assuming result
$row = [
"username" => "xxxxxxxxx",
"email" => "xxxxx#example.com"
];
$name = $row['username'];
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width , initial-scale=1.0">
<title>Damn Forms ! </title>
</head>
<body>
<form action="file.php" method="post" accept-charset="utf-8">
<label for="name">Name <span class="red">*</span></label>
<input type="text" id="name" class="form-control" name="name" placeholder="Enter your full name " value="<?= $name ?>">
<!-- sending values to another php file -->
<button type="submit">Submit</button>
</form>
</body>
</html>
file.php
<?php
if($_SERVER["REQUEST_METHOD"] === "POST"){
$name = $_POST['name'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width">
<title>Input Form </title>
</head>
<body>
<input type="text" name="name" id="" value="<?= $name ?>" />
</body>
</html>
I see 2 answers already, but my way of doing it would be....
HTML
<body>
<input type="text" id="name" class="form-control" name="name">
<label for="name">name</label>
<div id="externalPHP"></div>
<script type="text/javascript">
document.getElementById("externalPHP").innerHTML='<object type="type/php" data="PHPfile.php" ></object>';//javascript
$('#externalPHP').load('PHPfile.php');//jQuery
</script>
</body>
The php file
<?PHP
**some code here**
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo '<script>document.getElementById("name").value='."$row['name']".';</script>';
?>

Changing site title server-side

How can I change a web page title for everyone on that site and not to be changed with refreshing, using javascript or PHP?
I've tried HTML DOM title but it gets back to its first title after refreshing.
I've tried giving variable in PHP and changing it by after a button pressed but the title didn't change!
These were my codes:
<?php
$title = "Chat";
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<div id="chat_messages"></div>
<form enctype="multipart/form-data" method="post">
<input onClick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
<?php
if(isset($_POST['send'])){
$title = "new message";
}
?>
</body>
</html>
Any idea what should I do?
Glad to help.
Of course the title won't change, because php reads your code from 1st line to the end, and you have already added $title = "Chat";
what to do is to change the code like this:
<?php
if(isset($_POST['send'])) $title = "new message";
else $title = "Chat";
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<div id="chat_messages"></div>
<form enctype="multipart/form-data" method="post">
<input onClick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
</body>
</html>
This will change the title.
Also, if you want to change the title without refreshing the page, you need JS.
Just use
document.title = '***'; //use your title to replace "***"!
Have a good day~
There are some mistakes in your code like you have used onClick instead you should use onclick
you have not putted a semicolon ; while you are typing
You have not assigned action to your form
Action will be echo htmlspecialchars($_SERVER['PHP_SELF'])
And we will use if else
This will work
<?php
if (isset($_POST['send'])) {
$title = "new message";
} else {
$title = "Chat";
}
?>
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<div id="chat_messages"></div>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" enctype="multipart/form-data" method="post">
<input onclick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
</body>
</html>
I hope this will Help you

Values to PHP function parameters from Button click Javascript function

Friends,
I'm a newbie to PHP.
I've had a problem to deal with that I couldn't understand, so I posted it in this thread.
I've dynamically created 2 textboxes and a button.
Question ID text field
Question text field
Change Button
for the change button I need to write a 'onclick' javascript to pass Question ID
and Question value to a PHP function (set_id) written inside the Same file. In fact that’s why i
Called Form action $_SERVER[“PHP_SELF”].
Here’s my code.
<html>
<head>
<script>
function getvalue(value)
{
var qid_value = 'qid_'+value.substring(4);
alert('QID = '+ document.getElementById(qid_value).value + ' QUESTION = ' + document.getElementById(value.substring(4)).value);
/*
I created this javascript alert to test the id s of textboxes and their values
*/
}
</script>
</head>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<!-- These fields are dynamically created -->
<input type="text" id="'.$var_id.'" name="'.$var_id.'" value="'.$row['qid'].'" readonly size="2 px"/>
<input type="text" id="'.$var_question.'" name="'.$var_question.'" value="'.$row['question'].'" style="size:auto"/>
<input type="button" id="'.$var_question.'" name="'.$var_question.'" value="Change" onclick="getvalue(this.name)"/>
<!-- These fields are dynamically created -->
</form>
</body>
</html>
<?php
$msg= "";
function display($qid,$question)
{
require('uni_db_conn.php'); // this is my db connection
$qid = $_POST[$qid];
$question= $_POST[$question];
$query = "UPDATE question SET question='.$question.' WHERE qid='.$qid.'";
$result = mysql_query($query);
if(!$result)
{
$msg= 'Cant Insert Values to the Table !'.mysql_error();
}
else
{
$msg = 'Successfully Added to the Table !';
}
echo '<label>'.$msg.'</label>';
}
function set_id($qid,$question)
{
if(isset($_POST[$question]))
{
display($qid,$question);
}
}
?>
Thank You ! Sorry If there was any mistake.
Try this code
<?php
if(isset($_POST['submit'])){
$QID = $_POST["qid"];
$QUE = $_POST["question"];
echo $QID;
echo $QUE;
}
?>
<html>
<head>
<script language="javascript">
function getvalue()
{
var valid= true;
var id = document.getElementById("ID").value;
var ques = document.getElementById("ques").value;
return valid;
}
</script>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onSubmit=" return getvalue()" >
<input type="text" id="ID" name="qid"/>
<input type="text" id="ques" name="question"/>
<input type="submit" name="submit" value="Change"/>
</form>
</body>
</html>

Submission of form does not work in jQuery

Problem:
Trying to automatically generate a form and submit it without user interference.
Complete code:
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
$(document).ready(function()
{
var url = 'test.php';
var form = $('
<form action="' + url + '" method="post">' +
'<input type="text" name="Datafile" value="' + <?php echo "upload/".$_SESSION['txtfile'].""; ?> + '">' +
'<input type="text" name="Perspective" value="' + <?php echo implode(" ", $_SESSION['dimensions']); ?> + '">' +
'<input type="hidden" name="form_submitted" value="true">' +
'</form>
');
$('body').append(form);
$(form).submit();
});
</script>
</head>
<body>
</body>
</html>
It gives me first an error when looking at the source code that implode() parameters are wrong.
Desired solution:
The form should submit itself once it has been loaded.
Anyone who can spot what's wrong or why the form does not submit itself?
Since you are using jquery why aren't you just sending the data via post?
$.post( "test.php", { name: "<?php echo "upload/".$_SESSION['txtfile']; ?>" ,
Perspective: "<?php echo implode(" ", $_SESSION['dimensions']); ?>",
form_submitted : "true"} );
Can you try this,
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function AutoSubmit(){
document.my_form.submit();
}
</script>
</head>
<body onLoad="AutoSubmit();">
<form action="test.php" name="my_form" id="my_form" method="post">
<input type="hidden" name="Datafile" value="<?php echo "upload/".$_SESSION['txtfile']; ?>">
<input type="hidden" name="Perspective" value="<?php echo implode(" ", $_SESSION['dimensions']); ?>">
<input type="hidden" name="form_submitted" value="true">
</form>
</body>
</html>
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
$(document).ready(function()
{
var url = 'test.php';
var form =
"<form action="+url+" method=\"post\"><input type=\"text\" name=\"Datafile\" value=\"<?php echo \"upload/\".$_SESSION[\'txtfile\'].\"; ?> \"><input type=\"text\" name=\"Perspective\" value=\" <?php echo implode(\" \", $_SESSION[\'dimensions\']); ?>\"><input type=\"hidden\" name=\"form_submitted\" value=\"true\"></form>";
$('body').append(form);
$(form).submit();
});
</script>
</head>
<body>
</body>
</html>
You forgot to load jQuery in document:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>

Categories