I need help with FullCalendar and Javascript and PHP.
I need to include this foreach PHP code into this Javascript.
<script type="text/javascript">
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
events: [
<?php
$sql = "SELECT * FROM eventi";
$eventi = $mysqli->query($sql);
foreach ($users as $row) {
echo '{';
echo 'title: "'.$eventi['nome'] . '"';
echo 'start: "'.$eventi['data'] . '"';
echo '},';
}
?>
]
});
});
</script>
By changing your query so ite returns the data with the desired column names, and then using json_encode to format the results, you can
simplify the code quite a bit.
<script type="text/javascript">
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
events: [
<?php
$sql = "SELECT `nome` as `title`, `data` as `start` FROM eventi";
$eventi = $mysqli->query($sql);
$allrows = $eventi->fetch_all(MYSQLI_ASSOC);
$rslt = json_encode($allrows);
echo $rslt;
?>
]
});
});
</script>
Related
Used a form to create a php search for a MySQL database in a header.php file.
Attempting to use simplePagination.js with php. I am able to correctly calculate the number of results and display the appropriate amount of page links. However, search.php is not limiting the number of items on the page, and all of the pagination links lead to a blank page.
<form action="search.php" method="POST">
<input type="text" name="search" placeholder="search site">
<button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
</form>
search.php code:
<?php
include 'header.php';
?>
<section class="searchPage">
<div class="searchResults">
<?php
if (isset($_POST['submit-search'])){
$searchTerm = trim( (string) $_POST['search'] );
if (isset( $searchTerm[0] )) {
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
$limit = 10;
$numberOfPages = ceil($queryResult/$limit);
if ($queryResult > 0){
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='articleItem'>
<h2>".$row['title']."</h2>
<p>".$row['abstract']."</p>
<a href=".$row['link']." target='_blank'>".$row['link']."</a>
</div>";
}
$pageLinks = "<nav><ul class='pagination'>";
for ($i=1; $i<=$numberOfPages; $i++) {
$pageLinks .= "<li><a href='search.php?page=".$i."'>".$i."</a></li>";
};
echo $pageLinks . "</ul></nav>";
}
else {
echo "There are no results matching your search.";
}
}
}
?>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $queryResult;?>,
itemsOnPage: <?php echo $limit;?>,
currentPage : <?php echo $page;?>,
hrefTextPrefix : 'search.php?page='
});
});
</script>
You don't need to create the page links on your own, because this is what the plugin does through JavaScript events. So you can replace the ul with a div element. This is the reason why you get a blank page.
echo "<nav><div class='pagination'></div></nav>";
In the following is what I added to make it work:
$(document).ready(function(){
var pageParts = $(".articleItem");
pageParts.slice(<?php echo $limit;?>).hide();
$('.pagination').pagination({
items: <?php echo $queryResult;?>,
itemsOnPage: <?php echo $limit;?>,
onPageClick: function(pageNum) {
var start = <?php echo $limit;?> * (pageNum - 1);
var end = start + <?php echo $limit;?>;
pageParts.hide().slice(start, end).show();
}
});
});
I'm new with coding and I found some really valuable information that could help my register form look better using Ajax.
The problem is that, even though the php files are working fine, I think that the js file is not doing it's job. here:
in the register form there's this:
<?php
include 'php_includes/conexion.php'; (connect to DB users)
include 'php_includes/conexionlugar.php'; (connect to DB states/cities)
?>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.js"></script>
</head>
in the form there's this:
Select State
<select name="departamento" id="departamento">
<option value="">Seleccione Departamento</option>
<?php echo cargar_departamentos();?>
</select>
Select City
<select name="provincia" id="provincia">
<option value="">Seleccione Provincia</option>
</select>
Now, in the conexionlugar.php (tested/working):
<?php
function cargar_departamentos()
{
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output = '';
$sql = "SELECT * FROM departamentos ORDER BY NOMBRE_DEPA";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDDEPARTAMENTOS"].'">'.$row["NOMBRE_DEPA"].'</option>';
echo "$output";
}
}
return $output;
?>
in the jquery.js (don't know much about this :()
$(document).ready(function(){
$('#departamento').change(function(){
var IDDEPARTAMENTOS = $(this).val();
$.ajax({
url:'../php_includes/fetch_provincia.php',
type:"POST",
data:{departamentoId:IDDEPARTAMENTOS},
dataType:"text",
success:function(data)
{
$('#provincia').html(data);
}
});
});
});
in the fetch_provincia.php (tested/working)
<?php
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output ='';
$sql = "SELECT * FROM provincias WHERE departamentos_IDDEPARTAMENTOS = '".$_POST["departamentoId"]."' ORDER BY NOMBRE_PROV";
$result = mysqli_query($connect, $sql);
$output = '<option value="">Seleccione Provincia</option>';
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDPROVINCIAS"].'">'.$row["NOMBRE_PROV"].'</option>';
echo $output;
}
return $output;
?>
Though separately the PHP files are working, the JS file changing departamentoId for IDDEPARTAMENTOS looks like it's not... help me please.
I think I fixed it, deleting the "return" on both php and adding the js to the same page and not calling it through
The data you are sending from php needs to be sent as json. I would actually not do the "formatting" in php. Just return $result:
echo json_encode($result);
then in your js file, just iterate through "data" and create the options:
success:function(data)
{
$.each(data, function(key, val){
console.log("Key: " + key + " val: " + val);
}
}
have a some errors in your code.
First, in "cargar_departamentos", the return it´s out of a function, and in your fetch_provincia.php, not need a return statement.
In your jQuery code, try remove one of both jQuery called in your head, and Change de dataType directive of "text" to HTML.
#gilgameshbk you are calling jquery 2 times in your head
maybe this may cause some conflict.
I have this index.php file to show some stuff in tables from loop:
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?> </th></table>
<?php } ?>
However, I wish to have auto refresh for those tables. So I have this new file data.php and a updated index.php:
data.php:
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
print_r($row);
index.php:
<div id="show"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; </th></table>
<?php } ?>
This will refresh and print the output in the above <div>:
<div class="show"></div>
And it works great, but I don't really have any clue how to put that inside the loop for the tables, just as the first index.php file. Any suggestions of a direction to take in this matter?
You can use ajax to call data.php and return the response in json format for a better approach
Try:
js
function populate(){
var items= [];
$.ajax({
url: 'data.php',
type: 'GET',
dataType: 'json',
success: function(data){
//do something with data here
console.log(data);
//loop through data and push to array
$.each(data, function(i,v){
items.push('< th >'+v+'< /th >');
});
//join array and append to table
$('#sampleTable tbody').html(items.join(','));
},
error: function(err){
console.log(err.responseText);
}
});
}
//call populate every 10 secs (example only , you can change to how many seconds you like)
setTimeout(function(){
populate();
},10000);
data.php
$sql = 'SELECT id FROM usertbl';
$stmt = $hund->runQuery($sql);
$stmt->execute();
$row = $stmt->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($row);
In this line you forgot to close <?php ...
Possibly that's why foreach loop doesn't work correctly
<?php foreach ($row as $runloop) { ?>
<table><th> <?php echo $runloop['id']; ?></th></table>
<?php } ?>
Put these lines in data.php where print_r() is.
I've been trying to retrieve data from mysql database using SELECT Count, as I got a list of countries which I want to count how many times each country is displayed in the column SovereignState, to a Google Geo Chart and by browsing around, I believe that json_encode should do the trick.
However, I have no idea how to get make a json_encode from my php code and then put it in the DataTable of the chart.
This is the php code:
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD','');
define('DB_HOST', '');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) ;
if ($conn->connect_error) {
die ('Could not connect: ' . $conn->connect_error);
}
$sql = "SELECT SovereignState, COUNT(*) FROM Data_2 GROUP BY SovereignState";
echo $sql;
//$result = $conn->query($sql);
$result = $conn->multi_query($sql);
if(!$result) {
echo "Could not successdully run query ($sql) from DB: " . mysql_error(); exit;
}
echo "<pre>";
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s - %s\n", $row[0], $row[1]);
}
$result->free();
}
} while ($conn->more_results());
echo "</pre>";
$conn->close();
And this is the html code of the google geochart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Number'],
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
You can use json_encode() from your PHP code and use Ajax in order to get the JSON into your JS code.
Also, (not recommended) you can just call a PHP function from your JS code with <?php myFunction();?>, that function should return an echo json_encode().
I am running an SQL Query in PHP and putting the values into a JS variable:
<?php
$return_arr = array();
$sql="SELECT * from customer_billing group by productname ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs)) {
$return_arr[] = $result["productname"];
}
echo json_encode($return_arr);
?>
<script type="text/javascript">
$(function() {
var availableTags = <?php echo json_encode($return_arr); ?>
//autocomplete
$(".auto").autocomplete({
source: availableTags
});
});
</script>
I have 3 rows with the column productname equal to:
Integra Fibre Unlimited
Integra Fibre Unlimited (RRP: £59.95)
Integra Professional Web Hosting
and when i use echo json_encode($return_arr);, it displays like:
"Integra Fibre Unlimited",null,"Integra Professional Web Hosting"
it just doesn't like displaying the second one
Try:
// some code
while($result=mysql_fetch_array($rs)) {
$return_arr[] = utf8_encode($result["productname"]);
}
echo utf8_decode(json_encode($response));