fullcalendar.js is not reading the php json feed - javascript

i want to pre-poulate my fullcalendar instance via a php json feed.
The page is loading fine (no 404 or sth like that) but the calendar is not showing any of the events.
generating the json:
<?php
require("../config/config.php");
$uid = $_SESSION['uid'];
$res = $db->query("SELECT * FROM slots WHERE tid = '$uid'");
$data = array();
while($row = $res->fetch_assoc())
{
$event = array();
$event['editable'] = false;
$event['id'] = "fixE_".$row['id'];
$event['title'] = getSlotStatus($row['status']);
$event['sid'] = $row['sid'];
$event['status'] = $row['status'];
$event['start'] = $row['start'];
$event['end'] = $row['end'];
$event['standby'] = $row['standby'];
if(strpos($data['status'],"_old"))
{
$event['textColor'] = '#000000';
$event['color'] = '#cccccc';
$event['className'] = 'lessonSlotOld';
}
else
{
$event['color'] = getColorCode($row['status']);
if($row['standby'])
{
$event['borderColor'] = '#0000FF';
}
}
$data[] = $event;
}
echo json_encode(array("events"=>$data));?>
and here's the part of the fullcalendar code where i am inserting the feed:
events:
{
url: 'include/fetchSlots.php',
type: 'POST',
error: function(){alert("There was an error fetching events")}
},
the json output of the php looks like the following (this is just a part because the whole response would be too much ;) )
{"events":[{"editable":false,"id":"fixE_164","title":"Slot is closed","sid":"0","status":"closed","start":"2015-06-06T04:00:00+08:00","end":"2015-06-06T04:30:00+08:00","standby":"0","color":"#B20000"}]}

Ok so here's the solution/the mistake.
The only problem that fullcalendar has is the line where the actual json is posted:
echo json_encode(array("events"=>$data));
fullcalendar doesnt want the "events" and it doesnt want the twice wrapped array. so the solution to this is simply to output the data-array directly:
echo json_encode($data);
then, the events are all loaded correctly.
ah and for all watchmen out there, yes i found the mistake with the wrong named variable ;)
if(strpos($data['status'],"_old"))
to
if(strpos($row['status'],"_old"))

Related

(populate dropdown in contact form 7 getting this error - Warning: array_keys() expects parameter 1 to be array, null given in

Ok where to start, I will try and explain as much as I can.
I am using wordpress with contact form 7 and I am trying to populate 3 dropdown items on the contact form, I found some code that I was able to use with no problem but the problem with this was that it was getting the information from a excel file, the file is now to big and will not run on my website anymore so I would like to get the information from my database now.
I have made a table in my database "vehicle_information" with 3 columns "vehicle_type", "vehicle_make", vehicle_model"
I have code in my functions.php and code in my footer to be able to use the cf7 shortcodes.
Code from funtions.php
function ajax_cf7_populate_values() {
//MySQLi information
$db_host = '***';
$db_username = '***';
$db_password = '***';
$vehicles_makes_models = array();
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die('Error ' . mysqli_error());
//select MySQLi dabatase table
$vehicles_makes_models = mysqli_select_db($connection, 'vehicle_information') or die('Error ' . mysqli_error());
$sql = mysqli_query($connection, 'SELECT * FROM vehicle_type');
while($row = mysqli_fetch_array($sql)) {
$vehicles_makes_models[$row[0]][$row[1]][] = $row[2]; }
}
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'vehicles' => array_keys($vehicles_makes_models),
'makes' => array(),
'models' => array(),
'current_vehicle' => false,
'current_make' => false
);
// collect the posted values from the submitted form
$vehicle = key_exists('vehicle', $_POST) ? $_POST['vehicle'] : false;
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
// populate the $return_array with the necessary values
if ($vehicle) {
$return_array['current_vehicle'] = $vehicle;
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = $vehicles_makes_models[$vehicle][$make];
if ($model) {
$return_array['current_model'] = $model;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
Code from my footer
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $vehicles_dd = $('[name="vehicles"]');
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'vehicle' : $vehicles_dd.val(),
'make' : $makes_dd.val(),
'model' : $models_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('<?php echo admin_url( 'admin-ajax.php' ) ?>', data, function(response) {
all_values = response;
$vehicles_dd.html('').append($('<option>').text(' -- choose vehicle -- '));
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$.each(all_values.vehicles, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_vehicle == this) {
$option.attr('selected','selected');
}
$vehicles_dd.append($option);
});
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
},'json');
}
})( jQuery );
The problem is I am still learning and this is the first time I have had to use this funtion.
and I am getting an error on my website
Warning: array_keys() expects parameter 1 to be array, null given in /customers/4/0/0/motobid.co.uk/httpd.www/wp-content/themes/storevilla-child/functions.php on line 38 {"vehicles":null,"makes":[],"models":[],"current_vehicle":false,"current_make":false}
any help would be very greatful.
Just like to say code was supplied by BDMW.
Where you use the method array_keys(), instead of:
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
Try this:
$return_array['makes'] = ! empty($vehicles_makes_models[$vehicle]) ? array_keys($vehicles_makes_models[$vehicle]) : [];
From what I've read, the array_keys() has been an issue depending on php versions. Hope this helps!

