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>
Related
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>';
?>
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>
When I try to enter
<script type="text/javascript" >
alert("hello");
</script>
in the comment box on my PHP page I do not get an alert box. I see the script in my text file, not on the webpage. For some reason the <script> isn't executing. I have active scripting and javascript enabled on all my browsers.
My PHP code:
<?php //CFPcomments.php
include_once 'CFPheader.php';
if (isset($_POST['content']))
{
$fp = fopen('comments.txt', 'a');
fwrite($fp, $_POST['content'] . "<br />");
fclose($fp);
}
echo nl2br(file_get_contents('comments.txt'));
echo <<<_END
<h3>Post comment</h3>
<form action='CFPcomments.php' method='post'>
<textarea name='content' rows ='3' cols='100'></textarea>
<br/>
<input type='submit' value='Post' />
</form>
_END;
?>
Strange. I got it to work, not sure why.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
alert("hello");
</script>
</head>
<body>
</body>
</html>
When I type this in it seems to work
Anyone have any idea why???? Very confused.
your nl2br() is most likely translating
<script type="text/javascript" >
alert("hello");
</script>
to
<script type="text/javascript" ><br/>
alert("hello");<br/>
</script><br/>
and breaking the JavaScript code.
I assigned a variable to the content, then displayed the variable in the PHP code. Now it works.
<?php //CFPcomments.php
include_once 'CFPheader.php';
setcookie("username", $GLOBALS['user'], time()+3600);
setcookie("password", $GLOBALS['pass'], time()+3600);
if (isset($_POST['content']))
{
$fp = fopen('comments.txt', 'a');
fwrite($fp, $_POST['content'] . "<br />");
fclose($fp);
}
$comment = file_get_contents('comments.txt');
echo <<<_END
<h3>Post comment</h3>
'$comment'
<form action='CFPcomments.php' method='post'>
<textarea name='content' rows ='3' cols='100'></textarea>
<br/>
<input type='submit' value='Post' />
</form>
_END;
?>
I have a bunch locker numbers in a drop down list (populated from MYSQL/PHP). I want to display the locker's combination and location when you select a locker number from the list in two input fields below on the same page.
I have used jquery to tell me which item in the list is selected dynamically. Then I used the $.ajax() function to send that item to my server.
My problem: Can I use $.ajax() to send my variable to the same page I am on? I have tried this and I get an error. I am not sure how to accomplish this. My knowledge of AJAX is very minimal.
My code is as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Locker Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="form.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function show()
{
$('#addlocker').toggle();
}
function lockerSelected(sel)
{
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(){
alert(selected);
}
});
}
</script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<?php
$url = $_SERVER['REQUEST_URI'];
$studID = substr($url, strpos($url, "=") + 1);
$db_handle = mysql_connect("localhost", "root", "pickles") or die("Error connecting to database: ".mysql_error());
mysql_select_db("lockers",$db_handle) or die(mysql_error());
$result = mysql_query("SELECT * FROM students WHERE studID = $studID");
?>
<div class="container">
<header> <img src="images/headmast.png" alt="Insert Logo Here" width="686" height="180" id="Insert_logo" /> </header>
<div id="data1">
<form id ="studData" name="studData" action="update.php" medthod="post">
<fieldset>
<legend>Student Details</legend>
<?php
while($row = mysql_fetch_array($result))
{
echo '<ol>';
echo '<li>';
echo '<label for=studid>Student ID</label>';
echo '<input id=studid name=studid type=text value='.$row['studID'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>First Name</label>';
echo '<input id=fname name=fname type=text value='.$row['firstName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>Last Name</label>';
echo '<input id=lname name=lname type=text value='.$row['lastName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=email>Email</label>';
echo '<input id=email name=email type=text value='.$row['email'].'>';
echo '</il>';
echo '<li>';
echo '<label for=progam>Program</label>';
echo '<input id=progam name=progam type=text value='.$row['program'].'>';
echo '</il>';
echo '</ol>';
$program = $row['program']; //get name of program
}
?>
<input type="submit" value="Update" class="fButton"/>
</fieldset>
</form>
<form id="locker" name="locker" action="" method="post" >
<fieldset>
<input type="button" onclick="show()" value="Add Locker"/>
<div id="addlocker" style="display:none;">
<!--
query lockers where $program = program parsed in & student id is equal to 0 (this makes it available)
get select list to 10
populate select list --> <br/>
<legend>Lockers Available: </legend>
<select size="10" name="lockerSelect" multiple="yes" style="width:200px;" onChange="lockerSelected(this);">
<?php
$result1=mysql_query("SELECT * FROM lockers WHERE progName = '$program' && studID = 0") or die($result1."<br/><br/>".mysql_error());
while($row1 = mysql_fetch_array($result1))
{
echo '<option value=\"'.$row1['lockerScan'].'">'.$row1['lockerNo'].'</option>';
}
echo '</select>';
echo '<br>';
$lockerNo = $_POST['selected']; \\doesn't work - displays error
echo $lockerNo; \\errors out
?>
</div><!--end of add locker section-->
</fieldset>
</form>
</div><!--end of data1 -->
Search
</div><!-- end of container-->
</body>
</html>
Firstly, you can use :
function show()
{
$('#addlocker').toggle();
}
Then, you should learn more about Ajax and PHP. Your call shoud be :
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: {selected: selected},
success: function(data){
alert(data);
}
});
And in your PHP file :
<?php
$select = $_POST['selected'];
//....
// Do what you have to do then return your result
echo '<div>Send to your page !</div>';
First Arrange your files.
js's is in js folder
php's in php folder
best way is to assaign a seperate php page and then in js use on change event
$(document).on("change", "#selectfieldid", function(){
var selected = $('#selectfieldid').val();
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(data){
$('#addlocker').val(data); //echoed result placed here that has id addlocker
}
});
});
send those to a php page echo the result in that php.
I want to send information of 1 variable with javascript into PHP.
So , i used this code (in index.php) :
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
<script>
$.post('http://localhost/test/index.php', {
name: $('.class').html();
});
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.class').text();
$(this).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
});
});
</script>
<form action="" method="post" id="my_form">
<div class="class" name="name">
this is my div
</div>
<input type="submit" value="submit" name="submit" />
</form>
<?php
if(isset($_POST['name'])){ $name = $_POST['name']; }
echo $name;
But i see this error :
Notice: Undefined variable: name in C:\Program Files\EasyPHP-5.4.0RC4\www\test\index.php on line 22
What can i do ?
$name is not defined. You have the echo outside of the if statement, move it inside the braces.
if(isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
}
Also, you post to submit.php but this code is for index.php... so you need to fix that, too.
also , In using jQuery , you didn't closed the tag :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
close like this and use this code :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.post('http://localhost/test/index.php', {
name: $('.class').html();
});
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.class').text();
$(this).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
});
});
</script>
<form action="submit.php" method="post" id="my_form">
<div class="class" name="name">
this is my div
</div>
<input type="submit" value="submit" name="submit" />
</form>