Geolocation script issues - php

I've some issues with a geolocation script I'm working on and maybe someone could help me here :).
For this script I have 4 files :
functions.js:
function geolocation(){
GMaps.geolocate({
success: function(position) {
var userLat = position.coords.latitude;
var userLng = position.coords.longitude;
var dataString = 'userLat='+userLat+'&userLng='+userLng;
$.ajax({
type : 'POST',
url : 'getEvents.php',
data : dataString,
dataType : 'text',
success : function(msg){
console.log(msg);
}
});
},
error: function(error) {
alert('Echec de la localisation...');
},
not_supported: function() {
alert('Votre navigateur ne supporte pas la géolocalisation...');
}
});
}
index.php:
<?php require 'php/getEvents.php'; ?>
<!DOCTYPE html>
<html lang="fr">
<?php include('inc/head.html'); ?>
<body>
<div class="mosaic">
<?php echo visitorMosaicBox($data); ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
geolocation();
});
</script>
</body>
</html>
getEvents.php:
<?php
session_start();
require 'db-connect.php';
require 'lib.php';
$userLat = $_POST['userLat'];
$userLng = $_POST['userLng'];
$area = 10;
$i = 0;
$data = array();
if($userLat != '' && $userLng != ''){
if(isset($_SESSION['id'])){
echo 'Logged';
}else{
try{
$sql = "SELECT restaurants.cover, restaurants.name, restaurants.address, restaurants.location, restaurants.zip, events.title, events.trailer, events.id
FROM events
LEFT JOIN restaurants ON restaurants.id = events.fk_restaurants";
$req = $db->query($sql);
}catch(PDOException $e){
echo 'Erreur: '.$e->getMessage();
}
while($res = $req->fetch()){
$fetchAddress = $res['address'].', '.$res['zip'].' '.$res['location'];
$fixedAddress = str_replace(' ','+',$fetchAddress);
$geocode = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$fixedAddress.'&sensor=false');
$output = json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$lng = $output->results[0]->geometry->location->lng;
$distance = distance($userLat, $userLng, $lat, $lng, false);
if($distance <= $area){
$data[$i] = array(
"id" => $res['id'],
"name" => $res['name'],
"cover" => $res['cover'],
"address" => $fetchAddress,
"title" => $res['title'] ,
"trailer" => $res['trailer'],
);
$i++;
}
}
}
}else{
$data = 'ERROR';
}
?>
lib.php :
<?php
function visitorMosaicBox($array){
for($i=0; $i<sizeOf($array);$i++){
$html = '<div class="box" id="box-'.$i.'">';
$html .= '<img src="'.$array[$i]['cover'].'" alt="'.$array[$i]['name'].'" />';
$html .= '<span class="ribbon"></span>';
$html .= '<div class="back"></div>';
$html .= '<div class="infos" id="event-'.$array[$i]['id'].'">';
$html .= '<p class="msg"></p>';
$html .= '<div class="txt-1">';
$html .= '<span class="sits"><span class="dinners">5</span></span>';
$html .= '<h3>'.$array[$i]['title'].'<span class="block">'.$array[$i]['name'].'</span></h3>';
$html .= '<ul class="actions">';
$html .= '<li>Partager</li>';
$html .= '<li>Participer</li>';
$html .= '<li class="last">Info</li>';
$html .= '</ul>';
$html .= '</div>'; // Fin de .txt-1
$html .= '<div class="txt-2">';
$html .= '<h3>'.$array[$i]['title'].'</h3>';
$html .= '<p>'.$array[$i]['trailer'].'</p>';
$html .= 'Fermer';
$html .= '</div>'; // Fin de .txt-2
$html .= '</div>'; // Fin de .infos
$html .= '</div>'; // Fin de .box
return $html;
}
}
?>
So now what's that's supposed to do...
1/ functions.js geolocates the visitor, gets his coordonates (lat,lng) and send them to my getEvents.php
2/ getEvents.php receives the coordonates from functions.js, and compare them with the results from the database.
3/ If the distance between the result and the user is lower than the area (10) then I store all the datas from the result in my array $data.
4/ The function visitorMosaicBox() creates as many divs as there are results in my array.
5/ In index.php, I simply call visitorMosaicBox() by passing my array $data.
My problem is that no divs are created even if there are results. I receive the visitor's coordonates in my getEvents.php file but in my index.php file the coordonates doesn't exists.
Does anyone know why my coordonates can't pass from my getEvents.php file to my index.php file please ? Any solution ?
If I split my script in these 4 files it's because I'll need to do other stuffs on my getEvents.php file depending on the visitor is connected or not, etc...
Thanks and sorry for this long question.
Antho

