Javascript call php function and receives back results - javascript

This postprovides sample code using obtaining a server file list as an example. Here is the code I have used:
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>How to create form using jQuery UI</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/pepper-grinder/jquery-ui.css" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.get('getfilename.php', { dir : '/ajax1/' }, function(data) {
// you should now have a json encoded PHP array
$.each(data, function(key, val) {
alert('index ' + key + ' points to file ' + val);
});
}, 'json');
alert ("ok");
});
</script>
</head>
<body>
<h1>Get file names... </h1>
</body>
</html>
getfilename.php
$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'';
$Counter++;
}
}
echo json_encode($filesArray);
My problem is that the javascript alert alert('index ' + key + ' points to file ' + val); fails to display anything on the page. The script is working because I get a response in the Firebug console log.
ajax.jsajax.phpindex.html["ajax.js","ajax.php","index.html"]
What I need to change on the script to return this information to the html page so that I can use the JSON for further processing ?
Thanks.

With your debug you broke the JSON output in PHP. So, remove:
echo $filesArray[$Counter].'';
Also, before any output, you should add JSON header:
header('Content-Type: application/json');
At the end, your PHP file should look like this:
$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;
$filesArray = array();
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[] = $file;
}
}
header('Content-Type: application/json');
echo json_encode($filesArray);

Related

Calling a php variable in JS does not work

I’m trying to make a user input by reading the contents of my server directory with php. So the user can select a file, in my case a CSV file which gets saved into a variable and then gets processed further down in my JavaScript code that should make a chart from it. All it does now is output the path string of the selected file. I tried using the json_encode function but it still doesn’t seem to work.
<?php
$dir = '/var/www/html/';
$graphen = '';
if (!isset($_POST['submit'])) {
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
if ($files) {
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
foreach ($files as $file) {
echo '<input type="checkbox" name="files[]" value="' . $file . '" /> ' .
$file . '<br />';
}
echo '<input type="submit" name="submit" value="submit" />' .
'</form>';
} else {
exit('No files found.');
}
} else {
if (isset($_POST['files'])) {
foreach ($_POST['files'] as $value) {
$graphen .= $dir . $value . '<br />';
}
} else {
exit('No files selected');
}
}
echo $graphen;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="highcharts.js"></script>
<script src="data.js"></script>
<script src="exporting.js"></script>
<script src="export-data.js"></script>
<script src="accessibility.js"></script>
<script src="jquery-3.5.1.min.js"></script>
</head>
<body>
<div id="container1"></div>
<script type="text/javascript">
var fileName = <?php echo json_encode($graphen); ?>; //doesn't work
$.ajax({
type: "GET",
url: fileName,
success: function (data) {
drawChart(data)
}
});
function drawChart(raw_data) {
//my code to draw chart is here and working
}
If you assign a String to a variable in JavaScript, use " or ':
var x = "Hello";
Your current code results in
var fileName = <?php echo json_encode($graphen); ?>; => var fileName = variable;
Add quotes and it should work:
var fileName = '<?php echo json_encode($graphen); ?>'; => var fileName = 'variable';

Issues appending strings in PHP

