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.
Related
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.
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;
}
I have PHP code which successfully gets the contents of a directory on my server.
I wish to then write this array to a specific div on my main html page (so that I can parse this later and use this information further)
Currently my PHP navigates me away from my current page to write this array which I want to prevent.
Furthermore I wish to do all of the PHP work on a button click, and return the values on the main html page after.
How can I do this???
My button on my html page is as follows:
<form action="PHP_Function.php">
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />
</form>
And my PHP code looks like this to carry out the work:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
}}
I have an array: "IfPresentArray" which I then wish to write to my main html page:
if(in_array("Facebook.xml", $dirArray)){
$IfPresentArray[0]="1";
}else {
$IfPresentArray[0]="0";
}
Any help would be greatly appreciated as I am very new to PHP.
Thanks in advance
You need to use AJAX techniques to do this. Use a Javascript framework like jQuery to react to the button click, make a request to your PHP script, and then update the contents of the div.
See http://api.jquery.com/click/ for handling clicks, and http://api.jquery.com/jQuery.ajax/ for making the request.
Good luck!
You will need to use an ajax call. This allows your to click some div, send something to the server, receive a response and display an output in many different formats.
You can either reference the jQuery library in your header
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
or just download it and save it whereever
Here is a basic ajax call:
<script>
$(document).ready(function(){
$('#someval').click(function(){
var content = $('#somecontenttoadd').val; //this could be many things... etc(.text, .html)
$.ajax({
type:'post',
url: 'PHP_Function.php',
data: 'action='+content,
success: function(resp){
$('#somediv').html(resp); //lets put the information into a div
//this could be anything response format like .val or .text instead of .html
},
error: function(e){
alert('Error: ' + e);
}
});
});
});
</script>
HTML -- you can get rid of the tags and just use the id of the object.
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" id="someval"/>
As others said, AJAX is the solution, I will give you the code that works for me, so that you have an exact starting point.
As I understand you have a separate html page and a php file that includes your function.
In order to make this work you will have to implement a function with an AJAX call.
This should be placed in a javascript file and will be invoked after the form submit button is clicked on the html page.
The AJAX call will then invoke your php function, get the response data back from php.
The javascript function will update the html page in the end.
You will need three files:
main.html
script.js
function.php
Let me replace my original answer with a full example of the three files.
main.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form id="myForm" method="post" action="function.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
</form>
<div class="modal-footer">
<button type="submit" form="myForm" class="btn btn-primary" id="SaveButton">Submit</button>
</div>
<div id="resultbox">
</div>
</div>
</body>
</html>
Here we included jQuery, our own javascript and bootstrap just to look better. the form action is our function.php, the form 'id' is used in our jQuery code. the "result box" box will display the response.
script.js
$(function(){
$("#myForm").submit(function(event) {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data)
{
//display data...
$("#resultbox").html(data.name).show;
}
});
return false;
});
});
this will override the default form submit behavior. I had a typo here in the original answer, I fixed it. url and data are taken from the html form, dataType is set to json, because we expect a json back.
function.php
<?php
echo json_encode(array('name' => $_POST['name']));
Our php code is just one line, we build an array and return it as json. You can then used in jQuery, just like any other json, as shown in the above code.
I'm new to PHP. I want to use a (HTML) input type = button to make the content of a HTML empty.
I searched the web, if I use fopen(file.html,w+), it will clear the files content:
"w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist)".
Source: http://www.w3schools.com/php/func_filesystem_fopen.asp
My problem is that there is probably a bit of code missing or syntax mistakes, because when I press the button nothing happens.
I really don't know and couldn't find anything on the world wide web, it's probably really simple. Sorry in advance if I wrote the question wrong.
HTML code
<input type="button" name="clearlog" id="clearlog" value="Clearlog" class="btn btn-default">
PHP code:
<?php
// clear log
if(isset($_POST['clearlog']))
{
function cleartlog()
{
$fp = fopen("log.html", 'w+');
fwrite($fp, "");
fclose($fp);
}
}
?>
The PHP code is in an external file, but is required it in my index.php.
PS: is it better to use the ftruncate function?
Source: http://www.w3schools.com/php/func_filesystem_ftruncate.asp
What you're trying to do here is far beyond the scope of your current understanding. You don't have anything associating that button to any code. Either the button needs to be part of a form that submits to a php file, or you need a javascript click event listener added to it which will then send an ajax request to the server (php) to call your php code.
Form submission directly to a php file (requires a page load) is a mostly outdated practice. Using Ajax is preferred.
The logic is simple:
Attach a javascript click event listener to the button.
The click function will send an ajax request to a page where your php code to run.
jQuery is not necessary, but with jQuery, the ajax call could be as simple as $.get('foo.php). and then whatever php code on foo.php will be executed.
You should use a form which will connect to the server and the PHP should clear the log.html file.
<form action="wipeFileContents.php">
<input type="submit" value="Clear Log File">
</form>
It will be the simplest solution, although you can go the harder AJAX way which is theoretically faster, but requires you to learn javascript.
you could try the following:
HTML
<form action='myfile.php'>
<input type="submit" value="clear">
</form>
PHP
if(isset($_POST['clear']))
{
file_put_contents("log.html", "");
}