Related

Dynamic ID with JQUERY functions

I have a problem with my JQUERY code. Here's the code:
$maxcounter = $( '.testimonio-popup[id^="popup-"]' ).length;
var i = 0;
while (i < $maxcounter) {
$('#open-'+i).on('click', function() {
$('#popup-'+i).fadeIn('slow');
$('.testimonio-overlay').fadeIn('slow');
$('.testimonio-overlay').height($(window).height());
return false;
});
$('#close-'+i).on('click', function(){
$('#popup-'+i).fadeOut('slow');
$('.testimonio-overlay').fadeOut('slow');
return false;
});
i++;
}
It takes correctly the total of times the .testimonio-popup div is appearing in the site, and the fadeIn action for .testimoniooverlay class works.
But the fadeIn action for #popup-[number] is not working. Any help why?
For further assistance, I attach the PHP code that makes the query:
function get_the_content_with_formatting ($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
return $content;
}
add_shortcode( 'testimonios', 'display_testimonios' );
function display_testimonios($atts){
$atributos = shortcode_atts([ 'grupo' => 'PORDEFECTO', ], $atts);
$buffer = '<div class="testimonio-overlay"></div> ';
$contadorid = 0;
$q = new WP_Query(array(
'post_type' => 'test',
'tax_query' => array(
array(
'taxonomy' => 'grupos_testimonios',
'field' => 'slug',
'terms' => $atributos['grupo']
//'terms' => 'grupo-1'
)
)
) );
while ($q->have_posts()) {
$q->the_post();
$buffer .= '<div class="testimonio">';
$buffer .= '<div class="testimonio-img">' . get_the_post_thumbnail($_post->ID).'</div>';
$buffer .= '<div class="testimonio-titulo"><p>' . get_the_title() .'</p></div>';
$buffer .= '<div class="testimonio-intro"><div class="testimonio-parrafo">' . get_the_excerpt() . '</div><button class="testimonio-boton" id="open-'.$contadorid.'">Leer más</button></div></div>';
$buffer .= '<div class="testimonio-popup" id="popup-'.$contadorid.'"><div class="testimonio-popup-contenido"><div class="testimonio-cerrar"><button class="testimonio-boton-cerrar" id="close-'.$contadorid.'">x</button></div>';
$buffer .= '<div class="testimonio-popup-titulo"><p>' . get_the_title() .'</p></div>';
$buffer .= '<div class="testimonio-popup-contenido">' . get_the_content_with_formatting() . '</div></div></div>';
$contadorid = $contadorid + 1;
}
wp_reset_postdata();
return $buffer;
}
Thank you!
Frede
#Rory McCrossan is right (see comment).
I'm not sure what goes wrong there, but I would suggest you change this logic:
$("#open-1").on(....);
$("#open-2").on(....);
$("#open-3").on(....);
$("#close-1").on(....);
$("#close-2").on(....);
$("#close-3").on(....);
$("#popup-1").fadeIn()
$("#popup-2").fadeIn()
to using classes and attributes:
$(".popup-handler").on(.. check if open/close -> then action..);
$(".popup").filter(.. check for specific reference..).fadeIn()
And if you want to interact elements with different classes, add data attributes to them so you can find them when needed. Here is a simple example:
<!-- popup nr 1 -->
<div class="popup-handler" data-rel="1" data-action="open"></div>
<div class="popup" data-rel="1">
<div class="popup-handler" data-rel="1" data-action="close"></div>
</div>
<!-- popup nr 2 -->
<div class="popup-handler" data-rel="2" data-action="open"></div>
<div class="popup" data-rel="2">
<div class="popup-handler" data-rel="2" data-action="close">x</div>
</div>
<!-- jQuery -->
$(".popup-handler").on("click", function() {
/* get popup reference & action */
var rel = $(this).data("rel"),
action = $(this).data("action");
/* find the target popup */
var $popup = $(".popup").filter("[data-rel=" + rel + "]");
if (action == "open") {
$popup.fadeIn("slow");
/* ... other code when opening a popup... */
}
if (action == "close") {
$popup.fadeOut("slow");
/* ... other code when closing a popup... */
}
});
Demo here - 4 popups, working: jsfiddle
(Defining the same functions inside a while loop is generally a bad idea.)

