Fetching events from database into FullCalendar - javascript

I am trying to fetch data from a MySQL database into a calendar. (FullCalendar plugin)
I want to send the fetched data as a json feed to be displayed on the calendar.
This is my Javascript code for displaying the events:
events: {
url: 'http://localhost/Hotel/event_source.php',
error: function() {
alert('There was an error while fetching events.');
}
This is the event_source.php page where I'm fetching the data from the database:
<?php
include('hoteldb.php');
global $conn;
if($stmt = $conn->prepare("SELECT title, startDate, endDate FROM event"))
{
$stmt->execute();
$stmt->bind_result($title, $startDate, $endDate);
while ($stmt->fetch())
{
$rows[] = array('title' => $title, 'startDate' => $startDate, 'endDate' => $endDate);
}
$stmt->close();
echo json_encode($rows);
}
?>

The code should be modified as followed. The statement fetch method will return the next row and you have to catch it as follows. Also the columns are accessed as I have shown in the following code.
$rows=array();
while ($row=$stmt->fetch())
{
$rows[] = array('title' => $row['title'], 'startDate' => $row['startDate'], 'endDate' => $row['endDate']);
}

Try Below one in your while loop
'title' and 'start' must be there in event to load in calendar.
while ($stmt->fetch())
{
$rows[] = array('title' => $title, 'start' => date('Y-m-d H:i:s', strtotime($startDate)), 'end' => date('Y-m-d H:i:s', strtotime($endDate)));
}

Related

Display WordPress last posts via AJAX

I am building a news blog that upload posts every hour. I have created a shortcode that displays the last 15 posts on the home page. My problem was that the server cache needed to be deleted every hour. so I've decided to serve the post via AJAX so this area will get the latest posts every page load.
I found this answer and combine it whit my code.
My problem is that it displays all of the posts and not just 15.
PHP:
function get_ajax_posts() {
// Query Arguments
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => 15,
'nopaging' => true,
'order' => 'DESC',
'orderby' => 'date',
);
$ajaxposts = new WP_Query( $args );
$response = '';
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-parts/content-archive');
}
} else {
$response .= get_template_part('none');
}
echo $response;
exit; // leave ajax call
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
JS:
$.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html",
data: { action : 'get_ajax_posts' },
success: function( response ) {
$( '.home-hot-flights' ).html( response );
//hot-flights
var hot_flights_item = $(".home-hot-flights article").width() + 17;
$(".art-move-left").click(function () {
$('.move-right').addClass('show-move-right');
var leftPos = $('.home-hot-flights').scrollLeft();
$(".home-hot-flights").animate({scrollLeft: leftPos - hot_flights_item}, 200);
});
$(".art-move-right").click(function () {
var leftPos = $('.home-hot-flights').scrollLeft();
$(".home-hot-flights").animate({scrollLeft: leftPos + hot_flights_item}, 200);
});
}
});
This might help you:
Pagination parameters
(nopaging (boolean) – show all posts or use pagination. Default value
is ‘false’, use paging. )
Display all posts by disabling pagination:
$query = new WP_Query( array( 'nopaging' => true ) );
I think you should remove that parameter if you want to display a certain number of posts using posts_per_page.
Try this piece of code I have edit your code please see below
function get_ajax_posts() {
// Query Arguments
$args = array(
'post_type' => array('post'),
'post_status' => array('publish'),
'posts_per_page' => 15,
'order' => 'DESC',
'orderby' => 'date',
);
wp_reset_query();
$ajaxposts = new WP_Query( $args );
$response = '';
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-parts/content-archive');
}
} else {
$response .= get_template_part('none');
}
echo $response;
exit; // leave ajax call
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
If the two loops data is overwridden then, I your first code wp_reset_query() is incorrect. If you are using WP_Query then
wp_reset_postdata() //remove wp_reset_query() which is used for wp_query()
should be used after the end of the WHILE loop which means that in your two loops you have to have
wp_reset_postdata() // use this at both loops

Passing arrays with ajax to custom endpoints

