I have series of dropdown boxes which can be selected by the user. I then want to have two different submit buttons that will do two different actions with the selected data. I am trying to code the submit button to run the selected php, but when I click the button does nothing. Any help is appreciated, my code is below. AFAIK the only relevant bits are my formSubmit function and the input tag near the bottom of the code.
edit: I have edited out a bulk of the code and left the pieces that I think are relevant. Please let me know if more info is needed.
<!DOCTYPE html>
<?php
require 'config.php'; // Database connection
//////// End of connecting to database ////////
?>
<html>
<head>
<SCRIPT language="JavaScript">
//Scripts
function submitForm(action)
{
document.getElementById('f1').action = action;
document.getElementById('f1').submit();
}
</script>
</head>
<body>
<div>
<?Php
//Beginning of Form
echo "<form method=post name='f1' action =''>";
//Dropdown boxes are here
//This line is what is not working:
echo "<input type='submit' value='Careers' onclick=\"submitForm('rt.php')\">";
echo "</form>";
?>
</div>
</body>
</html>
Not quite sure what is wrong with the function, xe4me may have the correct answer. However, I just changed my onClick to this and it worked:
onClick=\"document.f1.action='rt.php'; document.f1.submit(); return true;\"
You're using document.getElementById('f1') in submitForm function
function submitForm(action)
{
document.getElementById('f1').action = action;
document.getElementById('f1').submit();
}
But your form doesn't have id attribute because of this line of code
echo "<form method=post name='f1' action =''>";
so the form won't be submitted when you click the Careers button. You need to add id='f1' attribute to the form by changing the above line of code to below
echo "<form id='f1' method='post' name='f1' action =''>";
Try the jQuery method :
http://api.jquery.com/jquery.post/
with
How to get ID of clicked element with jQuery
Whenever any button is clicked, find its id and based on that, use $.post to post data to the location you want.
you must add a class to your button and call the onclick based on that class name :
<?Php
....
echo "<input type='submit' class='submitter' data-action='rt.php' value='Careers' >";
echo "</form>";
?>
// In Javascript :
document.getElementByClassName('submitter').onclick = function(){
var action = this.data('action');
document.getElementById('f1').action = action;
document.getElementById('f1').submit();
}
Related
I want to create a confirm yes/no box in php
my code like this:
<?php
if(isset($_REQUEST['id']))
{
?>
<script>
var cf=confirm("do you want to delete Y/N");
if(cf)
{ i want to call code edit of php
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<form name="frm" method="post" action="edit.php">
Edit <br>
Edit <br>
Edit <br>
</form>
</body>
</html>
I Want to when press Yes i call code edit in PHP
But it do not work.
Can you help me ?
Thanks you
Just use inline onclick event.
This is a simple techique, you can use it in your PHP page.
Edit
In your code, you have mentioned PHP but, have used JavaScript.
If you want to do a confirm with PHP,
Create an intermediate page for confirmation.
Post form data there.
On confirmation page, add two submit buttons:
Yes: If pressed this, redirect/post to edit page.
No: If pressed this, redirect back to form
So, your confirmation page should be:
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['confirm'])) {
if ($_POST['confirm'] == 'Yes') {
header("Location:edit.php?id=1");
}
else if ($_POST['confirm'] == 'No') {
header("goBack.php");
}
}
?>
<form method="post">
<?php
if(isset($_REQUEST['id']))
{
?>
<input type="submit" name="confirm" value="Yes"><br/>
<input type="submit" name="confirm" value="No"><br/>
<?php
}
?>
</form>
Put an id on your form:
Create an event listener for the form's onsubmit event
<script>
function onFormSubmission(e){
return confirm("do you want to delete Y/N");
}
var frm = document.getElementById('frm');
frm.addEventListener("submit", onFormSubmission);
</script>
When the user submits a form they will be prompted with your message. If they click Yes the function will return true and the form will be submitted. Otherwise the function will return false and the form submission will be cancelled
I think this is what you want to do:
<?php
//YOU MUST BE SURE THAT YOUR URL CONTAINS THE $_REQUEST['id'] PARAMETER, OTHERWISE IT WON'T WORK FROM YOUR CODE... IF YOU WANT IT TO WORK REGARDLESS OF THAT, JUST COMMENT OUT THE IF(ISSET(... BLOCK...
$editURL = "edit.php"; //EDIT URL HERE
if(isset($_REQUEST['id'])) {
//ASSIGN THE ID TO A VARIABLE FOR BUILDING THE URL LATER IN JS...
//THE DEFAULT ID IS 1 BUT YOU CAN DECIDE WITH YOUR OWN LOGIC
$defaultID = ($dID = intval(trim($_REQUEST['id']))) ? $dID : 1;
?>
<script>
function confirmEdit(evt){
evt.preventDefault();
var cf=confirm("do you want to delete Y/N");
var id=<?php echo defaultID; ?>;
if(cf){
//i want to call code edit of php
//HERE'S THE CODE YOU MAY NEED TO RUN;
if(id){
//RETURN TRUE SO THAT THE SCRIPT WITH LINK TO THE APPROPRIATE URL
return true;
// OR REDIRECT WITH JAVASCRIPT TO EDIT PAGE WITH APPROPRIATE ID
//window.location = "" + <?php echo $editURL; ?> + "?id=" + id; //YOU ALREADY HAVE THE EDIT URL... JUST APPEND THE QUERY-STRING WITH ID TO USE IN THE EDIT PAGE
// You might also just (without redirecting) return true here so to that the page continues like you just clicked on the link itself...
}
}
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<!-- THE FORM TAG IS NOT NECESSARY IN THIS CASE SINCE YOUR ANCHOR TAGS HAVE THE EXACT URL YOU WANT ASSOCIATED WITH THEM... AND YOU DON'T EVEN NEED JAVASCRIPT IN THIS CASE... BECAUSE THE HREF OF THE LINKS ARE HARD-CODED... -->
<!-- <form name="frm" method="post" action="edit.php"> -->
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-1' href="edit.php?id=1">Edit Page 1 </a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-2' href="edit.php?id=2">Edit Page 2</a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-3' href="edit.php?id=3">Edit Page 3</a> <br>
<!-- </form> -->
</body>
</html>
So, now clicking on any of the Links will Ask me to confirm if I want to delete the Resource or not. If I choose yes, then the appropriate page is loaded for the Process...
not sure if the other answers really answered your question, this was my problem too, then I experimented and here's what I came up with:
.
confirmation in php :
$Confirmation = "<script> window.confirm('Your confirmation message here');
</script>";
echo $Confirmation;
if ($Confirmation == true) {
your code goes here
}
that's all, other people might look for this, you're welcome :)
I was looking to simply have a confirmation box in php before triggering POST isset without going through javascript:
echo "<input id='send_btn' type='submit' value='previous'
name='previous' OnClick=\"return confirm('Are you sure you want to go
to previous');\" >";
This appeared for me to be the easiest solution.
i have set the form action to a text retrieved from the database which has an id.my problem is when the form action executed it always shows the first id even if i clicked on the text holding id=2.I have checked the page source and it's showing the correct id for all the text.
here is my view code
<?php foreach ($content as $cont):?>
<form id="offer" method="post" action="<?php echo base_url() . 'index.php/pages/detail'?>">
<input type='hidden' name='cont_id'id='cont_id' value='<?php echo $cont->id?>'>
<a onclick="document.getElementById('offer').submit();"><?php echo $cont->title?></a>
</br>
</form>
<?php endforeach;?>
</div>
<script>
function submitForm() {
document.getElementById("offer").submit();}
</script>
here is my controller :
echo $this->input->post('cont_id');
You can use .submit()
Submit
If you have JAVASCRIPT knowledge you can use the
document.getElementById("myForm").submit();
method to submit the form..
create a Javascript Function
<script>
function submitForm()
{
document.getElementById("myForm").submit();
}
</script>
use this code for the text you want to hyperlink the button to
<h1 onclick="submitForm()">Click on this text</h1>
Hi i wannna get variable $_POST by link to self pages. Example :
<?PHP
$var = 'PIG';
echo "<a href='test.php?var=$var'>link</a>";
if (isset($_POST['var']))
{
echo $_POST['var']);
}
?>
it links to own pages. (test.php)
It not works, who can help me please. Thanks
A link cannot POST data, only GET.
In contrast to the GET request method where only a URL and headers are
sent to the server, POST requests also include a message body. This
allows for arbitrary length data of any type to be sent to the server.
Basically, a POST requires two requests, 1) the server receives the "normal" request, with an extra header value indicating that more data needs to be sent. At that point, the server sends an acknowledge and 2) the client sends the POST body. This behavior cannot be achieved only with a link.
However, there are solutions to this and I have seen some technique, among others, outputting a form with an autosubmit, something like
<form name="frm" method="post" action="http://your.domain.com/path/to/page.php?param1=1¶m2=2">
<input type="hidden" name="foo" value="bar" />
</form>
<script type="text/javascript">
document.forms["frm"].submit();
</script>
which would result into calling page.php with these arguments
$_GET = array('param1' => '1', 'param2' => '2');
$_POST = array('foo' => 'bar');
Note that this is a simple "redirect" method, but you can create <a> elements to actually trigger some hidden form like that instead of using the standard link. (untested code)
A simple link
<script type="text/javascript">
function dopost(url, params) {
var pe = '';
for (var param : params) {
pe += '<input type="hidden" name="'+param+'" value="'+params[param]+'" />';
}
var frmName = "frm" + new Date().getTime();
var form = '<form name="'+frmName+'" method="post" action="'+url'">'+pe+'</form>';
var wrapper = document.createElement("div");
wrapper.innerHTML = form;
document.body.appendChild(wrapper);
document.forms[frmName].submit();
}
</script>
This is probably what you need, actually.
Items in the query string are available via $_GET, not $_POST, since they are not actually POSTed. If you want to POST then you must either use a form with a method of post, or you must perform a XHR as POST.
Unfortunately, you really can't do that. If you need to use an anchor to submit a value, then you will need to access the variables through $_GET or $_REQUEST.
If it has to be a $_POST (if you are set in that design decision, because $_GET actually makes a lot more sense there), you can use a form and the style the submit button to make it look very much like a link. Put this code in a text editor and check it out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
.button {border:none;background-color:#FFFFFF}
.button:hover{ color:blue; }
</style>
</head>
<body>
<form action="test.php">
<input type="hidden" name="var" value="<?php echo $val; ?>" />
This kinda looks like a link:
<input type="submit" value="link" class="button" />
</form>
</body>
</html>
If you have multiple links and you don't want to rewrite all of them, just add one fake form like this:
<form id="fakeForm" method="post">
<input type="hidden" name="post_key" value="post_value" />
</form>
and set up proper jquery:
$('a').click(function(event){
event.preventDefault();
$('#fakeForm').attr('action',$(this).attr('href')).submit();
});
In this case, when you click on any link, the landing page receives the post_value variable.
Note that if the link is clicked with other than left click (or js is disabled), the link works properly, but the value isn't passed!
This code below demonstrates T30's idea works.
My rationale for passing via $_POST is to prevent certain variables from being exposed in the url which is accomplished here. However, they would still be exposed via "view source".
<?php
/*
This demonstrates how to set $_POST from a link in .php without ajax based on the idea from http://stackoverflow.com/a/27621672/1827488. The rationale for doing so is to prevent certain variables ('userid') from being exposed in the url via $_GET. However, there does not seem to be a way to avoid those variables being exposed by 'view source'.
*/
echo "<!DOCTYPE html><html lang='en'><head><title>Test Data Link</title></head><body>";
// only one hidden form
echo "<form class='hiddenForm' method='post'>
<input class='hiddenFormUserid' type='hidden' name='userid'/>
</form>";
// as many links as you need
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=101>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=101>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=102>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=102>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=103>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=103>Followers</a></p>";
echo "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>";
echo "<script type='text/javascript'>
console.log('jq');
$('.hiddenFormLink').click(function(e){
console.log('data-userid=' + $(this).attr('data-userid') + ', value=' + $('.hiddenFormUserid').val());
e.preventDefault();
$('.hiddenFormUserid')
.val($(this).attr('data-userid'));
$('.hiddenForm')
.attr('action',$(this).attr('href'))
.submit();
});
</script>";
if (isset($_GET["following"]) || isset($_GET["followers"])) {
if (isset($_GET["following"])) {
echo "followed by ";
} else {
echo "followers of ";
}
if (isset($_POST["userid"])) {
echo $_POST["userid"]."<br>";
} else {
echo "no post<br>";
}
} else {
echo "no get<br>";
}
echo "</body></html>";
$_POST["userid"] = "";
?>
I just started using jQuery in the past few days. I love how it makes functions simple. However because I am very new to using Javascript, I keep hitting a road block with one function.
I am trying to bind a couple functions together, but I'm not sure if I am doing it in the right order. What I want it to do is get a variable from a selector href='#from=xxxxx&to=xxxxx', with the xxxxx being a value printed out from a DB using PHP.
Then create a DOM window to display a form and insert those values into the hidden input fields. I have been stuck trying to figure out a way to pass those variables from the link to the form.
Here is my script:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://swip.codylindley.com/jquery.DOMWindow.js"></script>
</head>
<body>
<div id="msgBox" style="display:none"></div>
<?php $from="0"; $to="0";
for ($x=1; $x<=4; $x++){ $from++; $to++; ?>
user<?php echo $x;?><br>
<?php } ?>
<script type="text/javascript">
$("#msgBox").append("<form id='myForm' method='post' action='index.php'><div style='border:1px solid #cc0; width:300px;'><input type='hidden' value='<?php echo $from;?>'><input type='hidden' value='<?php echo $to;?>'>subject:<input type='text' name='subject'><br>message:<textarea class='mbox' name='msg'></textarea><br><input type='submit' value='submit'></div></form>");
$('.foo').click(function(){
$.openDOMWindow({
windowSourceID:'#msgBox',
height:135,
width:300,
overlay:0,
positionType:'anchoredSingleWindow',
windowBGColor:'#f9f5f5',
anchoredSelector:'.foo',
positionLeft:200,
positionTop:150
});
$("#msgBox").trigger();
return false;
});
</script></body></html>
In the handler for the click event on each link you can get a reference to the target link and extract the values from the href attribute and then set the values of the hidden fields in the form.
$('.foo').click(function() {
var href = $(this).attr('href'); // will contain the string "#from=0&to=0"
var from,to = ... // extarct from string by splitting by & or using url parse library
$('#msgBox').find("input[name='from']").val(from);
$('#msgBox').find("input[name='to']").val(to);
// rest of code...
});
Hiya:
i know some people would be so tired of my questions, but I'm working on a uni project and need to get it done as soon as possible. This question is about using JS on a button(button) and sending a php_my_sql update on the same button. The problem is JS uses button, right? but PHP uses button(submit). How can I get these two to work on one of these buttons, cuz there has to be only one button.
this is my code for JS
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex)
}
</script>
HTML
<form method="post">
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="**submit/button**" onclick="formAction()" name="Collect" value="Collect" /></form>
PHP
<?
if (isset($_POST['Collect'])) {
mysql_query("UPDATE Player SET score = score+10
WHERE name = 'Rob Jackson' AND rank = 'Lieutenant'");
}
?>
This can be a way
Submit the form through JS after removing parameter
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex);
document.forms[0].submit();
}
</script>
Input type button
<input type="button" onclick="formAction()" name="Collect" value="Collect" />
Embed jQuery and use $.post() to send an AJAX request.
JavaScript can interact with the button whilst the user is navigating the page and entering data into the form. The instant the user pushes the submit button and the request for the form submission is sent JS no longer has control. The request is sent to the form's action (most likely a PHP file) which processes the request and gives an answer back.
If you really need to combine the two, look into AJAX.
<?php print_r($_POST); ?>
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect");
x.remove(x.selectedIndex);
submit_form();
}
function submit_form() {
document.form1.submit();
}
</script>
<form method="post" name='form1'>
<input type='hidden' name='Collect'/>
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="button" onclick="formAction()" name="Collect" value="Collect" /></form>
<?
if (isset($_POST['Collect'])) {
//do whatever update you want
}
?>
Simple Solution
Make this modification in the form tag
<form method="post" onsubmit="return formAction()">
In JavaScript function add a line "return true;" at the end of the function.
Voila ..!!! you are done..!!
Enjoy..!!