I had a variable in my php page which is an URL printed on that page, I had another html page where I needs this URL value from that php page and it should be assigned to the button in html page.
How can it be performed?
php page content:
if ($output== true) {
//Output results as URL
print_r($resulta);
}
html page content:
<p align="center">
<input type="button" name="res1" value="result">
You should use Ajax.
When you need information to be filled in HTML page the only easy way is Ajax.
I suggest you to use jQuery for simpler requests.
More info about making get request with jQuery: https://api.jquery.com/jquery.get/
Example:
$(function() {
$.get('request.php', {}, function(response) {
if (response.url) {
alert('No information from server!');
return;
}
$('button.mybutton').onclick(function() {
window.location.href = response.url;
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybutton">Click</button>
And in your PHP something like this:
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$response = json_encode(array( 'url' => $url ));
die($response);
Header "Access-Control-Allow-Origin" is important when you do an Ajax request from different domains. you can see more usages of it in google: Access-Control-Allow-Origin
Use $_GET method to pass variables between PHP pages.
In your PHP page,
<?php
$value = "Some value";
header("location:nextPage.php?variable=$value");
exit();
?>
In the nextPage.php
<?php
$received = $_GET['variable'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<<button type="button"><?php echo $received; ?></button>
</body>
</html>
If the next page is not a PHP file, here is a solution,
// THIS WORKS FOR MULTIPLE VALUES, BUT IF YOU DO NOT SEND ANY VALUES, IT WILL SHOW ERROR OF "UNDEFINED". BUT THAT CAN ALSO BE FIXED.
// EXAMPLE : http://yourdomain.com?tag1=100&tag2=200&tag3=300
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
var url,url_contents,received_values,passed_values;
url = document.URL;
url_contents = url.split("?");
received_values = url_contents[1];
received_values = received_values.split("&");
for(var i=0;i<received_values.length;i++)
{
var value_array = received_values[i].split("=");
alert(value_array[0]+"="+value_array[1]);
}
</script>
</head>
<body>
</body>
</html>
Related
I have the below piece of code in my test.php file. The code mainly has a variable defined in PHP, and I want to send it to a JavaScript function so it could POST it. Here's the code :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!'; //the PHP variable (currently has a sample value, but will be string only)
//JS starts
echo <<<JS001
<script type="text/javascript">
var msg = {$myValue}; //trying to set it to a JS var, so I could send it to below function.
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');
}
}
};
ThunkableWebviewerExtension.postMessage(msg);
console.log(msg);
alert('Message Sent');
</script>
JS001;
} else {
echo 'Incorrect Value';
}
?>
</body>
</html>
But when I run this code, I get this error on console : Uncaught SyntaxError: Unexpected identifier. What should I do if I want to send just a simple string value to the JS code? What's wrong currently?
Any help is appreciated! Thanks!
You can do:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!';
?>
<script>
var msg = "<?php echo $myValue; ?>"; //trying to set it to a JS var, so I could send it to below
//Your remaining js script here ...
</script>
<?php } else {
//your else condition
}
?>
</body>
</html>
Try this
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
...
if($row) {
$myValue = 'Hi there!'
?>
<script>
var msg = "<?php $myValue; ?>";
</script>
<?php } else {
echo 'Incorrect Value';
}
?>
</body>
</html>
Simplifying your code (which you should always do when debugging!) you have this:
$myValue = 'Hi there!';
echo <<<JS001
<script type="text/javascript">
var msg = {$myValue};
</script>
JS001;
If you look at the HTML that's returned to the browser, you'll see that it looks like this:
<script type="text/javascript">
var msg = Hi there!;
</script>
The browser has no idea that "Hi there!" was supposed to be a string, so it tries to execute it as code.
What you wanted the output to be was this:
<script type="text/javascript">
var msg = 'Hi there!';
</script>
So we need to add those quote marks into the PHP:
$myValue = 'Hi there!';
echo <<<JS001
<script type="text/javascript">
var msg = '{$myValue}';
</script>
JS001;
As a more general solution, you can abuse the fact that JSON strings are valid JS values, and use json_encode in the PHP:
$myValue = 'Hi there!';
$myValueJson = json_encode($myValue);
echo <<<JS001
<script type="text/javascript">
var msg = {$myValueJson};
</script>
JS001;
This makes no difference in this case, but is useful for passing other types of value - arrays, null, etc
For a better code management, you should probably separate HTML, PHP, and JS code in different files.
Imagine something like this :
controller.php
$displayName="David";
include 'vue.php';
vue.php
<html>
...
<body>
<div id="php-data" data-displayName="<?php echo $displayName ?>"></div>
</body>
</html>
script.js
<script>
var msg = document.getElementById('php-data').dataset.displayName // "David";
</script>
I've put together this short little code that should randomly pick a url from "url.txt" and then redirect it through a javascript redirect. For whatever reason I can't get it to work. I'm aware of how to get it to work with other forms of redirection including meta refresh and php header, however I would like to know how to do with with javascript redirection.
<?php
$loadlist = explode("\n", file_get_contents('urls.txt'));
$rand = rand(0,count($loadlist)-1);
$picked = $loadlist[$rand];
?>
<html>
<head>
<script type='text/javascript'>
window.location.href = '<?php echo $picked ?>'
</script>
</head>
</html>
<?php
$loadlist = explode("\n", file_get_contents('urls.txt'));
$rand = rand(0,count($loadlist)-1);
$picked = $loadlist[$rand];
?>
<html>
<head>
<script type='text/javascript'>
window.location.replace("<?php echo $picked ?>");
</script>
</head>
</html>
Try this
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 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";
}
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