I am using ajax to send data to a custom rest endpoint. I am doing this because i'm creating a filter function on my WP site.
Now I am stuck trying to get the tax_query to work with my array of terms collected with JS on the front end. No matter what I do I cant seem to get this to work, and I am strongly suspecting this is only a minor error that I keep overlooking...
Just to clarify, the ajax sends the request successfully but the query returns all posts no matter what.
Here is the checkboxes used on the front end:
<div class="form-group">
<?php
if( $terms = get_terms( array( 'taxonomy' => 'utst', 'hide_empty' => false, 'orderby' => 'name' ) ) ) :
foreach ( $terms as $term ) :
echo '<div class="form-check">';
echo '<label class="form-check-label" for="'.$term->slug.'"><input class="form-check-input" type="checkbox" id="'.$term->slug.'" name="utstyrAr[]" value="'.$term->term_id.'"> '.$term->name.'</label>'; // ID of the category as the value of an option
echo '</div>';
endforeach;
endif;
?>
</div>
The JS (ajax function):
filterOppdrag(fiOppdrag) {
var utst = [];
var utstyrArray = document.getElementsByName("utstyrAr[]");
for (var i = 0; i < utstyrArray.length; i++) {
if(utstyrArray[i].type =='checkbox' && utstyrArray[i].checked == true) utst.push(utstyrArray[i].value);
}
console.log(utst);
$.ajax({
url: the.root + '/wp-json/myfilter/v1/filter',
type: 'GET',
data: {
'checkUtst' : utst,
},
success: (response) => {
console.log(response);
},
error: (response) => {
console.log(response);
}
});
}
And the wp_query (php):
function myFilter ($data) {
$checkUtst = sanitize_text_field($data['checkUtst']);
//Main $args
$args = array(
'post_type' => 'ml_opp', // Query only "ml_opp" custom posts
'post_status' => 'publish', // Query only posts with publish status
'orderby' => 'date', // Sort posts by date
'order' => 'ASC' // ASC or DESC
);
// for taxonomies / utstyr
if( isset( $utstyr ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'ml_utst',
'field' => 'id',
'terms' => $checkUtst
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
This returns all the posts regardless of terms no matter what I pass through. I get no error messages and yes I have tested so that there is value in the array when I send it to the query. But what happens to it on the road there, I dont know. That's why i figure that Its probably just a rookie mistake I am making here.
Any help would be greatly appreciated!
Have you tried removing the wrapping array and not using a key?
$args = array(
'taxonomy' => 'ml_utst',
'field' => 'id',
'terms' => $checkUtst
);

Integrating Payment Gateway in ASP.NET

integration payment gateway in asp.net webform based website. sample code documentation examples are in php only.
I am not sure how to go forward as documentation doesnt seem to be of much help
https://telr.com/support/knowledge-base/hosted-payment-page-integration-guide/
<%# Page Language="C#" AutoEventWireup="true" CodeFile="PaymentProcess.aspx.cs" Inherits="PaymentProcess" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<style>
#telr {
width: 100%;
min-width: 600px;
height: 600px;
frameborder: 0;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<p> Enter You Credit Card Details Here</p>
<p><iframe id= " telr " src= " [url obtained from create order] " ></iframe></p>
<div>
</div>
</form>
<script type="text/javascript">
</script>
</body>
</html>
Any help or pointer is appreciated
UPDATE:
I am trying to using HTTPClient for same but i am not sure if i am doing it wring
protected void btn_Click(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
TelrObj obj = new TelrObj();
obj.ivp_method = "create";
obj.ivp_store = 12345;
obj.ivp_cart = "cardid1234";
obj.ivp_test = 1;
obj.return_auth = "xxxx-xxxx-xxx";
obj.return_can = "";
obj.return_decl = "";
obj.ivp_amount = 10;
obj.bill_fname = "David";
obj.ivp_currency = "USD";
var str = "{ 'method':'create', 'order':{ 'ref':'OrderRef', 'cartid':'cardid1234', 'test':1,'amount':10,'currency':'USD', 'url':'https://secure.telr.com/gateway/process.html?o=OrderRef' }";
var response = client.PostAsync("https://secure.telr.com/gateway/order.json",
new StringContent(JsonConvert.SerializeObject(str).ToString(),
Encoding.UTF8, "application/json"))
.Result;
Response.Write(response);
if (response.IsSuccessStatusCode)
{
dynamic content = JsonConvert.DeserializeObject(
response.Content.ReadAsStringAsync()
.Result);
// Access variables from the returned JSON object
var appHref = content.links.applications.href;
}
}
}
RESPONSE
StatusCode: 417, ReasonPhrase: 'Expectation Failed', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Connection: close Date: Tue, 17 Jan 2017 10:52:30 GMT Server: Apache Content-Length: 364 Content-Type: text/html; charset=iso-8859-1 }
I have changed return_auth & ivp_store as i cant share it. Any pointer to do it right would be of great help.
I am confused with there documentation so to do it right way. They dont seem to have any .net example on their website rather they have PHP Plugins which i don't understand.
I found another example for wooCommerce plugin which is in PHP
<?php
if (!defined('ABSPATH')) { exit; } // Exit if accessed directly
if (!defined('WP_CONTENT_URL')) { define('WP_CONTENT_URL', get_option('siteurl').'/wp-content'); }
if (!defined('WP_PLUGIN_URL')) { define('WP_PLUGIN_URL', WP_CONTENT_URL.'/plugins'); }
if (!defined('WP_CONTENT_DIR')) { define('WP_CONTENT_DIR', ABSPATH.'wp-content'); }
if (!defined('WP_PLUGIN_DIR')) { define('WP_PLUGIN_DIR', WP_CONTENT_DIR.'/plugins'); }
function telr_init() {
/**
* __construct function.
*
* #access public
* #return void
*/
class WC_Gateway_Telr extends WC_Payment_Gateway {
public function __construct() {
global $woocommerce;
$this->min_wc_ver="2.3.8";
$this->id = 'telr';
$this->has_fields = false; // No additional fields in checkout page
$this->method_title = __('Telr', 'woocommerce');
$this->method_description = __('Telr Checkout', 'telr-for-woocommerce');
$this->order_button_text = __( 'Proceed to Telr', 'telr-for-woocommerce' );
$this->woocom_ver = $woocommerce->version;
// Load the settings.
$this->init_form_fields(); // Config page fields
$this->init_settings();
if ($this->can_init()) {
$preload='<iframe style="width:1px;height:1px;visibility:hidden;display:none;" src="https://secure.telrcdn.com/preload.html"></iframe>';
$this->enabled = $this->get_config_option('enabled');
$this->title = $this->get_config_option('title');
$this->description = $this->get_config_option('description').$preload;
$this->store_id = $this->get_config_option('store_id');
$this->store_secret = $this->get_config_option('store_secret');
$this->testmode = $this->get_config_option('testmode');
$this->debug = $this->get_config_option('debug');
$this->order_status = $this->get_config_option('order_status');
$this->cart_desc = $this->get_config_option('cart_desc');
$this->form_submission_method = true;
$this->api_endpoint = 'https://secure.telr.com/gateway/order.json';
// Actions
add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this, 'process_admin_options'));
add_action( 'woocommerce_thankyou', array($this, 'update_order_status'));
} else {
$this->enabled = false;
}
}
private function can_init() {
if (version_compare(PHP_VERSION, '5.5.0') < 0) {
return false;
}
if (!function_exists('curl_version')) { return false; }
if (!function_exists('curl_init')) { return false; }
if (version_compare($this->woocom_ver,$this->min_wc_ver) < 0) {
return false;
}
return true;
}
public function update_order_status($order_id) {
global $woocommerce;
$order = new WC_Order( $order_id );
$order_check = $this->check_order($order_id);
if($order_check) {
$new_status = $this->sorder_status;
if (empty($new_status)) { $new_status="completed"; }
$order->update_status($new_status);
}
}
/**
* Process the payment and return the result.
*
* #access public
* #return array
*/
function process_payment($order_id) {
$order = new WC_Order($order_id);
$result = $this->generate_request($order);
$telr_ref = trim($result['order']['ref']);
$telr_url= trim($result['order']['url']);
if (empty($telr_ref) || empty($telr_url)) {
wc_add_notice('Payment API Failure, Please try again.', 'error');
} else {
update_post_meta( $order_id, '_telr_ref', $telr_ref);
}
return array(
'result' => 'success',
'redirect' => $telr_url,
);
}
public function generate_request($order) {
global $woocommerce;
$order_id = $order->id;
$cart_id = $order_id."_".uniqid();
$cart_desc=trim($this->cart_desc);
if (empty($cart_desc)) { $cart_desc='Order {order_id}'; }
$cart_desc = preg_replace('/{order_id}/i',$order_id,$cart_desc);
$test_mode = ($this->testmode == 'yes') ? 1 : 0;
$return_url = 'auto:'.add_query_arg('utm_nooverride','1',$this->get_return_url($order));
$cancel_url = 'auto:'.$order->get_cancel_order_url();
$data = array(
'ivp_method' => "create",
'ivp_source' => 'WooCommerce '.$woocommerce->version,
'ivp_store' => $this->store_id ,
'ivp_authkey' => $this->store_secret,
'ivp_cart' => $cart_id,
'ivp_test' => $test_mode,
'ivp_amount' => $order->order_total,
'ivp_currency' => get_woocommerce_currency(),
'ivp_desc' => $cart_desc,
'return_auth' => $return_url,
'return_can' => $cancel_url,
'return_decl' => $cancel_url,
'bill_fname' => $order->billing_first_name,
'bill_sname' => $order->billing_last_name,
'bill_addr1' => $order->billing_address_1,
'bill_addr2' => $order->billing_address_2,
'bill_city' => $order->billing_city,
'bill_region' => $order->billing_state,
'bill_zip' => $order->billing_postcode,
'bill_country' => $order->billing_country,
'bill_email' => $order->billing_email,
);
if (is_ssl() && is_user_logged_in()) {
$data['bill_custref'] = get_current_user_id();
}
$response = $this->api_request($data);
return $response;
}
public function check_order($order_id) {
global $woocommerce;
$order_ref = get_post_meta($order_id, '_telr_ref', true);
$data = array(
'ivp_method' => "check",
'ivp_store' => $this->store_id ,
'order_ref' => $order_ref,
'ivp_authkey' => $this->store_secret,
);
$response = $this->api_request($data);
$order_status_arr = array(2,3);
$transaction_status_arr = array('A', 'H');
if (array_key_exists("order", $response)) {
$order_status = $response['order']['status']['code'];
$transaction_status = $response['order']['transaction']['status'];
if ( in_array($order_status, $order_status_arr) && in_array($transaction_status, $transaction_status_arr)) {
return true;
}
}
return false;
}
public function api_request($data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->api_endpoint);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
$results = curl_exec($ch);
curl_close($ch);
$results = json_decode($results,true);
return $results;
}
/* ------------------------------ Admin setting page ------------------------------------------------ */
public function get_config_option($key) {
return $this->get_option($key);
}
public function admin_options() {
if ($this->can_init()) {
$this->show_admin_options();
} else {
$this->not_available();
}
}
public function not_available() {
?>
<div class="inline error"><p><strong><?php _e( 'Gateway Disabled', 'woocommerce' ); ?></strong>: <?php _e( sprintf('Requires WooCommerce %s or later, PHP 5.5 or later, and PHP cURL',$this->min_wc_ver), 'woocommerce' ); ?></p></div>
<?php
}
public function show_admin_options() {
// Admin Panel Options
$configured = true;
if ((empty($this->store_id)) || (empty($this->store_secret))) { $configured=false; }
?>
<h3><?php _e('Telr', 'woocommerce'); ?></h3>
<?php if (!$configured) : ?>
<div id="wc_get_started">
<span class="main"><?php _e('Telr Hosted Payment Page', 'woocommerce'); ?></span>
<span>Telr <?php _e('are a PCI DSS Level 1 certified payment gateway. We guarantee that we will handle the storage, processing and transmission of your customer\'s cardholder data in a manner which meets or exceeds the highest standards in the industry.', 'woocommerce'); ?></span>
<span><br><b>NOTE: </b> You must enter your store ID and authentication key</span>
</div>
<?php else : ?>
<p><?php _e('Telr Hosted Payment Page', 'woocommerce'); ?></p>
<?php endif; ?>
<table class="form-table">
<?php $this->generate_settings_html(); ?>
</table><!--/.form-table-->
<?php
}
// Admin settings fields
function init_form_fields() {
// Initialise Gateway Settings Form Fields
$this->form_fields = array(
'enabled' => array(
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'checkbox',
'label' => __('Enable Telr', 'woocommerce'),
'default' => 'yes'
),
'title' => array(
'title' => __('Title', 'woocommerce'),
'type' => 'text',
'description' => __('This controls the title which the user sees during checkout.', 'woocommerce'),
'default' => __('Credit/Debit card', 'woocommerce'),
'desc_tip' => true,
),
'description' => array(
'title' => __('Description', 'woocommerce'),
'type' => 'textarea',
'description' => __('This controls the description which the user sees during checkout.', 'woocommerce'),
'default' => __('Pay using a credit or debit card via Telr Secure Payments', 'woocommerce'),
'desc_tip' => true,
),
'cart_desc' => array(
'title' => __('Transaction description', 'woocommerce'),
'type' => 'text',
'description' => __('This controls the transaction description shown within the hosted payment page.', 'woocommerce'),
'default' => __('Your order from StoreName', 'woocommerce'),
'desc_tip' => true,
),
'store_id' => array(
'title' => __('Store ID', 'woocommerce'),
'type' => 'text',
'description' => __('Enter your Telr Store ID.', 'woocommerce'),
'default' => '',
'desc_tip' => true,
'placeholder' => '[StoreID]'
),
'store_secret' => array(
'title' => __('Authentication Key', 'woocommerce'),
'type' => 'text',
'description' => __('This value must match the value configured in the hosted payment page V2 settings', 'woocommerce'),
'default' => '',
'desc_tip' => true,
'placeholder' => '[Authentication Key]'
),
'testmode' => array(
'title' => __('Test Mode', 'woocommerce'),
'type' => 'checkbox',
'label' => __('Generate transactions in test mode', 'woocommerce'),
'default' => 'yes',
'description' => __('Use this whilst testing your integration. You must disable test mode when you are ready to take live transactions')
),
'order_status' => array(
'title' => __('Order Status', 'woocommerce'),
'type' => 'select',
'label' => __('Order status for authorised payments', 'woocommerce'),
'default' => 'processing',
'description' => __('Set the WooCommerce order status that will be used for authorised transations', 'woocommerce'),
'options' => array(
'processing' => __( 'Processing', 'woocommerce' ),
'completed' => __( 'Completed', 'woocommerce' )
)
)
);
}
}
}
if(!function_exists('telr_list_network_plugins')) {
function telr_list_network_plugins() {
if (!is_multisite()) {
return false;
$sitewide_plugins = array_keys((array) get_site_option('active_sitewide_plugins'));
}
if (!is_array($sitewide_plugins)) {
return false;
}
return $sitewide_plugins;
}
}
function add_telr_gateway($methods) {
$methods[] = 'WC_Gateway_Telr';
return $methods;
}
// Add plugin to wordpress/woocommerce
if ((in_array('woocommerce/woocommerce.php', (array)get_option('active_plugins'))) || (in_array('woocommerce/woocommerce.php', (array)telr_list_network_plugins()))) {
add_action('plugins_loaded', 'telr_init', 0);
add_filter('woocommerce_payment_gateways', 'add_telr_gateway');
}
?>
If I use Postman and send a following request to the https://secure.telr.com/gateway/order.json I'm getting HTTP 200:
POST /gateway/order.json HTTP/1.1
Host: secure.telr.com
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 570a44c1-9c4e-58b2-5d4d-fdd352272235
ivp_method=create&ivp_store=12345&ivp_authkey=12345&ivp_cart=12345&ivp_test=1&ivp_amount=100.00&ivp_currency=AED&ivp_desc=Description&return_auth=https%3A%2F%2Fdomain.com%2Freturn.html&return_can=https%3A%2F%2Fdomain.com%2Freturn.html&return_decl=https%3A%2F%2Fdomain.com%2Freturn.html
So I guess you're building your request in a wrong way(especially Content-Type which should be application/x-www-form-urlencoded, not application/json).
I cannot test it more since I don't ivp_store parameter, thus following response appears:
{
"method": "create",
"trace": "4001/18544/587dfa99",
"error": {
"message": "E04:Invalid store ID"
}
}
EDIT:
Here's working example:
static void Main(string[] args)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://secure.telr.com/");
client.DefaultRequestHeaders.ExpectContinue = false;
var result = client.PostAsync("gateway/order.json",
new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("ivp_method", "create"),
new KeyValuePair<string, string>("ivp_store", "12345"),
new KeyValuePair<string, string>("ivp_authkey", "12345"),
new KeyValuePair<string, string>("ivp_cart", "12345"),
new KeyValuePair<string, string>("ivp_desc", "Desc"),
new KeyValuePair<string, string>("ivp_test", "1"),
new KeyValuePair<string, string>("ivp_amount", "100.00"),
new KeyValuePair<string, string>("ivp_currency", "AED"),
new KeyValuePair<string, string>("return_auth", "https://wwww.google.pl"),
new KeyValuePair<string, string>("return_can", "https://wwww.google.pl"),
new KeyValuePair<string, string>("return_decl", "https://wwww.google.pl"),
})).Result;
Console.WriteLine(result.Content.ReadAsStringAsync().Result);
Console.ReadLine();
}
}
Note following line:
client.DefaultRequestHeaders.ExpectContinue = false;
which is required for this server. If you do not include this line and run my code, you will get following response:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>417 Expectation Failed</title>
</head><body>
<h1>Expectation Failed</h1>
<p>The expectation given in the Expect request-header
field could not be met by this server.
The client sent<pre>
Expect: 100-continue
</pre>
</p><p>Only the 100-continue expectation is supported.</p>
</body></html>
HttpClient by default sends a Expect: 100-continue header, which clearly messes with a server you're trying to connect.

