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>
Related
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';
i'm trying to use a get statement in a variable to add data to a data base, when i try to do this nothing is added under folder however if i add plain text it is added. (i'm trying to add to the folder section)
My entire html document is provided below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="newfile.css">
<title>Folder</title>
</head>
<body>
<?php
include_once 'dbh.php';
echo $_GET["data"];
if(isset($_GET["data"])) {
$location = $_GET["data"];
$sql = "SELECT * FROM posts WHERE folder LIKE '%$location%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result))
{
echo $row['content'];
}
} else {
echo "There are no results matching your search!";
}
}
?>
<?php
$uploadpath = 'postimages/'; // directory to store the uploaded files
$max_size = 3116718; // maximum file size, in KiloBytes
$alwidth = 100000; // maximum allowed width, in pixeli
$alheight = 100000; // maximum allowed height, in pixeli
$allowtype = array('bmp', 'gif', 'jpeg', 'jpg', 'jpe', 'png', 'docx', 'psd', 'pdf', 'pptx', 'html', 'php', 'css', 'js', 'mp4', 'mp3'); // allowed extensions
if(isset($_FILES['fileup'])) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$name = basename( $_FILES['fileup']['name']);
$type = end(explode('.', strtolower($_FILES['fileup']['name'])));
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = '';
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*900000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x
'. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_GET['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
if($result !== false) {
header("Location: fold.php?data=Math");
}else{
echo "fail";
}
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<div class="upform">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="image-upload">
<label for="file-input">
<img src="add-file.png" />
</label>
<input id="file-input" type="file" name="fileup"/>
</div>
<input class="noshow" type="text" id="wow" placeholder="<?php echo $_GET['data']; ?>" name='name'>
<input type="submit" id="submit" name='submit' value="U P L O A D" />
</form>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$("#submit").show();
// or, as has been pointed out elsewhere:
// $('input:submit').removeAttr('disabled');
}
}
)
});
</script>
</body>
</html>
url= http://localhost/smart%20assist/fold.php?data=Math
Any help would be awesome, Thanks
So, if you doing file uploading you are using post method in your form with multi-part, right.
now, if you want to send something with your url as query params, then you have to use $_REQUEST. In your case,
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_REQUEST['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
If you facing the same problem, I need to check your HTML form, to help you in a better way.
I think you made below mistakes.
You are not posting "data" field value in your HTML.
You must put the name field for get data.
You are posting the form for using post method. So you should be used $_POST[] or $_REQUEST[].
please verify your HTML.
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);
I am trying to test the following code for inserting the value from PHP code to my javascript variable x
tested the PHP code, and it's giving the correct output but the alert box in the javascript shows this -
date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000"; $query = mysql_query($myquery); if ( ! $myquery ) { echo mysql_error(); die; } $data = array(); for ($x = 0; $x < mysql_num_rows($query); $x++) { $data[] = mysql_fetch_assoc($query); } //echo json_encode($data); echo ''; mysql_close($server); ?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Testing </title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
<?php
$username='user';
$password='pass';
$host='xx.xx.xx.xx';
$database='abc';
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = 'select code a,sum(fee) b from xyz where date > date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000';
$query = mysql_query($myquery);
if ( ! $myquery ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
//echo json_encode($data);
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
mysql_close($server);
?>
<script type="text/javascript">
function test(){
var x = document.getElementById("myPhpValue").value;
alert(x);
}
test();
</script>
</body>
</html>
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
Then:
var x = document.getElementById("myPhpValue").value;
you need to insert id="myPhpValue", because you used the "getElementById";
Add ID attribute in the html line
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
replace the above line by
echo '<input type="hidden" name="myPhpValue" id ="myPhpValue" value="'. json_encode($data) . '">';
You are inserting a value into html, not javascript code.
Do it like that:
<script type="text/javascript">
function test(){
var x = <?php echo json_encode($data); ?>;
alert(x);
}
test();
</script>
Server configuration problems
If You are getting php code on client-side (view-source to confirm), then the PHP engine is not working on the server.
You should check that php is properly installed on the server and is set as a handler for php files in your web server.
This depends on your web server and operating system.
Code problems
Problem #1: your output (echo) is creating an HTML element, not javascript. Hence you should escape the content for HTML - use htmlspecialchars instead of json_encode
Problem #2: you access the element with javascript document.getElementById but your actual element does not have an ID. Hence need to add the id attribute to your html input element.
Solution:
Stage 1: php outputs html - use htmlspecialchars and add id attribute
echo '<input type="hidden" name="myPhpValue" id="myPhpValue" value="'. htmlspecialchars($data) . '">';
Stage 2: javascript accesses html element (this is taken as-is from your code).
var x = document.getElementById("myPhpValue").value;
Side-note
You're using a deprecated mysql extension and should switch to PDO or mysqli instead.
There are numerous discussions both on SO and external resources on the matter.
Just a few:
Choosing an API - PHP manual
What is the difference between MySQL, MySQLi and PDO?
mysqli or PDO - what are the pros and cons?
Study jQuery from online tutorial, find many tutorials, just find one simple maybe good for newbie.
Here is the code for index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>
Autocompletement
</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="suggest.js"></script>
</head>
<body>
<input type="text" name="suggest" placeholder="Type a Country Name..." onkeyup="suggestion()"/>
<div id="autosuggest"></div>
</body>
</html>
Here is the code for suggest.php:
<?php
include "connect.php";
function auto($data){
global $mysqli;
$data = $_GET['data'];
$query = "SELECT code, name_en
FROM countries
WHERE name_en LIKE '%$data%'
OR code LIKE '%$data%'";
$items = '<ul class="suggestion">';
if($result = $mysqli->query($query)){
/* fetch associative array */
while($row = $result->fetch_assoc()){
$items .= '<li>'.$row['name_en'] . ' ' . $row['code'].'</li>';
}
$items .= '</ul>';
}else{
$items = "No results Found...";
}
echo $items;
}
auto();
?>
Here is the code for suggest.js
function suggestion(){
var suggestVal = $('#suggest').val();
if(suggestVal != ''){
$.ajax({
url: 'suggest.php?data='+suggestVal,
success: function(data){
$('#autosuggest').html(data);
}
})
}
}
The result above will only show "No results Found...", it seems that processing file suggest.php is not working, then I test it with a test file test.php:
$mysqli = new mysqli("host","user","pass","database");
//auto();
$data = $_GET['input'];
//$data = "ca";
$query2 = "SELECT code, name_en FROM countries WHERE name_en LIKE '%$data%' OR code LIKE '%$data%'";
echo "<br>" .$query2;
echo "<br>";
if($mysqli){
echo "Yes SQL";echo "<br>";
}else{
echo "No SQL";echo "<br>";
}
$result = $mysqli->query("SELECT code, name_en FROM countries WHERE name_en LIKE '%$data%' OR code LIKE '%$data%'");
if($result->num_rows){
echo "Yes Result";echo "<br>";
}else{
echo "No Result";echo "<br>";
}
The weird thing is that I cannot find anything wrong with my code, checked php.net sample and seems all to be good? But when I check vam_dump($result) then it is "null", any helps will appreciated.
Here is the test.php output:
SELECT code, name_en FROM countries WHERE name_en LIKE '%ch%' OR code LIKE '%ch%'
Yes SQL
No Result
URL: http://IP/project/jquery/auto_diy/test.php?input=ch
You defined your function as having a $data argument
function auto($data){...}
but you are calling it without the argument,
auto();
this will trigger a notice.
The argument is not needed, since you are already using $data=$_GET['data']; inside your function.
Then in your ajax call you should change it like so
$.ajax({
url: 'suggest.php',
type: 'get', // this can be omitted because GET is default
data: 'data='+suggestVal, // or
// data: {data:suggestVal}
success: function(data){
$('#autosuggest').html(data);
}
})
Update:
in test.php output directly the value of $result->num_rows
print "Rows returned: " . $result->num_rows . "<br>";
if you get zero rows, copy the query and run it in phpmyadmin or a mysql console to verify the data.
in suggest.php, update this:
$result = $mysqli->query($query);
if (!$result) {
print 'Could not execute query';
}
else {
while($row = $result->fetch_assoc()){
$items .= '<li>'.$row['name_en'] . ' ' . $row['code'].'</li>';
}
}
$items .= '</ul>';