Search form using ajax, php and json

i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>

PHP file ouputs the javascript code itself and not running

I'm trying to create an Edit Modal. Provided that I have the html code for this, I write this javascript/jquery code:
<script type='text/javascript'>
$(function() {
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo " <script type'text/javascript'> alert('1');</script>";
$unitID = $r['unitID'];
$unitStatus = $r['unitStatus'];
$unitNumber = $r['unitNumber'];
$floorNumber = $r['floorCode'];
$unitType = $r['unitType'];
$t = $db->query("select floorLevel, floor_buildingID from tblFloors where floorLevel = '$floorNumber'");
while( $u = $t->fetch(PDO::FETCH_ASSOC)){
$floorLevel = $u['floorLevel'];
$floor_buildingID = $u['floor_buildingID'];
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = $unitType");
while($x = $w->fetch(PDO::FETCH_ASSOC)){
$unitTypeName = $x['unitTypeName'];
?>
$("#editModal<?php echo $unitID; ?>").click(function(){
$("#editUnitNumber").val("<?php echo $unitNumber;?>");
$("#editUnitType").val("<?php echo $unitType; ?>").material_select('update');
$("#editFloorNumber").val("<?php echo $floorNumber; ?>");
});
<?php }}}?>
});
The code above is used to write the data from the modal, but instead it output this:
$("#editModal5").click(function(){ $("#editUnitNumber").val("12002"); $("#editUnitType").val("4").material_select('update'); $("#editFloorNumber").val("12"); }); });
How do I solve that? What causes this?
Use json to pass data from php to javascript, instead of echoing everything out in one place. It may seem an overkill but it's readable, and is more beneficial on the long run.
The code below is not tested, but it should give you a general idea on how to approach these things. I did not include the second and third queries within the first while loop. You can nest the results from those queries in the $unit array and access the relevant data via additional loops in javascript.
Also, ideally you wouldn't just echo out the decoded array right after the php, a better solution would be to call a function in the footer, that would generate a script tag with all data that is used by javascript. Another approach is to use AJAX and get a json response only when you need it, then you would feed that same json to the loop.
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
$units = [];
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$unit = [
'unitID' => $r['unitID'],
'unitStatus' => $r['unitStatus'],
'unitNumber' => $r['unitNumber'],
'floorNumber' => $r['floorCode'],
'unitType' => $r['unitType']
];
$units[] = $unit;
}
$units_json = json_encode($units);
?>
<script type='text/javascript'>
$(function() {
var units = '<?php echo $units_json ?>';
var units_array = JSON.parse(units);
// do some validation here
for (var i = 0; i < units_array.length; i++) {
// do some validation here
$("#editModal" + units_array[i].unitID).click(function(){
$("#editUnitNumber").val(units_array[i].unitNumber);
$("#editUnitType").val(units_array[i].unitType).material_select('update');
$("#editFloorNumber").val(units_array[i].floorNumber);
});
};
});
</script>

array_push flat array issue - need to be able to add multiple variables to the array