I'm using Codeigniter and had written a method to create css/js links, concatenate them and then pass them to my view. It was working before, until I decided to create a clean copy of the project with the latest CI version and it's not working now.
The part of the method that concatenates the data is the following:
foreach ($header_css as $item) {
$str .= '<link rel="stylesheet" href="'. base_url() . $item . '" type="text/css" />';
}
There's a similar one for the JS files. When printing the previous piece of code I'm getting an empty string, so I decided to use htmlentities:
foreach ($header_css as $item) {
$str .= htmlentities('<link rel="stylesheet" href="'. base_url() . $item . '" type="text/css" />');
}
and it works... partially. I mean, if I print at this point the string with the links are there but now when I pass the string to the view the data is being printed on screen instead of being added to the head. So this is my view:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo (isset($title)) ? $title : ''; ?></title>
<meta name="description" content="Test">
<meta name="author" content="Test">
<?php
# load assets
echo (isset($assets)) ? $assets : '';
?>
<script>var ajax_home = "<?php echo base_url(); ?>ajax/";</script>
</head>
<body>
The part that echoes the assets is printing the content of the variable on screen instead of parsing the assets as <script>...</script> or <link rel="stylesheet" ... />
Any indication on why this is happening?
Thanks.
The part of the method that concatenates the data is the following:
foreach ($header_css as $item) {
$str .= '<link rel="stylesheet" href="'. base_url() . $item . '" type="text/css" />';
}
There's a similar one for the JS files. When printing the previous piece of code I'm getting an empty string, so I decided to use
htmlentities: Below Code is NOT FOR JavaScript, it's for Style sheet
foreach ($header_css as $item) {
$str .= htmlentities('<link rel="stylesheet" href="'. base_url() . $item . '" type="text/css" />');
}
it should be like,
foreach ($header_js as $item) {
$str .= "<script type='text/javascript' src='". base_url() . $item . "'/>";
}
& Your Views has (Ahem!):
<?php
# load assets
echo (isset($assets)) ? $assets : '';
?>
So, My Question is:
Where is $str variable and why you are not using inside view instead of $assets it should be echo (isset($str)) ? $str : '';
I am assuming that you are using your function inside your controller as method & storing all js & css file build in that
variable. So.. are you returning that $str variable.. ?
Well, Here is some example for you, Hope you can solve your problem :)
/**
* Build Css or Script link
* #param array $assets [description]
* #param string $type [description]
* #return [type] [description]
*/
function build_assets($assets = array(), $type = 'css')
{
$str = '';
if (!empty($assets) && is_array($assets) && $type == 'css') {
foreach ($assets as $key => $file) {
$str .= "<link type='text/css' rel='stylesheet' href='" . base_url($file) . ".css' />";
}
} elseif (!empty($assets) && is_array($assets) && $type == 'javascript') {
foreach ($assets as $key => $file) {
$str .= "<script type='text/javascript' src='" . base_url($file) . ".js'></script>";
}
}
return $str;
}
/**
* Testing the method
* #return [type] [description]
*/
function index()
{
$data = [];
// get all style sheets
$style = $this->build_assets(['style', 'page', 'form']);
// get all js files
$script = $this->build_assets(['style', 'page', 'form'], 'javascript');
// assign in 'assets' variable
$data['assets'] = $style . $script;
// send to template/view
$this->load->view('ViewTemplate', $data);
}
& Views Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CodeIgniter</title>
<!-- CSS and JavaScript -->
<?php echo isset($assets) ? $assets : '' ?>
<!-- End Here -->
</head>
<body>
<di class="welcome">Say Hello to CodeIgniter!!!</di>
</body>
</html>

Passing argument from javascript to PHP function

