I am new to PHP and MySQL, so this task really keeps me struggling:
I have an MySQL database which contains a lot of geo coordinates which shall be extracted by php, transformed to JSON format to pass them to JavaScript and then be displayed in Leaflet's heatmap.
I already wrote the JS code, and the AJAX seems to be functioning. But Heatmap does not seem to be accepting my array containing the coordinates. I can't see where I made an mistake; I think my PHP array is not formatted in the right way.
Heatmap needs to get its data in this format:
var testData = {
max: 8,
data: [{lat: 24.6408, lng:46.7728, count: 1},{lat: 50.75, lng:-1.55, count: 1}, ...]
};
This is my code by now:
var geoData;
function loadData() {
alert("loading Data");
getJSON();
}
function getJSON() {
$.ajax({
url: "assets/php/readGeoData.php",
type: "GET",
datatype: "json",
success: function(data) {
alert("ajax transfer successful ");
geoData = data;
//For debugging:
alert(getGeoData());
}
})
}
function getGeoData() {
return geoData;
}
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin="" />
<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
<!-- Leaflet Heatmap JS -->
<script src="assets/js/Leaflet.heat-gh-pages/dist/leaflet-heat.js"></script>
<!-- map CSS -->
<link rel="stylesheet" href="assets/css/map.css" />
<!-- map JS -->
<script src="assets/js/mymap.js"></script>
<!-- main CSS -->
<link rel="stylesheet" href="assets/css/main.css" />
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- data JS -->
<script src="assets/js/loadGeoData.js"></script>
</head>
<body>
<h1>movementprofile</h1>
<button id="importButton">import geoData</button>
<div id="mapid"></div>
<script>
$("#importButton").click(function() {
loadData();
});
</script>
<!-- creating the map -->
<script>
var mymap = L.map('mapid').setView([51.25, 10.5], 6);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=' + mapboxToken, {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(mymap);
</script>
<script>
var heatmapData = {
max: 8,
data: getGeoData()
};
var heatmapLayer = new HeatmapOverlay(cfg);
heatmapLayer.setData(8, getGeoData());
</script>
</body>
</html>
PHP:
<?php
$db = new PDO('mysql:host=127.0.0.1;dbname=movementprofile;', 'root', *****);
$query ='SELECT longitude, latitude FROM movementprofile WHERE longitude IS NOT NULL AND latitude IS NOT NULL';
foreach ($db->query($query) as $row) {
print_r($row);
$longitude = $row['longitude'];
$latitude = $row['latitude'];
$singleDataset = array('lon' => $longitude,'lat' => $latitude, 'count'=> 1);
array_push($datasets,$singleDataset, JSON_FORCE_OBJECT);
echo json_encode($datasets);
}
This is the array I get right now (in the JS alert box):
Array
(
[longitude] => 13.39611111
[0] => 13.39611111
[latitude] => 52.52944444
[1] => 52.52944444
)
nullArray
(
[longitude] => 13.37472222
[0] => 13.37472222
[latitude] => 52.53027778
[1] => 52.53027778
)
nullArray
(
[longitude] => 13.38361111
[0] => 13.38361111
[latitude] => 52.53
[1] => 52.53
)
//... and so on, there are more than 30.000 entries
So, how do I get this array to look like the one Heatmap needs?
EDIT:
So I edited my PHP to this:
foreach ($db->query($query) as $row) {
print_r($row);
$longitude = $row['longitude'];
$latitude = $row['latitude'];
$singleDataset = array('lon' => $longitude,'lat' => $latitude, 'count'=> 1);
array_push($datasets,json_encode($singleDataset));
But still got this array:
Array
(
[longitude] => 13.39611111
[0] => 13.39611111
[latitude] => 52.52944444
[1] => 52.52944444
)
//and so on
# thinsoldier
Did you mean that?
First thing I see in your code is that you do print_r($row); - remove or comment that.
Also maybe take a look at my php connector how to create geojson (example connects with postgres but you can simply rewrite that to mysql and adjust to your database structure):
<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=pguser user=pguser password=pass");
$result = pg_query($dbconn, "SELECT * FROM test");
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
while($row = pg_fetch_assoc($result)) {
$feature = array(
'id' => $row['id'],
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array($row['latitude'], $row['longitude'])
),
# Pass other attribute columns here
'properties' => array(
'test' => 'test',
'column1' => $row['column1'],
'column2' => $row['column2']
)
);
# Add feature arrays to feature collection array
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
?>
EDIT
Because you want to get specific structure of json, not geoJson with features, above code may be simplified to:
....
$json = array(
'max' => '8',
'data' => array()
);
while($row = pg_fetch_assoc($result)) {
$data = array(
'lat' => $row['latitude'],
'lng' => $row['longitude'],
'count' => '1',
);
# Add feature arrays to feature collection array
array_push($json['data'], $data);
}
header('Content-type: application/json');
echo json_encode($json, JSON_NUMERIC_CHECK);
....
Related
This is my server side code
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
use Slim\Http\Request;
use Slim\Http\Response;
use Stripe\Stripe;
require 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();
require './config.php';
$app = new \Slim\App;
$app->add(function ($request, $response, $next) {
Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
return $next($request, $response);
});
$app->get('/', function (Request $request, Response $response, array $args) {
return $response->write(file_get_contents(getenv('STATIC_DIR') . '/index.html'));
});
$app->post('/checkout_sessions', function(Request $request, Response $response) use ($app) {
$params = json_decode($request->getBody());
$payment_method_types = [
'usd' => ['card'],
'eur' => ['card'],
'cad' => ['card']
];
$products = [
'cause-a' => 'prod_KP3YP2a3IGYqsb',
'cause-b' => 'prod_KP3iZRGcEjn5W8',
];
$session = \Stripe\Checkout\Session::create([
'success_url' => 'http://localhost:4242/success.html?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => 'http://localhost:4242/?cancel=true',
'mode' => 'payment',
'payment_method_types' => $payment_method_types[$params->currency],
'metadata' => [
'cause' => $params->cause,
'currency' => $params->currency,
],
'submit_type' => 'donate',
'line_items' => [[
'price_data' => [
'currency' => $params->currency,
'product' => $products[$params->cause],
'unit_amount' => $params->amount,
],
'quantity' => 1,
]]
]);
return $response->withJson([
'id' => $session->id
]);
});
$app->get('/order', function (Request $request, Response $response) {
$id = $_GET['sessionId'];
$checkout_session = \Stripe\Checkout\Session::retrieve($id);
echo json_encode($checkout_session);
});
$app->run();
this is the success page with javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Order Confirm</title>
</head>
<body>
<div id="main">
<div id="checkout">
<div id="payment-forum">
<h1>Success</h1>
payment status: <span id="payment-status"></span>
<pre>
</pre>
</div>
</div>
</div>
</body>
<script>
var paymentStatus = document.getElementById('payment-status');
var urlParams = new URLSearchParams(window.location.search);
var sessionId = urlParams.get("session_id")
if (sessionId) {
fetch("/order?sessionId=" + sessionId).then(function(result){
return result.json()
}).then(function(session){
var sessionJSON = JSON.stringify(session, null, 2);
document.querySelector("pre").textContent = sessionJSON;
}).catch(function(err){
console.log('Error when fetching Checkout session', err);
});
}
</script>
</html>
i need help with product detail , customer name , amount on success page and if possible payment paid or not paid status on it.... cant find any tutorial on it or any detail step by step guide on it
i am close but cant get it to bullseyes please help me with it
yeah on success page all i get is payment status and blank
Looks like here is what happened:
Your Checkout Session defined success_url to success.html
Your success.html fired another request to "/success?session_id=xxx"
Your backend handled this with $app->get('/success', function...
It could be confusing to name both HTML in step 2 and the handling URL in step 3 as "success". You may want to use a different name such as "success" and "get-checkout-session" like Stripe example on Github. After that, debug your server log on step 3 to see whether you got the session id correctly and have retrieved the Customer Id.
There is more information to extract from a CheckoutSession. See Stripe's API Reference on available properties. You probably want to expand its payment_intent to see the amount and payment status.
I have a website where when the user clicks a canvas, he draws on it and it gets pushed into the database. And it draws for every user 10 times in one second.
setInterval(function(){
$.ajax({
url: 'data/canvasSave.php',
success: function(data) {
$('.result').html(data);
console.log(data);
imageCanvas = data;
}
});
let img = new Image();
img.src = imageCanvas;
context.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0 , 0, canvas.width, canvas.height);
}, 100);
Now I notice that this isn't the best way. But is there a good way to check for Database updates?
I tried a few if statements but none of them really worked.
You can use PHP sockets for tracking MySQL Database changes with WebSockets.
Setup Frontend
File: index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MySQL Tracker</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit#3.7.4/dist/css/uikit.min.css" />
</head>
<body>
<div class="uk-container uk-padding">
<h2>Users</h2>
<p>Tracking users table with WebSockets</p>
<table class="uk-table">
<thead>
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
</thead>
<tbody>
<?php
$connection = mysqli_connect(
'localhost',
'root',
PASSWORD,
DB_NAME
);
$users = mysqli_query($connection, 'SELECT * FROM users');
while ($user = mysqli_fetch_assoc($users)) {
echo '<tr>';
echo '<td>' . $user['id'] . '</td>';
echo '<td>' . $user['name'] . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
</body>
</html>
Next, add the PieSocket-JS WebSocket library in your HTML file with the following code:
Now, we are ready to connect to the WebSocket channel and start receiving instantaneous updates from the server. Add the following code to your index.php file to make a websocket connection.
<script>
var piesocket = new PieSocket({
clusterId: 'CLUSTER_ID',
apiKey: 'API_KEY'
});
// Connect to a WebSocket channel
var channel = piesocket.subscribe("my-channel");
channel.on("open", ()=>{
console.log("PieSocket Channel Connected!");
});
//Handle updates from the server
channel.on('message', function(msg){
var data = JSON.parse(msg.data);
if(data.event == "new_user"){
alert(JSON.stringify(data.data));
}
});
</script>
Setup Backend
Let’s create a file called admin.php which adds an entry to the user’s table, every time it is visited.
<?php
$connection = mysqli_connect(
'localhost',
'root',
PASSWORD,
DB_NAME
);
mysqli_query($connection, "INSERT INTO users .....");
?>
The code snippet given above adds an entry in the users table every time its execute either via CLI or from a webserver.
Use the following PHP function to do that.
<?php
function publishUser($event){
$curl = curl_init();
$post_fields = [
"key" => "PIESOCKET_API_KEY",
"secret" => "PIESOCKET_API_SECRET",
"channelId" => "my-channel",
"message" => $event
];
curl_setopt_array($curl, array(
CURLOPT_URL => "https://PIESOCKET_CLUTER_ID.piesocket.com/api/publish",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($post_fields),
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
print_r($response);
}
$connection = mysqli_connect(
'localhost',
'root',
PASSWORD,
DB_NAME
);
mysqli_query($connection, "INSERT INTO users .....");
$payload = json_encode([
"event" => "new_user",
"data" => [
"id"=> 1,
"name"=>"Test user"]
]);
publishUser($payload);
?>
Track MySQL changes in real-time with Laravel
For example, in your User model under app/model/User.php add the following code block
public static function boot() {
parent::boot();
static::created(function($user) {
publishUser(json_encode($user));
});
}
Track MySQL changes in real-time with Django
import requests
import json
url = "https://CLUSTER_ID.piesocket.com/api/publish"
payload = json.dumps({
"key": "API_KEY",
"secret": "API_SECRET",
"channelId": 1,
"message": { "text": "Hello world!" }
});
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
I have code to get some data (terms = page-a) built with Wordpress.
Currently, the data of page-a is acquired like'terms' =>'page-a' and displayed on the example.com/page-a page.
I would like to change this data acquisition code so that the data along the lower page url can be acquired (for example, the data on page-b at example.com/page-b).
I created a code to get the url with $_SERVER and convert it, but I can't get the url because I am using ajax. I want to get the url with javascript and pass it to php.
How should I make the changes?
functions.php
add_action('wp_ajax_get_case', 'dk_get_case');
add_action('wp_ajax_nopriv_get_case', 'dk_get_case');
function dk_get_case() {
$headers['Access-Control-Allow-Origin'] = '*';
$return = ['status' => false, 'data' => [], 'message' => ''];
$case_clinics = [1,2,3,4];
foreach($case_clinics as $key => $case_clinic){
// (1)Get the current URL
$http = is_ssl() ? 'https' : 'http' . '://';
$url = $http . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
// (2)Get a string such as'page-a' from the URL
$keys = parse_url($url);
$path = explode("/", $keys['path']);
$terms = $path[2];
$dk_posts = get_posts(
array(
'showposts' => -1,
'post_type' => 'case',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'case_clinic',
'field' => 'term_id',
'terms' => $case_clinic
),
array(
'taxonomy' => 'case_category',
'field' => 'slug',
'terms' => 'page-a'
)
)
)
);
taxonomy-case_category-page-a.php
<div class="col case-right">
<h3 style="font-family:'Futura PT'; font-weight:600">Clinic</h3>
<h4 style="font-weight:600">Clinic</h4>
//data display position
<div class="case-img" data-slider-3></div>
<div class="popup"></div>
</div>
Tried
footer.php
<script>
jQuery(document).ready(function () {
var url = window.location.href;
$.ajax({
type: "GET",
url: "taxonomy-case_category-page-a.php",
data: {"url": url},
});
});
taxonomy-case_category-page-a.php
<?php var_dump($_GET['url']); ?>
error
GET: 404error
https://example.com/pagea/taxonomy-case_category-page-a.php?url=https%3A%2F%2Fcharme-beauty.jp%2Fstaging%2Fcase%2Fpagea%2F
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
);
I'm having problems with CGridView and one custom Formatter that uses javascript. When CGridView triggers an ajax request of any kind, my Formatter that works with javascript stops working.
Let's try one trivial example:
The Formatter
class DFormatter extends CFormatter {
public function formatTest(){
$js = <<<EOD
console.log("test");
EOD;
$cs = Yii::app()->getClientScript();
$cs->registerScript("testjs", $js);
return false;
}
}
The view:
<?php $this->widget('zii.widgets.grid.CGridView',
array(
'id' => 'development-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
array(
'name' => 'testField',
'type' => 'test',
),
array(
'class' => 'CButtonColumn',
),
),
)); ?>
After the first Ajax Request, the javascript code used in the formatter stops working, How can I get my javascript code works after every ajax call made by CGridView Widget?
Thanks.
You should not put scripts in the formatter.
Remove:
$js = <<<EOD
console.log("test");
EOD;
$cs = Yii::app()->getClientScript();
$cs->registerScript("testjs", $js);
Configure your grid view:
<?php $this->widget('zii.widgets.grid.CGridView', array(
//.. other options
// ADD THIS
'afterAjaxUpdate' => 'function() { afterAjaxUpdate(); }',
Add to <head> of /layouts/main.php:
<script src="<?= Yii::app()->getBaseUrl(true); ?>/js/myCustomJS.js"></script>
Create new JS file at /js/myCustomJS.js:
function afterAjaxUpdate() {
// do your formatting here
}