<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/style.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script src="./js/jquery.js"></script>
<script src="./js/laddubox.js"></script>
<script src="./js/pop.js"></script>
<script src="./js/jquery.js"></script>
<script type="text/javascript">
var sbs = {
'url' : '<?="./gearedup-pics/"?>',
'logged' : '<?=$notregister?>',
'userid' : '<?= $id ?>',
'father' : '<?= $father ?>' ,
'mother' : '<?= $mother ?>',
'kid' : "<?= $kid ?>"
};
</script>
<title><?=$title?></title>
</head>
I am sending information via javascript using php but $kid ,$mother and $father are in array format . So its showing me an error.
Notice: Array to string conversion in C:\xampp\htdocs\sbs\sbs\html\meta.php on line 19
Array' ,
<?= converts the variable to a string and outputs it. Implicitly converting arrays to strings results in a notice (not an error).
I advise you to use json_encode():
<?php
$data = array(
'url' => './gearedup-pics/',
'logged' => $notregister,
'userid' => $id,
'father' => $father,
'mother' => $mother,
'kid' => $kid
);
?>
var sbs = <?php echo json_encode($data); ?>;
Related
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>
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 searched for a solution of passing a get variable obtained from index.php page to included.php file[ loaded by javascript ]. A nice solution by php require function is given Pass and print a $_GET variable through an included file by php require function
However, in my case I have
for index.php => url[ index.php?var=item]
<?php
if(isset($_GET['var'])) {
$var=$_GET['var'];
}
?>
<script>
$(document).ready(function(){
$("#ok").load("included.php");
});
</script>
<div id='ok'>
</div>
in included.php [which will be loaded in index.php by javascript load function]
<?php
echo $var;
?>
The error was the undefined var in included.php file.How Can I echo this variable with a combination of php and javascript ?
If you want to pass these variables on to the included file you could go with
$("#ok").load("included.php?<?php echo $urlString; ?>");
The URL string can be generated with this function
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
Another option would be :
$( "#ok" ).load( "included.php", { "choices[]": [ "Jon", "Susan" ] } );
Based upon the first example:
index.php:
<?php
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
if(isset($_GET['var']) === true) {
$var=$_GET['var'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Test</title>
<script type="text/javascript">
$(document).ready(function(){
$("#ok").load("included.php?<?php echo GenGetVars(); ?>");
});
</script>
</head>
<body>
<div id='ok'>
</div>
</body>
</html>
included.php
<?php
echo print_r($_GET, true);
?>
index.php:
<?php
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
if(isset($_GET['var']) === true) {
$var=$_GET['var'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Test</title>
<script type="text/javascript">
function LoadScriptFile(){
/// SENDING THE INFORMATION BY AJAX
$.ajax({
type : "POST", /// SEND TYPE
url : "getScriptName.php", /// TARGET FILE TO RETRIEVE INFORMATION
data : {
'SomeParamID' : 1,
'AnotherParamID' : 'Dunno.. just something'
},
///######## IN CASE OF SUCCESS
success:function(response){
if( response != "" ){
$.getScript( 'js/' + response + '.js', function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
}
else{
alert( "Error retreiving data" );
}
}
}
);
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#ok").load("included.php?<?php echo GenGetVars(); ?>");
});
</script>
</head>
<body>
<div id='ok'>
</div>
</body>
</html>
included.php
<?php
echo print_r($_GET, true);
?>
getScriptName.php
<?php
switch($_POST['SomeParamID']){
case 1:
echo 'MyGreatJSFile';
break;
case 2:
echo 'MyNotSoGreatJSFile';
break;
}
?>
You could try this.
I'm trying to auto-refresh multiple PHP variables. So far I can only auto-refresh one variable and the rest do not work (it will always be the last one that works, so var2).
I was thinking of making a JSON script and trying to do it like that but how would I go about making each array in the JSON to auto-refresh on my PHP page without refreshing the whole page?
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" src="jquery-1.2.6.min.js"></script>
<script language="javascript" src="jquery.timer-1.0.0.js"></script>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="jquery-1.9.0.min.js"></script>
<?php $ra = "<div id='c1b'></div>
<script type='text/javascript'>
$(document).ready(function() {
$('#c1b').load('var1.php');
refresh();
});
function refresh(){
setTimeout( function() {
$('#c1b').fadeOut('slow').load('var1.php').fadeIn('slow');
refresh();
}, 2000);
}
</script>";
$rb = "<div id='c2b'></div>
<script type='text/javascript'>
$(document).ready(function() {
$('#c2b').load('var2.php');
refresh();
});
function refresh(){
setTimeout( function() {
$('#c2b').fadeOut('slow').load('var2.php').fadeIn('slow');
refresh();
}, 2000);
}
</script>"; ?>
<?php echo $ra . ' & ' . $rb ?>
var1.php
<?php
include_once 'connect.php';
$d= 'var1';
$q = $handler->prepare("SELECT * FROM var WHERE name = ?");
$q->bindParam(1, $d);
$q->execute();
while($r = $q->fetch()){
$e = $r['names'];
}
echo $e;
?>
var2.php
<?php
include_once 'connect.php';
$d= 'var2';
$q = $handler->prepare("SELECT * FROM var WHERE name = ?");
$q->bindParam(1, $d);
$q->execute();
while($r = $q->fetch()){
$e = $r['names'];
}
echo $e;
?>
As best as I can read this, you're going to have two functions named "refresh" defined on your page.
Try changing the script in your second one to a unique name, e.g.
$(document).ready(function() {
$('#c2b').load('var2.php');
refreshvar2();
});
function refreshvar2(){
setTimeout( function() {
$('#c2b').fadeOut('slow').load('var2.php').fadeIn('slow');
refreshvar2();
}, 2000);
}
I have a project i am working on that requires sending information from database through a php script using json feed to javascript. Here are the scripts:
This is the javascript:
<link rel= 'stylesheet' type='text/css' href='fullcalendar/fullcalendar/fullcalendar.css' />
<link rel="stylesheet" media="print" href="fullcalendar/fullcalendar/fullcalendar.print.css" />
<script type="text/javascript" src="fullcalendar/lib/jquery.min.js"></script>
<script type='text/javascript' src="fullcalendar/fullcalendar/fullcalendar.js"></script>
<script type="text/javascript" src="fullcalendar/lib/jquery-ui.custom.min.js" ></script>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: "public_calendar.php"
})
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
?php require_once("includes/initialize.php"); ?>
<?php require_once(LIB_PATH.DS.'database.php'); ?>
<?php
//Find all the events
$events = Event::find_all();
foreach($events as $event):
$id = (int) $event->id;
$title = "{$event->event_title}";
$start = "{$event->start_date}" ." ". "{$event->start_time}";
$end = "{$event->end_date}" ." ". "{$event->end_time}";
$url = "event_detail.php";
echo json_encode( array(
'id' => $id,
'title' => "{$title}",
'start' => "{$start}",
'end' => "{$end}",
'url' => "{$url}"
));
endforeach;
?>
This is how the php script should look like:
[ {"id":111,"title":"Event1","start":"2013-10-10","url":"http:\/\/yahoo.com\/"},
{"id":222,"title":"Event2","start":"2013-10-20","end":"2013-10-22","url":"http:\/\/yahoo.com\/"}
]
This is how it looks like now:
{"id":12,"title":"Matriculation","start":"2013-11-5 08:00","end":"2013-11-5 17:00","url":"event_detail.php"}
{"id":13,"title":"Exam","start":"2013-11-30 09:00","end":"2013-11-30 16:00","url":"event_detail.php"}
{"id":2,"title":"Convocation","start":"2013-12-11 08:00","end":"2013-12-11 19:00","url":"event_detail.php"}
Thanks for your help in advance.
The best way to achieve the result you want is to create an array in PHP, then use json_encode() to create the output. You're already doing some of this - you just need a little more:
<?php
//Find all the events
$events = Event::find_all();
$eventList = array(); // Assemble list of all events here
foreach($events as $event):
$eventList[] = array( // Add our event as the next element in the event list
'id' => (int) $event->id,
'title' => $event->event_title,
'start' => $event->start_date." ".$event->start_time,
'end' => $event->end_date." ".$event->end_time,
'url' => "event_detail.php"
);
endforeach;
echo json_encode($eventList); // encode and output the whole list.
?>
I've also simplified and shortened some of your code to remove the unnecessary double quotes.