I am trying to add a pair of variables 'product_name' and 'photos' (which is the URL of the car photo) into an array. I have a friend that said my efforts are failing because I am pushing into a flat array. I've looked to see how to do this with variable pairs and am stymied. He had suggested pushing row into $isotopecubes instead of how I have it below, but when I try I am getting null values. I need to be able to access val.photo and val.product_name in my javascript call in my php file that references this ajax code.
Note: if I just use:
array_push($isotopecubes, $row['photo']);
I get back the following JSON response on my console:
"/images/photos/cars/vw/14_Virginia_L.jpg",
"/images/photos/cars/mazda/2013/14hybrid.jpg"
so I know I am reaching the database and getting the correct values. Here is my ajax code:
<?php
include '../../global_config.php';
include 'config.php';
if ($_GET['action'] == 'get-images') {
$selectSql = "SELECT product_name, photo FROM cars WHERE publish = 1;";
$isotopecubeResult = $db->query($selectSql);
$isotopecubes = array();
while($isotopecubeResult->fetchInto($row, DB_FETCHMODE_ASSOC)) {
array_push($isotopecubes, $row['photo'], $col['product_name']);
// $isotopecubes = array_merge($isotopecubes, $row['photo']);
}
echo json_encode($isotopecubes);
}
?>
It can be done by
<?php
include '../../global_config.php';
include 'config.php';
if ($_GET['action'] == 'get-images') {
$selectSql = "SELECT product_name, photo FROM cars WHERE publish = 1;";
$isotopecubeResult = $db->query($selectSql);
$isotopecubes = array();
while($isotopecubeResult->fetchInto($row, DB_FETCHMODE_ASSOC)) {
//array_push($isotopecubes, $row['photo'], $col['product_name']);
// $isotopecubes = array_merge($isotopecubes, $row['photo']);
$isotopecubes[] = array('product_name' => $row['product_name'], 'photo' => $row['photo']);
}
echo json_encode($isotopecubes);
}
?>
Now you will be able to get value through val.product_name and val.photo

Ajax call posting duplicates in DB

I am using to Fullcalendar jquery with php for event management. I using ajax call for adding events. The call works fine for the first event entry after refresh. But for the following event entries duplicate events are created for each entry. Not sure what causing this.
This is the error:
This is the jquery call:
Jquery
$('#evesav').bind('click',function(){
$('#evesav').attr('disabled','disabled');
var title = $('#evename').val();
var edes = $('#evedes').val();
var everegion = $('#everegion').val();
var eveserv = $('#eveserv').val();
$.ajax({
url: 'add_events.php',
data: 'title='+ title+'&start='+ start +'&end='+ end +'&edes='+ edes +'&everegion='+ everegion +'&eveserv='+ eveserv,
type: "POST",
success: function(json) {
$('#myModal').modal('hide');
$('#alertcon').html(json);
$('#alert').modal('show');
$('#evename').val("");
$('#evedes').val("");
$('#evesav').removeAttr('disabled');
$('#calendar').fullCalendar( 'refetchEvents' );
}
});
$('#calendar').fullCalendar( 'rerenderEvents' );
});
This is the PHP Code:
PHP
<?php
if(($_POST['title'] && $_POST['start'] && $_POST['end'] && $_POST['edes'] && $_POST['everegion'] && $_POST['eveserv'])!= NULL)
{
// Values received via ajax
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
$edes = $_POST['edes'];
$region = $_POST['everegion'];
$server = $_POST['eveserv'];
//echo $title."".$start."".$end."".$edes."".$region."".$server;
// connection to the database
include('includes/db.php');
// insert the records
$sql = "INSERT INTO evenement (title, start, end, edes, region, server) VALUES (:title, :start, :end, :edes, :region, :server)";
$q = $bdd->prepare($sql);
$q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server));
if($q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server))){
var_dump($q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server)));
}
$eveid=$bdd->lastInsertId();
// Get array of all source files
$files = scandir("uploads/");
// Identify directories
$source = "uploads/";
$destination = "evedata/".$eveid."/";
mkdir("evedata/".$eveid);
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
echo "Added Successfully";
}
else {
echo "Please Fill the data";
}
?>
Some one please help me with this.
I'd give each event addition form a control, for instance a dynamic GUID, which then can be used to save to DB. This way you have a GUID to work with in dealing with CalDAV protocol, if you ever choose to do as such with your calendar, as well as have a way to make certain nothing is duplicated by chance in your database.
Now, do keep in mind this is simply a patch, not a fix. Therefore, you'll do yourself a lot of good to find a way to stop the multiple attempts to add an event to your DB. Regardless of your success in finding your bug, using a control mechanism or unique identifier is a good idea.

Categories