Got a php code:
<?php
$date = date("Y/m/d");
echo json_encode($date);
?>
It exports a json file. But then, I wanna catch it by JS:
$.get("/your/url").done(function(data){
});
But my problem is - how can I know where the JSON file was saved (if it even was saved)?
Does the echo json_encode($date) exports a json file to somewhere? Or echo has nothing to do with that?
Thanks for any further help.
Edit: Anybody can help me?
Your are doing correctly in php side but in jquery side i dont know if $.get().done() works or not
i have used it by this way and its working fine
$.getJSON( "url/yoururl", function( data ) {
console.log(data);
});
You can also use
$.ajax({
method:GET,
url:'url/yoururl',
success:function(data){
console.log(data);
}
});
console.log(data) will return date which you have exported from php
I don't jQuery, but the concept is identical.
001-tmp.php
<?php
$date = date("Y/m/d");
echo json_encode($date);
?>
001-tmp.html
<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id){return document.getElementById(id)}
function ajaxGet(url, onLoad, onError)
{
var ajax = new XMLHttpRequest();
ajax.onload = function(){onLoad(this);}
ajax.onerror = function(){console.log("ajax request failed to: "+url);onError(this);}
ajax.open("GET",url,true);
ajax.send();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('goBtn').addEventListener('click', onBtnClick, false);
}
function onBtnClick(evt)
{
ajaxGet('001-tmp.php', onLoad, onError);
function onLoad(ajax)
{
var rawData = ajax.responseText;
var parsedData = JSON.parse(rawData);
byId('ajaxTarget').innerHTML = parsedData;
}
function onError(ajax)
{
// todo: add something useful here
}
}
</script>
<style>
</style>
</head>
<body>
<button id='goBtn'>Get data from PHP</button>
<div id='ajaxTarget'></div>
</body>
</html>
Related
I have a file named sample.php, in which I have some JS code, and some PHP code. This is some sort of sample snippet of the code I have :
<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<head>
<script type="text/javascript">
var ThunkableWebviewerExtension = {
receiveMessage: function(fxn) {
var callbackFunction = function(event) {
if (typeof fxn === 'function') {
fxn(event.data)
}
};
document.addEventListener('message', callbackFunction, false);
window.addEventListener('message', callbackFunction, false);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var value;
ThunkableWebviewerExtension.receiveMessage(function(message) {
value = message;
});
//sending the value with ajax
$.ajax({
url : "./sample.php", //same file
method : "GET",
data: {"name": value},
success : (res) => {
console.log(value);
},
error : (res) => {
console.log(res);
}
})
</script>
<?php
echo $_GET['name'];
?>
</body>
</html>
The problem is the PHP code doesn't print anything - Are there any error/bug I need to fix? Or is there a better method for accessing a JS variable in PHP?
Thanks! :)
Here's how you can access PHP code within in a <script> (without using AJAX):
<?php
echo"<script>";
include ('javascriptStuff.js');
echo'let x = '.json_encode($phpVariable).';';
echo"</script>";
?>
I have an image URL in javascript extracted from a canvas in html and i want to create an image from that URL and upload it to my storage files in server.
i can send the Url in a ajax post request to my sendImagetoController function in controller or if there is a method from javascript to do that.My routes are all defined and tested.Please Help
my display.blade.php .
<html>
<head>
<title>HeatMap Display</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src='http://www.patrick-wied.at/static/heatmapjs/assets/js/heatmap.min.js'></script>
<script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script>
<script src="{{ asset('js/jquery.js')}}" type="text/javascript"></script>
<script src="{{ asset('js/app.js') }}" defer></script>
<script src="{{ asset('js/heatmap.js' )}}" type="text/javascript"></script>
<script>
var coordinatesarray = #json($coordinates);
var finalcoordinatesarr=[];
var count=0;
var mapId={{$targetHeatMap->id}};
var mintime=10000000;
var maxtime=0;
var imgUrl="";
coordinatesarray.forEach(element => {
var cor={
'x' : coordinatesarray[count]['x'],
'y' : coordinatesarray[count]['y'],
'value' : coordinatesarray[count]['time_spent']
};
if(mintime>coordinatesarray[count]['time_spent']){
mintime=coordinatesarray[count]['time_spent'];}
if(maxtime<coordinatesarray[count]['time_spent'])
maxtime=coordinatesarray[count]['time_spent'];
finalcoordinatesarr.push(cor);
count++;
});
console.log(finalcoordinatesarr);
function load(){
renderCanvas();
}
function renderCanvas(){
var heatmapInstance = h337.create({
container: document.getElementById('heatMap')
});
var testData = {
min: mintime,
max: maxtime,
data:finalcoordinatesarr
};
heatmapInstance.setData(testData);
imgUrl = (document.getElementById("heatMap").childNodes[0]).toDataURL();
document.getElementById("heatMapPic").src=imgUrl;
}
sendImageToController();
function sendImageToController(){
formdata = new FormData();
if($('#heatMapPic').prop('files').length>0){
file = $('#heatMapPic').prop('files');
formdata.append("heatMapPic",file);
}
formdata.append('tagetHeatMap',$('#targetHeatMap').val());
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: "{{route('HeatMap.moveToStorage')}}",
data: formdata,
type:'post',
// traditional:true,
success:function(response){
console.log("correct");
console.log(response);
},
error:function(e){
console.log("errrooooor");
console.log(e);
},
});
console.log("hi");
}
</script>
</head>
<body onload="load()">
<form id="form" enctype="multipart/form-data">
#csrf
<input type="file" id="heatMapPic" name="heatMapPic" src=""/>
<input type="text" id="targetHeatMap" value="{{$targetHeatMap}}"/>
</form>
<div id="heatMap" style="height:740px"></div>
<a-scene>
{{-- <a-sky radius=10 opacity="0.8" src="{{asset('uploads/heat_map_images/'.$targetHeatMap->heatmap_image)}}"></a-sky> --}}
{{-- <a-sky radius=10 src="{{asset('uploads/'.$imageName)}}"></a-sky> --}}
</a-scene>
</body>
</html>
my Controller method
public function moveToStorage(Request $request){
return 'hello';
}
I use this method in PHP, the fact that the file itself comes to php through the variable $_FILES() and is not visible in the main query.
<?php
putenv("upload_tmp_dir=/var/www/site.com/public_html/upload/");
$uploadDir = getenv("upload_tmp_dir");
$uploadFile = $uploadDir . basename($_FILES['userfile']['name']);
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile);
?>
Then you can open the file in the path in the $uploadFile variable
If you have url which is publicly accessible then you can use it like this
public function moveToStorage(Request $request){
$data = $request->all();
$url = $data['file_url'] ; //file url that you have in javascript
$contents = file_get_contents($url);
$name = substr($url, strrpos($url, '/') + 1);
Storage::put($name, $contents);
return 'hello';
}
OR if your file is posted as base64 then try this
public function moveToStorage(Request $request){
$data = $request->all();
$file = $data['file_url']; //base64 encoded image
$file = substr($file, strpos($file, ",")+1);
$imgeData = base64_decode($file);
$contents = file_get_contents($imgeData);
Storage::put("test.png", $contents);
return 'hello';
}
Looking at your code, it looks like you're trying to send the image before it is actually rendered. You need to move sendImageToController() inside your load function, after renderCanvas().
Also, no need for all the formData stuff. Just send the result of .toDataURL() as-is to the server, then use base64_decode() to turn it back into an image.
Here are the relevant changes:
function load() {
renderCanvas();
sendImageToController(); // send to server AFTER rendering
}
var imgUrl;
function renderCanvas() {
// ...
imgUrl = (document.getElementById("heatMap").childNodes[0]).toDataURL();
// ...
}
Shorter AJAX code:
function sendImageToController() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
$.post("{{route('HeatMap.moveToStorage')}}", {
heatmap: imgUrl // global var set in renderCanvas()!!
})
.done(function(response) {
console.log("correct");
console.log(response);
})
.fail(function(e) {
console.log("errrooooor");
console.log(e);
});
}
On the server, grab the heatmap parameter.
public function moveToStorage(Request $request){
$heatmap = $request->input('heatmap');
$base64 = explode(",", $heatmap)[1];
$binary = base64_decode($base64);
// store $binary data in PNG file
return 'image saved successfully';
}
Long-time user, first-time asker. I've learned so much from the community and I love this site.
So here is what I'm shooting for. I want to have a web interface that runs ping commands on the backend. I ideally want a website that has a text input that allows you to enter an IP address or domain, a button that runs the command and a python script that runs from PHP to actually run the ping command. The tricky part for was to get the output to print to the website live as it is outputted on the command line. I want to do it this way as a way to future-proof the concept and eventually use different iperf parameters.
I built a little PHP page that "technically" gets the job done but I can't figure out how to only call the PHP script when the button is clicked. Since it's a PHP page, it runs whenever the page is loaded. So after some research, I figure ajax jquery is what I'm looking for. I've spent about 2 days trying different things that get me really close but it seems that I'm dancing around my solution.
From what I've learned about ajax, I essentially need a button that runs an ajax function that is linked to my working php script. I can get it to run the script but I can't get it to update the page content in a live/continuous manner. Only when the command is finished running.
Here is my php page that does what it needs to do but does it everytime the page is loaded/reloaded. Not ideal. I want the script to only run when the button is pressed.
liveping.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="liveping.php" id="ping" method="post" name="ping">
Domain/IP Address: <input name="domain" type="text"> <input name="ping" type="submit" value="Ping">
</form><?php
if (isset($_POST['ping'])) {
function liveExecuteCommand($cmd)
{
while (# ob_end_flush()); // end all output buffers if any
$proc = popen("$cmd 2>&1", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "<pre>$live_output</pre>";
# flush();
}
pclose($proc);
}
}
$domain = $_POST['domain'];
$pingCmd = "python /var/www/html/ping.py ".$domain;
if (isset($_POST['ping'])) {
liveExecuteCommand($pingCmd);
}
?>
</body>
</html>
ping.py:
#!/usr/bin/python
import cgi
import os
import sys
ping = "ping -c 5 -W 2 "+sys.argv[1]
os.system(ping)
Some things I've tried:
<html>
<head>
<script>
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = setInterval(function() {
if (ajax.readyState == 4) {
document.getElementById('content').innerHTML = ajax.responseText;
}
},100);
function updateText() {
ajax.open('GET', 'ajax.php');
ajax.send();
}
</script>
</head>
<body>
<button onclick="updateText()">Click Me</button>
<div id="content">Nothing here yet.</div>
</body>
</html>
OR
<!DOCTYPE html>
<html>
<body>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('ajax.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>
</head>
<div id="load_tweets"> </div>
</body>
</html>
WITH ajax.php
<?php
while (# ob_end_flush()); // end all output buffers if any
$proc = popen("ping -c 5 -W 2 google.com", 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "<pre>$live_output</pre>";
# flush();
}
pclose($proc);
?>
Thanks for any help!
You do not need python for showing ping results. Just two PHP files will be enough.
index.php will have the AJAX functionalities along with the form.
ajax.php will have the code to ping specified domain address.
I afraid that using jQuery you might not able to catch the live feed. Because it doesn't have any onreadystatechange. So, you might need to use vanilla JavaScript in this case. Here is a working demonstration:
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Ping AJAX</title>
</head>
<body>
<div>
Domain/IP Address: <input id="domain" type="text">
<input id="ping" type="button" value="Ping">
</div>
<div id="result"></div>
<script>
function updateText(domain) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 3) {
var old_value = document.getElementById("result").innerHTML;
document.getElementById("result").innerHTML = this.responseText;
}
};
var url = 'ajax.php?domain='+domain;
ajax.open('GET', url,true);
ajax.send();
}
document.getElementById("ping").onclick = function(){
domain = document.getElementById("domain").value;
updateText(domain);
}
</script>
</body>
</html>
ajax.php:
<?php
if (isset($_GET['domain'])) {
function liveExecuteCommand($cmd)
{
while (# ob_end_flush()); // end all output buffers if any
$proc = popen($cmd, 'r');
$live_output = "";
$complete_output = "";
while (!feof($proc))
{
$live_output = fread($proc, 4096);
$complete_output = $complete_output . $live_output;
echo "<pre>$live_output</pre>";
# flush();
}
pclose($proc);
}
$domain = $_GET['domain'];
$pingCmd = "ping ".$domain;
liveExecuteCommand($pingCmd);
}
else{
echo "No post request";
}
?>
Output:
Declaimer:
The ping command is changed as I am currently using Windows operating system. Update it according to your operating system.
As a first time questioner, you have described the problem neatly and also showed your efforts to solve the problem. I really appreciate it.
ajax.readyState == 4
essentially means, script on the other side has finished ... 3 is partial.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
You just have to take all ajax script into the function
example:
function updateText() {
$.ajax({
type: 'GET', // can be POST, too
url: "ajax.php",
crossDomain: true,
data: {
firstvar: firstvar,
secondvar: secondvar
},
cache: false,
success: function(data) {
if($.trim(data) == "false") {
alert("Fail to recived data");
}
else {
// Success getting data
// Do some jobs
}
}
});
}
If you want to cancel submit to not refesh, U can use
return false; // At the end of the function above
Hope it helps.
First thing I am new to javascript.
What I am trying to do is to get data from a URL in json and save it in java script variable.
What I have already done:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
This shows me output : 1
and what I want is to get data from URL like:
var json ='url';
obj = JSON.parse(json);
alert(obj.count);
and for the clearance I am using this URL to get JSON data and i just need to print fare from the data.
any help in this matter would be highly appreciated !!
I have done this in php like this way, but I need it to do this in javascript.
$jsonData = file_get_contents("url");
$json = json_decode($jsonData,true);
echo $json['fare'];
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
console.log(data)
});
Try this ways to read ur URL
Try this way, convert the url to an array then
var json = 'data url in array',
obj = JSON.stringify(json);
alert(obj.count);
Use Ajax call for fetching data from external sources.
On clicking it will fetch data from the url.
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://daewoocab-test.herokuapp.com/api/v1/rates?token=6ab676ddd7bf00101408ea3a27fdbb8ad22e9dcdf2faafdcd2ef0efc1509d463&pickup_area=Street%201%2CF-8%2CIslamabad%2CIslamabad%20Capital%20Territory%2CPakistan&drop_area=padhrarazadari.com%2C%20kallar%20kahar%20road%2C%20padhrar%2C%20punjab%2C%20pakistan&distance=169", function(result){
console.log(result);
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<button onclick="showHint()">abcd</button>
<script>
function showHint() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(JSON.parse(xhttp.response));
}
};
xhttp.open("GET", "http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback", true);
xhttp.send();
}
</script>
</body>
</html>
Temporary Solution:
Here is my working fiddle
If you get 'Access-Control-Allow-Origin' header is present on the requested resource. error, add CORS extension to your browser and enable it.
hope this helps :)
This code is working on other test environment but not on mine.
Do you know why?
I am using Amazon EC2 and Cotendo CDN.
The result I am getting is a blank page.
Thanks in advance!
<html>
<head>
<title>Geo Test</title>
<script type='text/javascript' src='http://www.101greatgoals.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script>
$(document).ready( function() {
$.getJSON( "http://smart-ip.net/geoip-json?callback=?",
function(data){
console.log(data);
var c = data.countryCode;
if(c=="US" || c=="US" ){
document.getElementById('ddd').innerHTML = 'US'; } else {
document.getElementById('ddd').innerHTML = 'Not US';}
/*
this service needs ip
var ip = data.host;
alert(ip);
$.getJSON( "http://freegeoip.net/json/"+ip,
function(data){
console.log(data);
}
);*/
}
);
});?
</script>
</head>
<body>
<div id="ddd"></div>
</body>
</html>
Change this line:
$(document).ready( function() {
to that:
jQuery(document).ready( function($) {
It's necessary, because inside http://www.101greatgoals.com/wp-includes/js/jquery/jquery.js?ver=1.7.1 you've already got a call of jQuery.noConflict(); , so jQuery is not accessible by using the $
...and also remove the ? (see Pointy's comment above)