Submitting with Javascript and getting form data with php - javascript

I have a search bar that uses a javascript function to submit the form when the user hits Enter (which is working) because it doesn't have a submit button, but I need to use php to handle the data in the textbox on post. The form is submitting, but on post it's not able to grab what was in the search textbox.
Here's the code:
<form id="siteWideSearch" name="siteSearch" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<input id="homeSearch" type="text" maxlength="100" onkeypress="startSiteSearch(event);" />
</form>
Javascript:
if (event.keyCode == 13) {
document.getElementById("siteWideSearch").submit();
}
PHP:
if($_SERVER["REQUEST_METHOD"] == "POST") {
echo "<script type=\"text/javascript\">window.alert(\"Post reached. Yay!!\");</script>";
echo "<script type=\"text/javascript\">window.alert(\"Search Criteria: ".trim($_POST['homeSearch'])."\");</script>";
}
I get the popup saying that post was reached, but the second popup just outputs "Search Criteria: " and nothing else.

You're missing the name attribute on your form input. Without it that value is not submitted.
<input id="homeSearch" type="text" maxlength="100" onkeypress="startSiteSearch(event);" />
should be:
<input name="homeSearch" id="homeSearch" type="text" maxlength="100" onkeypress="startSiteSearch(event);" />

Related

Form Always submitting with Javascript Confirm

