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.
Related
I would like to refresh a div every second with a PHP variable using Jquery.
I have a simple PHP file with a variable date:
<?php
$date = date('d/m/Y H:i:s');
?>
I have a HTML file with the following code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
function request() {
$.ajax({
url: "date.php",
dataType: "text",
cache: false,
success: function(data) {
var json = $.parseJSON(data);
$('#result').html(json.date);
}
});
}
setTimeout(request, 1000);
});
</script>
</head>
<body>
<div id="result">
</div>
</body>
</html>
But the result is a blank page. I can not make it work. I would like your help.
I would like to refresh every second a PHP variable using Jquery.
You need to print date variable:
<?php
$date = date('d/m/Y H:i:s');
echo $date;
?>
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',
Let's say I'm currently browsing mypage.html, which in its header has a link to the following js file:
<script language="JavaScript" type="text/javascript" src="jsfile.js"></script>
In jsfile.js, there's a function keyup() that is executed when the user types something into #searchbar, whose value is then stored in search = $(#searchbar).val();
I then pass this value on to search.php as follows:
$.post( "search.php", { searchval: search }, function(sentdata){
console.log(sentdata);
});
where the content of search.php reads:
<?php
if(isset($_POST[searchval])){
$search = $_POST[searchval];
echo "input value is $search";
echo "<script type='text/javascript'> alert('its working') </script> ";
}
?>
However, instead of an alert pop up (or anything else that would normally be executed in JS), the second echo simply prints " alert('its working') " into the console.
How can I modify search.php to allow it to inject actual js into myfile.html? Note that I've also tried wrapping the js code in tag.
Related question: why is it that when I omit console.log(sentdata), search.php does no longer echo anything into the console?
How I can modify search.php to allow it to inject actual js in myfile.html?
First of all, you need to modify your javascript file:
$.post( "search.php", { searchval: search }, function(sentdata){
eval(sentdata);
});
And no need for javascript tags, just echo a valid Javascript code:
if(isset($_POST[searchval])){
echo "alert('its working');";
}
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/eval
you can do this
$.post( "search.php", { searchval: search }, function(data){
alert(data); // this will alert the data which will print on search.php
});
and in the php file echo the data you want to print like
if(isset($_POST[searchval])){
echo 'its working. i got'.$_POST[searchval];
}
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);
}
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