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',
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'm having trouble with an AJAX POST to PHP call.
JS in an PHP file (tableOutput.php)
var changedArr=[];
var undoRedoArr=[];
//For editing data, http://tabulator.info/docs/3.3
$("#tabulator").tabulator({
cellEdited:function(cell){
//this is called whenever a cell's value is edited.
var value = cell.getValue();
var theID = cell.getRow().getIndex();
var ip=cell.getRow().getData();
var field = cell.getField();
var x=Object.values(ip);
console.log(ip);
changedArr.push(x);
},
});
//called when I hit a button
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(){
alert("SAVED!");
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
</script>
<?php
include "getInfo.php";
?>
PHP code in a different file (getInfo.php)
<?php
if(!empty($_POST['ipString'])){
echo '<script language="javascript">';
echo 'alert("Post")';
echo '</script>';
}
if(!empty($_REQUEST['ipString'])){
echo '<script language="javascript">';
echo 'alert("Request")';
echo '</script>';
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
</html>
Earlier in the files, I have a GET command that works.
HTML in tableOutput.php
<div class=form>
<form onsubmit="fillTable()" >
<input type="submit" name="deny" value="Denied" />
<input type="submit" name="permit" value="Permitted" />
</form>
</div>
getInfo.php
$test="'CREATE'";
if( isset( $_GET['deny'] )){
$test="'DENY'";
}
if( isset( $_GET['permit'] )){
$test="'CREATE'";
}
Tried on Fedora and Windows. Code is on a server. Browser: Firefox
The Ajax posts successfully. I get an alert box saving "SAVED!", but nothing echos on the page. If I use window.location.href instead, then the getInfo.php echos to the page. The problem is that I get redirected to the getInfo.php page, which I don't want.
How do I get the Ajax to post to the getInfo.php file? Why is it not working?
It looks like you are trying to mix two different mechanisms here (AJAX and post-back). When you use AJAX, simply echo-ing output will not insert that content into the DOM (like it does when using a full post-back). Your echo statement puts data into the output stream that is then consumed by your success function. And it will stay there unless you programmatically (using javascript/jQuery) insert it into the DOM. You can manually insert that into the DOM. There are many ways of doing that. The key is looking at your response object. This is one possibility:
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(response){
alert("SAVED!");
//add the script element to the DOM body
$(response).appendTo('body');
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
It is important to understand that when including a php file (like getInfo.php), the output is written on the client side and cannot be accessed by php anymore.
What you want is to request the getInfo.php, get its response the write it on the client side.
Client:
<script>
function saveChanges(){
$.ajax({
url: "getInfo.php/",
type:'POST',
data: {'ipString':changedArr},
success: function(textResponse /* you MUST use this parameter*/){
alert("SAVED!");
// textResponse is the string the server sends. do whatever you want with this
document.getELementById("out").innerHTML = textResponse;
},
error: function(XMLHttpRequest, textStatus, error){
alert("AJAX error: " + textStatus + "; " + error);
}
})
console.log(changedArr);
}
</script>
<div id="out"></div>
At the server side, it is important you do not include any <head> or <body> tags, otherwise you will have a new document inside your <div id="out"></div>! You should write just pure text, or something that can be put inside a div element, like a table.
Server: getInfo.php
<?php
if (isset($_POST['ipString'])) {
echo "A request has been made";
}
?>
or write pure html closing the php tags (a nice trick):
<?php
if (isset($_POST['ipString'])) {
?>
A request has been made
<?php
}
?>
If your getInfo.php file needs to have its <head> and <body> tags, you must exit() the script so the rest of the file will not be sent.
<?php
if (isset($_POST['ipString'])) {
echo "A request has been made";
exit(); // exit here so ajax doesn't get the rest of the file
}
?>
<html>
<head></head>
<body></body>
</html>
Finally, if you want to be flexible and have your client do stuff based on what the server sends, you should try JSON which converts objects to strings and vice versa.
The problem was not with the code posted.
At the beginning of getInfo.php, I forgot to add "php"
It was:
<?
instead of:
<?php
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>
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