The form was working for a while but I moved some code around and can't revert (A lesson learned), now the code isn't working like it's supposed to. In a nutshell, User clicks delete button > Delete button sends specific Entry ID to function, Function gets form ID, "Confirms delete", then should send to my delete_entry.php code. Now, form is always submitting even when I hit "NO" and I added an alert to tell me which route it goes.
I've tried commenting out the form, and it still submits, so I don't think it's explicitly tied to the confirm function (Could be crazy though)
if ($entry['SubEntryID'] == "0") { ?>
<div id="post"><!-- This is the main post-->
<div id="main">
<div id="title">
<?php echo $entry['EntryID']; ?>
<?php echo $entry['Title']; ?>
</div><br />
<p><?php echo $entry['Body']; ?></p><br />
<div id="postinfo">
At: <?php echo $entry['CreateDate']; ?><br/>
Posted by - <?php echo $entry['UserName']; ?>
</div>
<!-- Start the form for the delete button -->
<form action="Delete_entry.php" method="post" id="Delete<?php echo $entry['EntryID'];?>">
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<input type="hidden" readonly="true" name="UserID" value="<?php echo $entry['UserID']; ?>" />
<?php if ($userid == 1 || $userid == $entry['UserID']) { ?>
<input onclick="confirmdelete('Delete<?php echo $entry['EntryID'];?>')" type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post"/>
<?php } ?><br />
</form>
</div>
function confirmdelete(eid) {
var retval = confirm("Are you sure you want to delete?" + eid + "?");
if (retval == true) {
alert("You said Yes");
document.getElementById(eid).submit();
}
else
{
alert("You said No");
}
}
I want the delete button to call the function, the function to respond by submitting the form if it's true, and cancelling the form submission if false. The form page should only get called if confirm is true, and then submit()
Firstly the confirmdelete() is not returning any true/false back so there is no code that stops the form from submission. Secondly, a form will submit anyway even if the function returns false because you have 2 submits (the form and the onclick).
Move the function call to onsubmit() of the form. Remove the onclick because the input type image submits the form by default. Here is the code:
Form:
<form action="Delete_entry.php" method="post"
id="Delete<?php echo $entry['EntryID'];?>"
onsubmit="return confirmdelete(<?php echo $entry['EntryID'];?>)">
Then the button (onclick removed):
<input type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post" />
Finally the JavaScript (returns true/false):
function confirmdelete(eid) {
if (confirm("Are you sure you want to delete?" + eid + "?")) {
alert("You said Yes");
return true;
}
else
{
alert("You said No");
return false;
}
}

PHP form handling not working with javascript onclick function

I'm trying to submit a form, but before that, i want a javascript function to take place. Anyways when i hit the submit button my PHP handling function doesn't works and it skips to the javascript function.
How can i execute the PHP function and then the javascript ?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Complete a survey to become part of our team.</title>
<!-- Start of content locker code -->
<script type="text/javascript">var gwloaded = false;</script>
<script src="http://asmlk.com/gwjs.php?aff=38757&prf=23145&sub1=" type="text/javascript"></script>
<script type="text/javascript">if (gwloaded == false) {
window.location = "http://asmlk.com/widget_adblock.php?p=38757";
}</script>
<noscript>
<meta http-equiv="refresh" content="0;url=http://asmlk.com/widget_nojs.php?p=38757"/>
</noscript>
<!-- End of content locker code -->
</head>
<body>
<?php
$userErr ="";
$emailErr ="";
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if (strpos($url, 'error=user-empty') !== false) {
$userErr ="Please enter your username!";
}
if (strpos($url, 'error=email-empty') !== false) {
$emailErr ="Please enter your email!";
echo $emailErr;
}
if (strpos($url, 'error=email-incorrect') !== false) {
$emailErr ="Please enter a valid email!";
echo $emailErr;
}
if (strpos($url, 'error=succes') !== false) {
$entry = 'You have entered succesfully!';
}
?>
<h1> Please enter the following info: </h1>
<form method="post" action="enter.php">
Username: <input type="text" name="username" placeholder="Username" /> <br>
<span class="error"><?php echo $userErr ?></span><br>
E-mail: <input type="text" name="email" placeholder="E-mail" /><br>
<span class="error"><?php echo $emailErr ?></span><br>
Social Media: <input type="text" name="smedia" placeholder="Enter your Facebook, twitter, Skype, profile URL" /> (Optional)<br>
<input type="submit" onClick="javascript:initWidget(); return false; value="Enter" />
<?php echo $entry ?>
</form>
</body>
</html>
If i would run the code above, normally when i click the Enter button the PHP validation works, once i add the OnClick function it doesnt works anymore.
Try this:
Add id to your form:
<form method="post" action="enter.php" id="myForm">
Attach the javascript form submit method to your button:
<input type="submit" onClick="javascript:initWidget();document.getElementById('myForm').submit();" value="Enter" />
This way your onClick method might not override the browser submit action.
Assign the event handler on submit event
<form method="post" action="enter.php" onsubmit="return !!initWidget();">
and instead of explicitly returning false you can return Boolean representation of whatever value initWidget returned.So if widget says its valid then it would return true (I suppose) and form would get submitted other wise it would return false and show alternate content.

PHP: Echoing an input submitted from a form

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>

Trying to validate a form client and server side

The client side validation looks something like this:
function validateFname() {
var x = document.getElementById('fname').value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
The server side below it:
if(isset($_POST['SubmitForm'])){
if(empty($_POST['fname'])){
echo "First name cannot be empty!<br/><br/>";
return false;
}
and the form itself below that:
<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>"
accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" onsubmit="return validateFname()"
class="required" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" value="Send"/>
Ofcourse there is a lot more to it but ive just given one example above. I am trying to figure out why the (clientside)javascript function is not working and instead the (server) php error is coming up. I need to be able to have the client run validation checks before the server to reduce load.
The onsubmit is a event that belongs to the <form> element. You have placed it with the submit button which won't work.
Here's a working fiddle:
Demo
Reference
<form name = 'checkout' method='post' action="<?php echo $_SERVER['PHP_SELF']; ?>" accept-charset='UTF-8'>
First Name:<input type="text" name="fname" id="fname" value="<?php echo $fname;?>" />
<input type="submit" name="SubmitForm" onClick="return validateFname()" value="Send"/>
</form>
try the above code. Instead of using onSubmit in input text field use onClick in submit button.
good luck

How to show box after submit value in form

So I have pop-up window where user need to enter name, after clicking submit button this window close.
You can test it here: http://eurokos.lt/under20/button.php (Click 21 button, then try to enter any value and see what happens)
For this pop-up box I've used function:
function popUp() {
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
This function is used for X button to close window:
function closeWindow() {
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none';
}
My button which open pop-up window looks like:
Echo "<input type='button' onclick='popUp();' value='".$i."' />";
And here is PHP_SELF and form:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "</br>You have entered: <b> $name </b>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
`
What I need to do that posted result what entered and window not closed?
Maybe I need to use popUp() function again when submitting? But how to do that correctly? Thank you.
Try this:
html:
<form method="post" action="" onsubmit="return display()">
<div id="answer"></div>
<input type="text" name="name" id="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
javascript:
function display(){
var ans = document.getElementById("name").value
document.getElementById("answer").innerHTML="You have entered:"+ans;
return false;
}
Update:
function popUp(){
document.getElementById("answer").innerHTML=""; //Add these in your popup function
document.getElementById("name").value="";
}
First of all i suggest you to avoid PHP_SELF in the action it can be manipulated by people and it's not good.
at top of page try to do :
<?php
$thispage = $_SERVER['PHP_SELF'];
?>
<html>
.
.
.
<form method="post" action="<?=$thispage?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
</html>
Then, using the action for sending data to PHP, will reload the page so you are probabilly losing all the inline fix you did.
Try to get the input values after the submit, assign them to varibles and do, for example:
xmlhttp.open("POST","<?=$thispage?>",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=name");
with an asynchronous call you don't reload the page and you don't lost your changes

Categories