Shortcode is not working correctly if it is used more then one time in a same page

I have created one shortcode to return a tab content and it is working fine
if I am using one time in a page.But if want one more on this same page it is not working. I have tried in several way but its not giving fruits.
Here is the code
if($tab_box == 'tab_box_1' && $tabs_lay == 'awavc-tabs-pos-left') {
$add_class = rand(99,9999);
$q = rand(99,99999);
$html .= '
<div class="awavc-tabs awavc-tabs-'.$add_class.' '.$tabs_lay.' '.$tab_style.' awavc-tabs-response-to-icons '.$el_class.' ">';
$i = 1;
foreach($tab_contents as $tab_content){
$tab_lable = 'Lable';
$tab_icon = '';
if(!empty($tab_content['tab_lbl'])){$tab_lable = $tab_content['tab_lbl'];}
if(!empty($tab_content['icon'])){$tab_icon = $tab_content['icon'];}
$html .= ' <input type="radio" name="awavc-tabs" checked id="awavc-tab-'.$i.'" class="awavc-tab-content-'.$i.'">
<label for="awavc-tab-'.$i.'"><span><span style="font-size:'.$lable_size.'px;color:'.$lable_clr.';"><i class="'.$tab_icon.'" style="font-size:'.$lable_size.'px;color:'.$icon_clr.';"></i>'.$tab_lable.'</span></span></label>';
$i++;
}
$html .= '
<ul>';
$i = 1;
foreach($tab_contents as $tab_content){
$tab_title = 'Title';
$content = '';
if(!empty($tab_content['title'])){$tab_title = $tab_content['title'];}
if(!empty($tab_content['content'])){$content = $tab_content['content'];}
$html .= '<li class="awavc-tab-content-'.$i.'">
<div class="typography">';
if(!empty($tab_title)){ $html .= '<h1 style="font-size:'.$ttl_size.'px;color:'.$ttl_clr.';">'.$tab_title.'</h1>';}
$html .= '
<p style="font-size:'.$content_size.'px;color:'.$content_clr.';font-style:'.$content_style.';">'.$content.'</p>
</div>
</li>';
$i++;
}
I have tried something like $i.$add_class but...
If you want to use the shortcode multiple times on the same page do it like so:
add_shortcode("fmg_shortcode", "fmg_callback");
function fmg_callback($args) {
ob_start();
$html = "";
//your code here
echo $html;
return ob_get_clean();
}

PHP concatenation not working properly

So i'm trying to build a pagination for my website without refreshing the page.
I'm using ajax, php and mysql for that purpose.
At the moment i'm stuck with php, specifically with foreach and concatenation.
Here's my foreach loop:
if (isset($_POST['page'])) {
$algus = $_POST['page'];
$loos = '';
$mitu = 5;
$msg = [];
foreach (uritused($conn, $id, $algus, $mitu) as $key => $vals) {
$loos .= "<tr class='tr-data'>";
$loos .= '<td>'.$vals['eventi_nimi'].'<br><span class="owner" data-id="'.$vals['owner-id'].'">'.$vals['owner'].'</span></td>';
$loos .= '<td data-loosiaeg="'.$vals['loosiAeg'].'">'.$vals['loosiAeg'].'</td>';
$loos .= '<td>'.$vals['attendiloos'].'</td>';
$loos .= '<td>';
if (is_array($vals['auhinnad'])) {
foreach($vals['auhinnad'] as $keys => $val){
$loos .= $val['auhind'].'<br>';
}
} else {
$loos .= $vals['auhinnad'];
}
$loos .= '</td>';
$loos .= '<td>Postitus: '.$vals['tingimused']['postitus'].'<br>Osalus: '.$vals['tingimused']['osalus'].'</td>';
$loos .= '<td>';
if (is_array($vals['valista'])) {
foreach($vals['valista'] as $keys => $val){
$loos .= $val['nimi'].'<br>';
}
} else {
$loos .= $vals['valista'];
}
$loos .= '</td>';
$loos .= '<td data-sec='.$vals['sec'].' class="tr-icons">
<i class="material-icons staatus ' . $vals['staatus'] . '" data-staatus="'.$vals['staatus'].'" data-toggle="tooltip" data-placement="bottom" data-class="stopped" data-eltext="radio_button_checked" data-text="radio_button_unchecked" title="Peata loosimine">radio_button_checked</i></td>';
$loos .= "</tr>";
}
$msg['data'] = $loos;
$msg['success'] = true;
echo json_encode($msg);
}
Here's my ajax call
var page = 1;
$.ajax({
type: "POST",
url: "pages/php/loosid_data.php",
cache: false,
dataType: 'json',
data: {'page': page},
success: function(msg){
console.log(msg);
if(msg['success']){
$('.tr-data').remove();
$('.m-loosid table').append(msg['data']);
}
},
error: function(msg){
console.log(msg);
}
});
EDIT: Heres the function
function uritused($conn, $id, $algus, $mitu){
try{
$uritused = $conn->prepare("SELECT COUNT(*) FROM loosid WHERE usr_id='$id'");
$uritused->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$uritus_arr = [];
$count = $uritused->fetchColumn();
if($count > 0){
try{
$urituseds = $conn->prepare("SELECT * FROM loosid WHERE usr_id='176237127636' ORDER BY loosiAeg DESC LIMIT 1, 5");
$urituseds->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$uritus = $urituseds->fetchAll();
for ($z=0;$z<$count;$z++) {
$uritus_arr[$z] = array(
'eventi_nimi' => $uritus[$z]['eventi_nimi'],
'loosiAeg' => $uritus[$z]['loosiAeg'],
'tingimused' => array(
'postitus' => $uritus[$z]['post'],
'osalus' => $uritus[$z]['osalus']
),
'sec' => $uritus[$z]['sec'],
'staatus' => $uritus[$z]['staatus'],
'attendiloos' => $uritus[$z]['attendiloos']
);
$auhinnad = explode(',', $uritus[$z]['auhinnad']);
if($uritus[$z]['auhinnad'] != '-'){
foreach ($auhinnad as $key) {
$auhind = explode('-', $key);
$auhinna_arr[] = array(
'auhind' => $auhind[0],
'voitjad' => $auhind[1]
);
}
$uritus_arr[$z]['auhinnad'] = $auhinna_arr;
}else{
$uritus_arr[$z]['auhinnad'] = $uritus[$z]['auhinnad'];
}
$valista = explode(',', $uritus[$z]['valista']);
if($uritus[$z]['valista'] != '-'){
foreach ($valista as $keys) {
$valistad = explode('-', $keys);
$valista_arr[] = array(
'nimi' => $valistad[0],
'id' => $valistad[1]
);
}
$uritus_arr[$z]['valista'] = $valista_arr;
}else{
$uritus_arr[$z]['valista'] = $uritus[$z]['valista'];
}
$valista_arr = [];
$auhinna_arr = [];
}
}
return $uritus_arr;
}
THIS NOW GIVES ME UNDEFINED OFFSET, ALTHOUGH I KNOW THAT THERE'S DATA WITH THAT INFO IN THE DB.
For some reason the data is always empty.
Whenever i try to run this same code inside my page directly without ajax, everything works as it should.
Maybe you guys have any suggestions on how to fix this? I know that there's already same kind of posts out here but i haven't found my answer yet.
#Gino Pane
I'm sorry but thats not the case actually. It seems that i made a rookie mistake with my query. I have only one instance of data in the database but my limit is set to 1, 5 but it should be 0, 5.
Basically my query was looking data from the database starting at 1 when it should've started at 0. Thats why it seemed to me that there is no data in the database.
I also said that when i echo foreach directly on the page it works because i had more than 1 instance of data in the database at that time.
Sorry for wasting your time guys.

How to display product details without page being refreshed

I am developing a website using php & MySQL, i have two functions
1. Grab data from database,
2. display HTML view codes with a link to view individual product details using $_GET variable.
Everything works perfectly. But i want the product details to load without the page being refreshed. I understand Ajax is capable in handling the task but i am not knowledgeable in Ajax. Any assistance would be appreciated.
Below are my codes example:
//Main product view
function product_view($product) {
$output = "";
$output = $output . '<li class="col-sx-12 col-sm-3">';
$output = $output . '<div class="product-container">';
$output = $output . ' product name';
$output = $output . '----';
$output = $output . '----';
$output = $output . '----';
$output = $output . '</div>';
$output = $output . '</li>';
return $output;
}
//Main product display
function get_products() {
require(ROOT_PATH ."inc/db_connect.php");
$sql = "SELECT * FROM products WHERE status='Active'";
$query = mysqli_query($db_connect, $sql);
return $query;
}
//View page
$products = get_products();
if (!empty($products)) {
foreach ($products as $product) {
echo product_view($product);
}
}
To use AJAX as suggested in some comments of your question, you can use this sample code in your client side:
$(document).ready(function(){
$.ajax({
url: 'products.php',
method: 'GET'
}).then(function(data){
for(int i=0; i < data.length; i++){
$('body').append('<li class="col-sx-12 col-sm-3"><div class="product-container>...'+data[i].attribute+'</div></li>');
//append all information that you need
}
})
});
at your backend you need to return the JSON so:
$products = get_products();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($products);

dynamically changing CSS background-image

I'm fairly new to both PHP and Javascript, so please forgive my ignorance and poor use of terminology, but I'll do my best to explain exactly what I'm struggling to achieve.
I have information stored in a PHP array that I call to my index page using the function below (the code below is in a separate PHP file called articles.php that's included in my index.php) :
<?php
function get_news_feed($article_id, $article) {
$output = "";
$output .= '<article class="img-wrapper">';
$output .= '<a href="article.php?id=' . $article_id . '">';
$output .= '<div class="news-heading">';
$output .= "<h1>";
$output .= $article["title"];
$output .= "</h1>";
$output .= "<p>";
$output .= "Read more...";
$output .= "</p>";
$output .= "</div>";
$output .= '<div id="news-img-1">';
$output .= "</div>";
$output .= "</a>";
$output .= "</article>";
return $output;
}
$articles = array();
$articles[] = array(
"title" => "Andy at NABA",
"description" => "Docendi, est quot probo erroribus id.",
"img" => "img/gym-01.jpg",
"date" => "05/04/2013"
);
$articles[] = array(
"title" => "Grand Opening",
"description" => "Docendi, est quot probo erroribus id.",
"img" => "img/gym-01.jpg",
"date" => "05/04/2013"
);
?>
My index.php looks like the following minus some HTML that plays no role in this process:
<?php
include("inc/articles.php");
?>
<?php
$pageTitle = "Home";
include("inc/header.php");
?>
<section class="col-4 news">
<?php
$total_articles = count($articles);
$position = 0;
$news_feed = "";
foreach($articles as $article_id => $article) {
$position = $position + 1;
if ($total_articles - $position < 2) {
$news_feed .= get_news_feed($article_id, $article);
}
}
echo $news_feed;
?>
</section>
I am aiming to dynamically change the CSS Background-Image property of the div element with ID news-img-1 using Javascript.
I have tried such things as:
document.getElementById('news-img-1').style.backgroundImage = 'url('<?php $article["img"]; ?>')';
document.getElementById('news-img-1').style.backgroundImage = 'url('http://www.universalphysique.co.uk/' + '<?php $article["img"]; ?>')';
document.getElementById('news-img-1').style.backgroundImage = 'url('window.location.protocol + "//" + window.location.host + "/" + '<?php $article["img"]; ?>')';
.....but I'm getting nowhere!! My code in practise works because the following Javascript inserts an image correctly:
document.getElementById('news-img-1').style.backgroundImage = 'url("img/gym-01.jpg")';
Here is my site up and running, the images should be placed in the empty circles you'll see! Any help would be great, this ones tough for me!!
comparing the hard coded javascript to ones that don't work, I notice that you are not including the double-quotes around the <?php $article["img"]; ?> snippet. The hard coded one shows
= 'url("img/gym-01.jpg")'
but the ones with the php snippet will produce
= 'url(img/gym-01.jpg)'
so perhaps if you modify it to
document.getElementById('news-img-1').style.backgroundImage = 'url("'<?php $article["img"]; ?>'")';
OR
edit the get_news_feed function as follows:
replace these lines
$output .= '<div id="news-img-1">';
$output .= "</div>";
with
$output .= '<div class="news-img"><img src="' . $article["img"] . '"></div>' ;
and change your css like so:
article.img-wrapper {
position: relative;
}
div.news-img {
position: absolute;
top: 0;
z-index: -1000;
}
OR
Modify your get_news_feed function, change the statement for the <div id="news-img-1"> output to include a data-url attribute like:
$output .= '<div class="news-img" data-url="' . $article["img"] . '">';
Then add a jquery statement like:
$(".news-img").each( function() {
$(this).css("background-image", "url(" + $(this).data("url") +")" );
});
The jquery statement goes in a static js file as opposed to generating the script in php.
You need to remove the quotes from your PHP tags and see if it works!
Do it like this:
document.getElementById('news-img-1').style.backgroundImage = 'url(' + <?php $article["img"]; ?> + ')';
Hope it helps.

Categories