Trying to write to a txt file upon button click. Not sure how to do it and my code isnt working. Im starting to think i might need AJAX? If so, can someone give me a quick pointer in the right direction? Please and thankyou in advance!
Here's my code:
<?php
//write to file on button event
function buttonWrite()
{
$filename = 'button.txt';
# $fp = fopen("messages/".$filename, 'wb');
if (!$fp)
{
echo '<p><strong>Cannot generate message file</strong></p></body></html>';
exit;
}
$outputstring = 'Hello, i have been generated by the button';
fwrite($fp, $outputstring);
}
?>
<html>
<head>
<title>Button Writer</title>
</head>
<body>
<button type="button" onclick="buttonWrite()">Write to File</button>
</body>
</html>
UPDATE!
None of these answers actually work at all.. Not sure if its the server im hosting on or what, but yeah the just dont work.. any ideas guys ?
Create a PHP file .Lets say "abc.php".It contains:
<?PHP
$filename = 'button.txt';
# $fp = fopen("messages/".$filename, 'wb');
if (!$fp)
{
echo '<p><strong>Cannot generate message file</strong></p></body></html>';
exit;
}
else
{
$outputstring = 'Hello, i have been generated by the button';
fwrite($fp, $outputstring);
Echo "Message inserted";
}
?>
HTML file
<html>
<head>
<title>Button Writer</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.10.1.js'></script>
</head>
<body>
<button id="button1" type="button">Write to File</button>
</body>
<script type='text/javascript'>
$('#button1').click(function(){
$.ajax({
type: "POST",
url: "abc.php",
data: "",
success: function(msg){
alert(msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Some error occured");
}
});
});
</script>
</html>
You do it wrong - javascript and php can't be executed together in HTML.
What you need to do is to create:
1) "onclick" button event, that execute AJAX request to your server. I'll use jQuery in my examples for the simplicity.
<button id="btn">SAVE FILE</button>
<script type="text/javascript">
// bind click event to button
$('#btn').click(function() {
// send ajax request to save.php (using POST method)
$.post('save.php', { text: "sample text", function(data) {
// output response to console
console.log(data);
});
});
</script>
2) create save.php file - it will be responsible for saving your data to the file
<?php
// saving sample text to file (it doesn't include validation!)
file_put_contents('file.txt', $_POST['text']);
die('file has been saved');
?>
Entire Code
Save.php
<?php
//write to file on button event
function buttonWrite()
{
$filename = 'button.txt';
$outputstring = "Hello, i have been generated by the button'\n";
file_put_contents($filename, $outputstring, FILE_APPEND | LOCK_EX);
}
?>
index.php or index.html
<html>
<head>
</head>
<body>
<form name="input" action="save.php">
<input type="submit" value="Write to File">
</form>
</html>
This should work it will write the $outputstring to the button.txt using the file_put_contents function
Related
I created simple code, that should pass JS variable to PHP on the same page. This is code that i have written so far:
<body>
<h3>Client side IP geolocation using ipinfo.io</h3>
<p><a onclick="" href="xyz.pdf" download id="xyz" value="x">test pdf</a></p>
<p><?php print_r($_SERVER['SERVER_NAME'] . '/' . $_SERVER['REQUEST_URI']); ?></p>
<p><?php
if(isset($_POST['city']))
{
$uid = $_POST['city'];
print_r("elo");
}
?></p>
</body>
<script>
$.get("http://ipinfo.io", function (response) {
if(response.city == 'Białystok') {
$("a").click(function() {
var city = response.city;
$.ajax({
type: "POST",
url: 'index.php',
data: { city : city },
success: function(data)
{
alert(city);
}
});
});
}
}, "jsonp");
</script>
So as u can see, im trying to pass city of the user, who downloaded specific file. When i test it locally, after clicking on download link
i get alert from success, so i guess I'm doing it correctly. But my PHP above doesn't print anything. There is no $_POST['city'] on the website.
Do you have any advice what I'm doing wrong?
If all you want is to print city name after clicking on the link then you don't need php for it.
<html>
<body>
<h3>Client side IP geolocation using ipinfo.io</h3>
<p><a onclick="" href="xyz.pdf" download id="xyz" value="x">test pdf</a></p>
<p><?php print_r($_SERVER['SERVER_NAME'] . '/' . $_SERVER['REQUEST_URI']); ?></p>
<p id="result">
<!-- Result will be printed here -->
</p>
</body>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
$.get("http://ipinfo.io", function (response) {
$("a").click(function() {
var city = response.city;
$('p#result').html("City Name: "+city);
});
}, "jsonp");
</script>
</html>
If you want something from php side then...
Write this condition in the starting of the file
<?php
if(isset($_POST['city'])) {
die("...Return something to the call from jquery");
}
?>
and this code should be followed by your remaining code.
Note: If you are expecting JSON data from php then use correct headers and output the json string from php. using die() won't solve the issue.
I am trying to get some data from a form post and outputting it in a PDF file with html2pdf on the same page. However, when trying to post the form data to the same page it won't open the PDF file, probably because the rest of the PHP file will come after the if($_POST). If I remove the code in the "else" part it downloads fine.
Is there any way around this? Or a better way to do it? I am creating form data with javascript so I need to post it to php somehow, but the code below is just a simplified example. Doesn't matter to me if solution is jquery/javascript/php but I essentially need to post an array to this PDF output after user action.
<?php
if(isset($_POST['sweets'])){
// get the HTML
ob_start();
?>
<page backtop="35mm" backbottom="20mm" backleft="15mm" backright="15mm">
<div id="p1-content">
<h3>Mer test</h3>
<p>Normalement une valeur devrait vous être demandée, puis affichée</p>
</div>
</page>
<?php
// PDF script to execute
$content = ob_get_clean();
// convert to PDF
require_once(dirname(__FILE__).'/html2pdf/vendor/autoload.php');
try
{
$html2pdf = new HTML2PDF('P', 'A4', 'en');
$html2pdf->writeHTML($content, isset($_GET['vuehtml']));
$html2pdf->Output('testprint.pdf','D');
}
catch(HTML2PDF_exception $e) {
echo $e;
exit;
}
?>
<?php
} else {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".sendData").click(function () {
var str = "";
$("select[name='sweets'] option:selected").each(function () {
str += $(this).text() + " ";
});
jQuery.ajax({
type: "POST",
data: $("form#a").serialize(),
success: function(data){
jQuery(".res").html(data);
$('#test').html(data);
}
});
var str = $("form").serialize();
$(".res").text(str);
});
});
</script>
<div id="test"></div>
<form id="a" action="" method="post">
<select name="sweets" >
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option>Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
</form>
<button class="sendData">Send Data</button>
<?php
}
?>
I was able to use example09 on the HTML2PDF page to post to the page itself, I only wish the examples were presented a bit better so I could have seen this right away.
The short of what I'm trying to do is search for a file and display a picture from the server. The HTML has a simple search bar that allows you to type in a search term. The JavaScript uses an ajax request to call the PHP file, and the PHP finds the image on the server and sends it back to be displayed.
What happens right now is that the image isn't displayed, and I get an icon indicating some invalid image. The ajax call appears to be working, but I think the data I'm sending back isn't correct. I've been trying to search for it but everyone seems to have a different opinion on how to do it and it's kind of confusing.
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script src="search.js"></script>
<style type="text/css"></style>
</head>
</body>
<header>
<h1>My Page</h1>
</header>
<input type=text name="search" id="searchbox" placeholder="Search...">
<input type=button value="Search" id=search><br>
<div id="images"></div>
</body>
JavaScript
$(document).ready(function() {
$("#search").on('click', function(){
$.ajax({
url: '/search.php',
type: 'POST',
data: $("#searchbox").serialize(),
success: function(data) {
$('#images').append(data);
},
error: function() {
alert('failure');
}
});
});
});
PHP
<?php
if(isset($_POST['search'])) {
$searchterm = $_POST['search'];
$image = "images/".$searchterm.".jpeg";
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';
}
else {
echo 'Error: image not found';
}
PS. For the moment, I'm ignoring any sort of error checking, I'm just trying to get it working and assuming the input is all valid
SUGGESTIONS:
Try this link:
Image Data URIs with PHP
<?php
if(isset($_POST['search'])) {
$searchterm = $_POST['search'];
$image = "images/".$searchterm."jpeg";
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
echo '<img src="', $src, '">';
...
Debug the actual HTTP traffic between your jQuery/Browser and your PHP/back-end server. You can use a tool like Telerek Fiddler or Firebug, among many others.
'Hope that helps!
Use file_get_contents it will display the image on browser.
$image = "images/".$searchterm.".jpeg";
echo '<img src="data:image/jpeg;base64,'.base64_encode(file_get_contents($image)).'">';
Please change the url property in the object, used in your .ajax() method call. The path to your search.php is incorrect.
$.ajax({
url: '/search.php',
goes to:
$.ajax({
url: './search.php',
I'm attempting to post some data back to the same page through ajax. In the example below the $name variable is not being updated in my page once the button is clicked. However, if I look at the console log of the response from ajax (using firebug) it shows the correct html, with the name inserted (i.e. <div>Matthew</div>) - the page just isn't being updated with this response. Any ideas for how to fix this would be greatly appreciated.
The code I have is:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<?php
$name = "A name";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name = "No name!";
}
else{
$name = $_POST["name"];
}
}
?>
<script>
$(document).ready(function(){
$("button").click(function(){
var mydata = {name: "Matthew"};
$.ajax({
type: 'POST',
data: mydata,
success: function(data){
console.log(data);
}
});
});
});
</script>
<button>Send an HTTP POST request to a page and get the result back</button>
<div id="name">
<?php echo $name;?>
</div>
</body>
</html>
It is because <?php echo $name;?> does not run again when doing the ajax call. You have to replace the content of the div in the success function like this:
success: function(data){
$("div").html(data);
}
I am currently trying to make a site where I put in info in on my html side, it send the info to the php file and grabs info from another site depending on what you put in on the html side.
To make this more clear this is how it works:
You put in your username in the html site(where the javascript code
is).
Then it sends your username to the php file.
The php file gets the information, puts it in a link and request it.
It grabs information from this request (highscores page).
This is where it stops.
I don't know how to return the information to my javascript file.
This is my code:
html/javascript page:
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<script>
function test() {
var username = "Exzib";
window.location.href = "grabinfo.php?username=" + username;
}
</script>
</body>
</html>
This is my php file: (grabinfo.php)
<html>
<head>
</head>
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
echo $formatxp;
}
?>
<body>
</body>
</html>
So how do I proceed to send the $formatxp to my javascript?
Thanks
So what you do is execute:
window.location.href = "grabinfo.php?username=" + username;
This causes the browser to navigate to grabinfo.php and display the information that you want. Except that you don't want the information to be displayed, you want to retrieve it into a JavaScript variable, right?
To do so, don't set window.location.href. Instead call your script using AJAX. You'll find plenty of tutorials on AJAX out there. This will allow you to capture the output of your PHP script.
Change the following line
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
to
$formatxp = str_replace(array('$',',','.',' '),'',$xp);
And to pass the variable to Javascript you can do something like this.
<script type="text/javascript">
var $formatxp = '<?php echo $formatxp; ?>';
</script>
Write a script tag and set the variable equal to your PHP variable.
<script>
var thing = '<? echo $formatxp; ?>';
</script>
This is going to be easy as you already include jQuery. (Using ajax)
Look
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<label>Type your username:<input id="username" type="text"></label>
<input id="submit-button" type="button" value="Get my highscores!">
<p id="response"></p>
<script>
//When user clicks "submit-button" button
$("#submit-button").on('click', function() {
var username = $("#username").val();
//We request our php with the username
$.get("grabinfo.php?username=" + username, function(xpValue) {
//When we receive the response from php then we add it to a "p" tag
$("#response").text("LOL your xp is: "+xpValue+". NOOOOOOOB!!");
});
});
</script>
</body>
</html>
And that's it!
More info at http://api.jquery.com/on/
And http://api.jquery.com/get/
http://api.jquery.com/text/
http://api.jquery.com/val
And well the whole jQuery API documentation http://api.jquery.com
EDIT:
OH. You have to change grabinfo.php. It should only have this:
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
if(empty($formatxp)) {
echo "ERROR: Invalid could not find xp with username {$username}";
}
else {
echo $formatxp;
}
}
else {
echo "ERROR: Invalid arguments";
}