It should be quite simple, yet it does not work for me. I need to get user input to form and print it on another php page using GET or POST (because I think it is the easiest option and I am just building a prototype)
My default.php code:
<html>
<head>
<script src="pytimber.js"></script>
</head>
<body>
<p>Enter the parameter</p>
<form method="post" action="php/plot.php">
<input type="text" name='parameter' value="check"/>
<input type="button" value="Plot" class="homebutton" id="plot"
onclick="plot()"/>
</form>
</body>
</html>
Javascript code:
>
function plot() {
alert('JI')
document.location.href = 'php/plot.php';
}
function goBack() {
document.location.href = '../Default.php';
}
Second php page code:
<html>
<head>
<script src="../pytimber.js"></script>
<?PHP
$username = $_POST["parameter"];
print ($username);
?>
</head>
<html/>
1st : Simple remove all your javascript .
2nd : Change the button type to submit
<input type="submit" value="Plot" name="submit" class="homebutton" id="plot" />
3rd : In second page just echo the post variable with isset() function
if(isset( $_POST["parameter"]))
echo $_POST["parameter"];
Actually you don't need the js code, you just need to put a name on your button and change the type to submit and do this to another page:
<?php if(isset($_POST["buttonname"])){
echo $_POST["parameter"]; } ?>
As stated by different people here, the easiest way is to utilise the awesomeness of the submit button, and let HTML take care of the rest.
But, seeing as you use javascript to 'post' the form, let me explain how that could be done as well.
By adding an id to the form, and using that to submit through js, it will work.
Change the form tag and add an id:
<form method="post" action="php/plot.php" id="js_form">
Change the plot function to this:
function plot() {
alert('JI');
document.forms["js_form"].submit();
}
This way the javascript will act as a submit button and send all the data to plot.php
Either
change button type from 'button' to 'submit'
Or
change in js function 'plot'
function plot(){
document.forms[0].submit();
OR
document.getElementById('formid')'.submit;
}
Related
I'm having a form with its action link created dynamically.
Basically the page is populated with pagination and the form action link is different for 1st page and last page. I have a timer running and when timeout I want the form to be submitted.
Now here is the problem. During timeout if the user is on 1st page, the javascript submit function submit with the dynamic action link created for 1st. My original purpose is to submit the form for the last page action link.
<form method="post" id="submitmyform" <?php if($page==$firstpage){?> action="1st/page/action/link"<?php }elseif($page==$lastpage){?>action="last/page/action/link"<?php } ?> >
<?php if($page==$firstpage){?>
<input type="hidden" name="firstpagecontent1" value="somthing" >
<input type="hidden" name="firstpagecontent2" value="somthingelse" >
<button type="submit" id="firstpagebutton" name="firstpagebtn" value="1">
<?php }elseif($page==$lastpage){?>
<input type="hidden" name="lastpagecontent1" value="somthing" >
<input type="hidden" name="lastpagecontent2" value="somthingelse" >
<button type="submit" id="lastpagebutton" name="lastpagebtn" value="2">
<?php } ?>
</form>
<script>
function ontimeout{
var button = document.getElementById('lastpagebutton'),
form = button.form;
form.addEventListener('submit', function(){
return true;
})
}
</script>
I have no problem with the PHP part. I'm only trying to figure out how JS can work for me. The above JS is not working. It frequently submit but not with the last page values. Could anyone please guide me to find out where I'm stuck and possibly show a way.
Note: Above code is only illustration to give the concept. I have not included the pagination here as its long piece of code as a whole and I'm only having problem with JS.
Many Thanks in advance.
setTimeout(function(){
// Invoke function every 10 minutes
$('#lastpagebutton').trigger('click');
}, 600000);
Using jquery
Since you're using PHP to change the form action, until you got to the last page there is not access to the action value, meaning it won't take place in the form submit action while it is a different page than the last one.
I would suggest having that last page url/action in a different php variable, so it can be used as for JS expiration/redirection anytime. Something like:
1: Timeout - Redirection last page
<?php
$lastPageUrl = 'https://example.com';
?>
<script type="application/javascript">
setTimeout(function() { timeOut() }, 3000);
function timeOut() {
var lastPage = "<?= $lastPageUrl ?>";
location.replace(lastPage);
}
</script>
2: Timeout - Update form action last page
<script type="application/javascript">
function timeOut() {
var form = document.getElementById('submitmyform');
form.action = '<?= $lastPageUrl ?>';
}
</script>
I have a form in my codeigniter project using google's invisible recaptcha like so:
HTML
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmitInvisRecaptcha(token) {
document.getElementById("contact_us-form").submit();
}
</script>
</head>
<body>
<form id="contact_us-form" method="post" action="/info/contact_us">
<div>
<label>full name</label>
<input type="text" name="full_name" value="<?php echo $this->input->post('full_name'); ?>"/>
</div>
<div>
<button type="submit"
id="submit_btn"
class="btn my-other-styles g-recaptcha"
data-sitekey="<?php echo $sitekey; ?>"
data-callback="onSubmitInvisRecaptcha">
Submit
</button>
</div>
</form>
</body>
</html>
PHP
defined('BASEPATH') OR exit('No direct script access allowed');
class Info extends MY_Controller
{
function contact_us()
{
print_r($_POST);
}
}
from my code I, I have 2 problems: (I hope it's ok to ask about multiple problems in 1 post)
the recaptcha icon is nowhere to be found in the page. I've checked the sitekey I use in the form is the same as the one I find in www.google.com/recaptcha/admin.
in the contact_us function, the print_r($_POST); there is no g-recaptcha-response..
P.S.: the form is a part of another page that is shown using ajax so the form is wrapped by another <div>.
finally I've found the answer from this SO answer. The link shows a code for multiple recaptcha/form in one page, but it's simple enough to understand and modify for my needs.
basically, if I understand correctly, the reason my code failed was because of these points:
I need to use a separate <div> element to apply the recaptcha instead of the submit button.
google recaptcha will try to find the appointed element when the page loads, otherwise, I need to render and execute the grecaptcha manually using javascript if the element only appears or added to the page after some action.
From this earlier thread I thought I learned that form data could be sent by POST method using javascript submit() command. But I can't get it to work. This demo doesn't make obvious sense with respect to purpose but bear with me. I just wanted to test this specific command which doesn't seem to work for me. Can you please help me? Clicking the regular submit button sends the post data ok but activating the javascript via the link does not.
<html><body>
<?php
$self = $_SERVER['PHP_SELF'];
$posttext = file_get_contents('php://input');
echo "Received input: ".chr(34).$posttext.chr(34)."<br><br>";
echo "<form id='test' action='{$self}' method='post'>";
?>
Please fill in the fields with any text:<br><br>
foo: <input type="text" name="foofield"><br><br>
bar: <input type="text" name="barfield"><br><br>
<input type="submit" value="Submit button works"><br><br>
Submitting by JS not working – why?
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
$(document).ready(function(){
$("a#submitlink").click(function(){
alert("Yes, the link has been clicked. It is not that.");
$("form#test").submit();
});
});
});
</script>
</body></html>
You need to: event.preventDefault(); the default behaviour from the <a>. The problem is if you don't do that, the page reloads cause that is what the <a> tag does. So even you submit the data you also refresh the page where the submitted data gets lost.
$("a#submitlink").click(function(event){
event.preventDefault();
$("form#test").submit();
});
The other solution is to add # in the href of the <a> tag like:
Submitting by JS not working – why?
this will also prevent the <a> tag from doing a refresh.
i try to submit a form without submit button with javascript but not work. My code is:
<?php echo form_dropdown('week_id',$weeklist,'onChange="submitform();"','class ="form-control selectpicker" data-style="btn-danger"'); ?>
and the js is:
<script type="text/javascript">
function submitform() {
document.autosubmit.submit();
}
The name and the id of the form is autosubmit. Also i will try to put the week_id inside the function but not work too. Any suggestions? Thanks in advnace.
If you're going to use an ID:
document.querySelector('#autosubmit').submit();
If you just want to target the form, you need to use the name="" attribute, not the id="" attribute, something like this:
document.forms['autosubmit'].submit();
I would like to run a php function from a javascript code, to be more specific I got a button that delete a record from the database. The function that does that named
delete_post($id)
Here is what I tried:
<input type="submit" name="delete" value="delete"
onClick="if(confirm('Are you sure?')) {<?php delete_post($row['id']);?>}">
When I click the button, there is no alert box. The funny thing is if I don't call a function inside the php code and I do something else such as echo the alert does pop out but the php code doesn't executed.
So, how can I do that? How can I run a php code inside my javascript onClick code.
You can't. PHP is supposed to be run before the page loads, thus giving it the name Pre-Hypertext Protocol. If you want to run PHP after a page loads via JavaScript, the best approach would be linking to a new page that runs the PHP, then returning the user back.
file1.php:
...
<input type="submit" name="delete" value="delete" onClick="if(confirm('Are you sure?')) document.location.href='file2.php';">
...
file2.php:
<!doctype html>
<html>
<head>
<?php
delete_post($row['id']);
?>
<meta http-equiv="refresh" content="0; url=file1.php" />
</head>
<body>
<p>You will be redirected soon; please wait. If you are not automatically redirected, click here.</p>
</body>
</html>
Assuming you would have multiple IDs, you can keep them all onto one redirect page:
if(confirm('Are you sure?')) document.location='file2.php?id=2'; // file1.php
delete_post($row[$_GET["id"]]); // file2.php
But do not put PHP code directly into the query string, or your site could be susceptible to PHP injection
You can't RUN php code in Javascript , but you can INVOKE it through JS/Ajax. For good practice split your php and JS , for example create a page that takes an ID and deletes it's row (i'm guessing your using REST) and invoke it through JS.
Cleaner , effective , and more secure
From your question, i would suggest you give jquery a try.
link to Jquery on your page's head section,
here is your js function
function deleteRow(id)
{
var url='path/to/page.php';
$("#loading_text").html('Performing Action Please Wait...');
$.POST(url,{ row_id: id } ,function(data){ $("#loading_text").html(data) });
}
This should do it for you.
Since its a delete, am using $.post Let me know if you find any more issues
here is a link to jQuery hosted by google CDN
//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js
This is how your form should look like
<form>
<label for="Number"></label>
<input type="text" name="some_name" id="some_id" value="foo bar">
<input type="submit" name="delete" value="delete"
onClick="javascript: deleteRow(the_id_of_the_row);">
</form>
<br>
<div id="loader_text"></div>
now your php page that does the delete could look like this
<?php
$row_id = some_sanitisation_function($_POST['row_id']) //so as to clean and check user input
delete_post($row_id);
echo "Row deleted Successfully"; //success or failure message
?>
This should do it for you.