I am using jqueryfiletree to display a folder of files on the web server. I also have php to parse the csv and display it on the page. How can I pass the selected jqueryfiletree file to the php in the page so it displays the selected csv? Here's what I have so far:
Javscript:
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.easing.js" type="text/javascript"></script>
<script src="jqueryFileTree.js" type="text/javascript"></script>
<link href="jqueryFileTree.css" rel="stylesheet" type="text/css"
media="screen" />
<script type="text/javascript">
$(document).ready( function() {
$('#fileTreeDemo_1').fileTree({ root: '../data/', script:
'connectors/jqueryFileTree.php' }, function(file) {
alert(file);
var file = "<?php echo $file;?>";
});
});
</script>
</head>
<body>
<h1>Select a file to view</h1>
<div class="menuleftcontent">
<div id="fileTreeDemo_1" class="demo"></div>
</div>
</td><td>
PHP
<div class="maincontent">
<?php
$row = 1;
if (($handle = fopen($file, "r")) !== FALSE) {
echo '<table border="1">';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
?>
</div>
I can see two problems so far. Firstly, you do not have a semi-colon to end the line on this line:
var file = "<?php echo $file;?>";
(i've added it).
Also, $file is not defined in your php. And you can not try and define it in javascript (I fear that is what you are trying to do maybe?).
Best options is to make an AJAX request so you can send it to the server side and use it there (which is what you want?). And of course, you can then respond data back to the front end.
THis is a rough idea:
$('#fileTreeDemo_1').fileTree({ root: '../data/', script:
'connectors/jqueryFileTree.php' }, function(file) {
$.post('myphpfile.php', {file:file}, function(response){
// handle response
});
});
and then in php, check for the post with if(isset($_POST['file'])) ,etc etc

PHP `file_get_contents()` output pass to JavaScript and calculate length

I want to pass the output from PHP's file_get_contents() to JavaScript and calculate its length. Everything ok but when passing the variable JavaScript evaluates it as HTML code, so I have to use PHP's json_encode() to keep it "sane" but this way the string length from JavaScript will be different from the one in PHP. Using JS's JSON.parse() doesn't help because again the HTML code gets interpreted. Any idea how can I achieve the same evaluated data length?
EDIT: Basically I need to count all the characters in the page source, that includes tags and special characters. To have the same output computed in JS like the one i get in PHP's strlen($url_data).
EDIT 2: I thought about doing bin2hex() on the $url_data then reconvert in JS and check the length. Would be that reliable?
Here is what I did so far:
<?php
ini_set('display_erros', -1);
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
$url = filter_var($_POST['urlinput'], FILTER_SANITIZE_URL);
$url_data = #file_get_contents($url);
$js_url_data = json_encode($url_data);
//$url_src = htmlspecialchars($url, ENT_IGNORE);
$url_data_len = mb_strlen($url_data);
$url_src = strip_tags($url_data);
echo '<ul id="resultList">';
echo "<li>The following page contains " . $url_data_len . " characters</li>";
echo "<li>Page URL: " . $_POST['urlinput'] . "</li>";
echo "<li>Page title: " . page_title($url_data) . "</li>";
echo "<li>Protocol: " . parse_url($url, PHP_URL_SCHEME) . "</li>";
echo "<li>Host: " . parse_url($url, PHP_URL_HOST) . "</li>";
echo "</ul>";
//var_dump($url_src);
} else {
$error = "URL is not valid!";
}
}
function page_title($str) {
$matches = array();
if (preg_match('/<title>(.*?)<\/title>/i', $str, $matches)) {
return $matches[1];
}
else {
return null;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP file_get_contents()</title>
</head>
<body>
<div class="url_class">
<form id="getsrc" method="post">
<input style="width: 300px;" type="text" name="urlinput" id="urlinput" placeholder="URL">
<input type="submit" name="submit" value="Get SRC">
</form>
</div>
<textarea rows="20" cols="50">
<?php
if (!empty($url_src)) {
echo $url_src;
}
?>
</textarea>
<?php echo '<br><span style="color:red">' . $error . '<span>'; ?>
<?php
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
var url_data = $js_url_data;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript page characters: " + url_data.length);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
}
?>
</body>
</html>
Simply use the value calculated by php, it can be used within EOT block:
...
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
...
$url_data = #file_get_contents($url);
$fileSize = strlen($url_data);
...
}
....
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
...
var textnode = document.createTextNode("JavaScript page characters: " + $fileSize);
...
</script>
EOT;
echo $script;
Since no good answer, I would post my solution to my problem. The only way I could find was to hex-encode $url_data, pass it to JS, decode it and count the characters. For the pack() function I used the one ported in php.js.
...
$js_url_data = bin2hex($url_data);
...
if (!empty($js_url_data)) {
/* This is a good example when one is forced to use inline JS */
$script = <<<EOT
<script>
var url_data = "$js_url_data";
var url_data_len = pack('H*', url_data).length;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript calculation page characters: " + url_data_len);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
...

PHP variable not being passed to AJAX call?

Im trying to get my PHP script called from AJAX (that is in my main php file).
Here's an example of what it is supposed to do: http://jsfiddle.net/xfuddzen/
The HTML source code shows only desk_box DIV being created (which is in my main.php). station_info DIV (being created in the display_station.php) is not there. How can I fix this? thanks in advance
Problem: DIVs from my display_stationinfo.php are not being created by using the AJAX call.
main.php with JQuery/AJAX part:
<div id="map_size" align="center">
<?php
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
?>
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$('.desk_box').each((function(){(this).click(function() {
var id = $(this).attr("data")
$("#station_info_"+id).toggle();
$.ajax({
url: 'station_info.php',
data: { 'id': id },
type: 'POST',
dataType: 'json',
success: function(json) {
$("#station_info_"+id).css({'left':json.x_pos ,'top': json.y_pos}).append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}//end success
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
$html = '';
if($station_result->num_rows > 0){
while($row = $station_result->fetch_object()) {
$id = $row->coordinate_id;
$html .= "<div class='station_info_' id='station_info_$id' style='position:absolute;left:{$row->x_coord}px;top:{$row->y_coord}px;'>Hello the id is:$id</br>Section:{$row->section_name}</br></div>";
}
}
else{
// no results - may want to do something with $html
$html = "no result given";
}
$station_result->free();
$conn->close();
echo $html;
?>
Why dont you filter the coordinate in the query? Like this:
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id = " . $_GET['coordinate_id'];
And in jquery code:
url: 'display_stationinfo.php?coordinate_id=' + id,
Let's start with your database connection, which should be on a separate secure page.
connect.php:
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Obviously, your host will not be 'host'.
Now main.php:
<?php
// only use for PHP on this page for initial page load - target other pages with AJAX
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>This is Where Your Title Goes</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='main.js'></script>
<link rel='stylesheet' type='text/css' href='main.css' />
</head>
<body>
<div id='map_container'>
<div id='map_size'>
</div>
</div>
</body>
</html>
Now for main.js:
//<![CDATA[
$(function(){
var ms = $('#map_size');
$.post('main_init.php', {init:'1'}, function(d){
for(var i in d){
var di = d[i], x = di.x, y = di.y;
var sti = $("<div class='station_info_' id='station_info_"+i+"'></div>").css({
left:x,
top:y
});
// HTML id, class, and name attributes cannot start with a number
$("<div class='desk_box' data='"+i+"'>id:"+i+'</div>').css({
left:x,
top:y
}).appendTo(ms).append(sti).click(function(){
var info = $(this).next();
$.post('live_info.php', {station_id:info.attr('id').replace(/^station_info_/, '')}, function(r){
// do stuff with r
info.html('love:'+r.love+'<br />hate:'+r.hate).toggle();
}, 'json');
});
}
}, 'json');
});
// use CSS to do `.desk_box,.station_info_{position:absolute;}`
//]]>
Now for main_init.php:
<?php
if(isset($_POST['init']) && $_POST['init'] === '1'){
include_once 'connect.php'; $db = db(); $json = array();
$q = $db->query("SELECT * FROM table WHERE"); // example only
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$json[strval($r->coordinate_id)] = array('x' => $r->x_coord, 'y' => $r->y_coord);
}
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// could be a hack
}
?>
Here's what live_info.php might look like:
<?php
if(isset($_POST['station_id'])){
include_once 'connect.php'; $db = db(); $json = array();
// example only - you will only get one `$row` if query is done specific, so while loop is not needed
$q = $db->query("SELECT love,hate FROM some_table WHERE id='{$_POST['station_id']}'");
if($q->num_rows > 0){
$row = $q->fetch_object();
// it's okay to overwrite array in this case
$json = array('love' => $row->love, 'hate' => $row->hate);
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// may be a hack
}
?>

Categories