Autocomplete data fields in CakePHP

I am new in CakePHP. I have a CakePHP (2.5.1) application which has streets table (with columns id, street_name, house_no, district, city). I need to autocomplete a form by extracting the table data. It should be like, the user will be typing a street name in the Street Name field of a form which has fields- Street Name, House No, District and City. After selecting a street name from auto suggestions, corresponding data (House No, District and City) will be populated in the other fields.
Now, over 25000 data rows are loaded in the streets table which is the entire street database of a city. it is a ClearDB database on Windows Azure. streets table is not linked with other tables of the application through foreign keys. I have Street model, StreetsController , but view is in different folder (app/View/User/add.ctp ). Street model in app/Model/Street.php is following:
class Street extends AppModel {
public function getStreetNames($term = null) {
if(!empty($term)) {
$streets = $this->find('list', array(
'conditions' => array(
'street_name LIKE' => trim($term) . '%'
)
));
return $streets;
}
return false;
}
}
In app/Controller/StreetsController.php,
class StreetsController extends AppController {
public $components = array('RequestHandler');
public function autocomplete($term){
if ($this->request->is('get')) {
$this->autoRender = false;
$data = $this->Street->getStreetNames($term);
$this->set(compact('data'));
$this->set('_serialize', array('data'));
echo json_encode($data);
}
}
}
In app/webroot/js/View/Users/streetdata.js file,
(function($) {
$('#autocomplete').autocomplete({
source: "/streetdata.json",
minLength: 1
});
})(jQuery);
The input forms are in different controller. In app/View/Users/streetdata.ctp file,
<?php
echo $this->Html->script('View/Users/streetdata', array('inline' => false));
?>
<?php echo $this->Form->create('Street', array(
'class' => 'form-horizontal',
'role' => 'form',
'inputDefaults' => array(
'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
'div' => array('class' => 'form-group'),
'class' => array('form-control'),
'label' => array('class' => 'col-lg-2 control-label'),
'between' => '<div class="col-lg-3">',
'style'=>array('width:200px; height:35px;'),
'after' => '</div>',
'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
))); ?>
<fieldset>
<legend><?php echo __('Street data '); ?></legend>
<?php
echo $this->Form->input('Street.street_name', array(
'class' => 'ui-autocomplete',
'id' => 'autocomplete'));
echo $this->Form->input('Street.house_no');
echo $this->Form->input('Street.district');
echo $this->Form->input('Street.city');
?>
</fieldset>
<?php echo $this->Form->end(__('Proceed')); ?>
in View/Layouts/default.ctp, i have added followings
echo $this->Html->script('jquery.js');
echo $this->Html->script('bootstrap.min');
echo $this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');
echo $this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array('inline' => false));
echo $this->Html->script('https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', array('inline' => false));
echo $this->Html->css('https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css');
echo $this->Html->css('font-awesome.min');
echo $this->Html->css('bootstrap.min');
echo $this->Html->meta('icon');
echo $this->fetch('meta');
echo $this->fetch('css');
echo $this->fetch('script');
echo $this->Html->charset();
But the autocomplete fields (street name and others) are not working.
I found following error messages in the console of chrome browser :
-Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:26949/Users/js/jquery.js
-Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:26949/Users/js/bootstrap.min.js
-Uncaught TypeError: Cannot read property 'offsetWidth' of undefined bootstrap.min.js:6
I am struggling to find a solution. Could anyone tell me please what is wrong here ? is it because of the location of .js file ? am i missing anything here?

Google Charts and JSON data

I'm not a JS guy, I working on a small interface for my weather station. I have a serverside code which generates the JSON data for the graph. It looks like this:
[
{
"temperature": "32.1",
"humidity": "91",
"battery": "100",
"time": "2016-02-21 15:28:56"
},
{
"temperature": "32.1",
"humidity": "99.3",
"battery": "100",
"time": "2016-02-21 15:28:47"
},
{
"temperature": "22.2",
"humidity": "70.2",
"battery": "88.2",
"time": "2016-02-21 15:28:19"
},
{
"temperature": "21.2",
"humidity": "88.1",
"battery": "90.4",
"time": "2016-02-21 15:28:22"
}
]
How can I feed this data into a Line chart using Google's Chart API? I have tried using the example but it does not work. (https://developers.google.com/chart/interactive/docs/gallery/linechart)
First define your array in the format which google charts requires:
$resultsarray = array(
'cols' => array(
array('label' => 'temperature', 'type' => 'number'),
array('label' => 'humidity', 'type' => 'number'),
array('label' => 'battery', 'type' => 'number'),
array('label' => 'time', 'type' => 'date'),
),
'rows' => array()
);
Then add the data to your array:
$resultsarray['rows'][] = array('c' => array( array('v'=> 'tempvalue'), array('v'=>'humidityval'), array('v'=>'batteryval'),array('v'=>'timeval')));
Encode as JSON and write to a file:
$fp = fopen('data.json', 'w');
//JSON encode and write array to file
fwrite($fp, json_encode($resultsarray, JSON_NUMERIC_CHECK));
fclose($fp);
Then in your JavaScript you need: (as per Google Example)
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
Then the contents of getdata.php (as per google example)
<?php
// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.
$string = file_get_contents("data.json");
echo $string;
// Instead you can query your database and parse into JSON etc etc
?>
The json isn't formatted properly. Google charts expect a specific json type for its chart. I'm assuming that your database is mysql. If not, I can always modify the following code. I have created a small library to perform these annoying tasks. So here it is :
<?php
function generate_GChart_cols($result) {
$fieldcount = mysqli_num_fields($result);
$stringVal = [253]; // MySQL field type codes -See http://php.net/manual/en/mysqli-result.fetch-field-direct.php
$numericVal = [246, 8]; // MySQL field type codes -See http://php.net/manual/en/mysqli-result.fetch-field-direct.php
$colsarray = array();
for ($i = 0; $i < $fieldcount; $i++) {
$finfo = mysqli_fetch_field_direct($result, $i);
switch ($finfo->type) {
case in_array($finfo->type, $stringVal):
$type = 'string';
break;
case in_array($finfo->type, $numericVal):
$type = 'number';
break;
default:
$type = 'string';
}
// Constructs the column array
$colsarray[] = array(
'label' => $finfo->name,
'type' => $type
);
}
return $colsarray;
}
function generate_GChart_rows($result) {
$fieldcount = mysqli_num_fields($result);
$rows = array();
while ($r = $result->fetch_row()) {
$temp = array();
for ($j = 0; $j < $fieldcount; $j++) {
$temp[] = array(
'v' => $r[$j]
);
}
$rows[] = array(
'c' => $temp
);
};
return $rows;
}
?>
A usage example would be :
<?php
header('content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin:*'); //Include this header to make the requests cross-origin
include 'dbconnect.php';
include 'generate_google_json.php';
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = // Your query here - e.g SELECT * FROM TABLE // ;
$result = $conn->query($sql);
$table['data']['rows'] = generate_GChart_rows($result); // Call to function to generate rows
$table['data']['cols'] = generate_GChart_cols($result); // Call to function to generate columns
$conn->close(); // Close db connection
// We echo the json and enforce a numeric check on the values
echo $_GET['callback'] . '(' . json_encode($table, JSON_NUMERIC_CHECK) . ')';
?>
An example output would be :
?(
{
data:{
rows:[
{
c:[
{
v:3123600
},
{
v:3116452
}
]
}
],
cols:[
{
label:2013,
type:"number"
},
{
label:2014,
type:"number"
}
]
}
}
)
In the event where you use other types than bigint, varchart and decimal, you might wanna add more values to the $stringVal and $numericVal arrays :)
Cheers
Google charts is expecting the JSON in this format:
{
"cols": [
{"id":"","label":"temperature","pattern":"","type":"number"},
{"id":"","label":"humidity","pattern":"","type":"number"},
{"id":"","label":"battery","pattern":"","type":"number"},
{"id":"","label":"time","pattern":"","type":"date"}
],
"rows": [
{"c":[{"v":"32.1","f":null},{"v":99.3,"f":null},{"v":100,"f":null},{"v":2016-02-21 15:28:47,"f":null}]}
]
}

Categories