How to get a php array index and use it in javascript - javascript

I have a PHP script that returns a latitude and longitude from the database.
Then I have a Javascript loop that loops according to the number of rows the PHP query returns and populate my data object with the logitude and latitude at a given index. The challenge now is - how do I get the index without hard coding it?
PHP
$DBhost = 'localhost';
$DBuser = 'root';
$DBpass = '';
$DBname = 'symptoms';
$con = mysqli_connect($DBhost, $DBuser, $DBpass) or die(mysql_error());
mysqli_select_db($con, $DBname);
$query = mysqli_query($con, 'SELECT latitude,longitude FROM markers') or die(mysql_error());
$longArr = array();
$latArr = array();
$count = 0;
while ($row = mysqli_fetch_array($query)) {
$lat = $row['latitude'];
$lon = $row['longitude'];
$latArr[$count] = $lat;
$longArr[$count] = $lon;
++$count;
}
JavaScript
var latArr = [];
var longArr = [];
var markersD = [];
var num = <?php echo $count ?>;
for (var i = 0; i < num; i++) {
var data = {
lat: '<?php echo $latArr[1]?>',
lon: '<?php echo $longArr[1]?>'
}
console.log(data);
}

You have to create json object via php
while($row = mysqli_fetch_array($query))
{
$json[] = array('lat' => $row['latitude'], 'lon' => $row['longitude']);
}
$json_string = json_encode($json);
=== JS ===
var data = <?php echo json_string; ?>;
console.log(data);

You can put all your coords in one array
$coords = array();
while($row = mysqli_fetch_array($query))
{
$coords[] = array(
'latitude' => $row['latitude'],
'longitude' => $row['longitude'],
)
}
and pass it to the js as a JSON object
var data = <?php echo json_encode($coords) ?>;
console.log(data);
All data you need should be available in the javascript

Related

For each loop with JavaScript and PHP generating markers in LeafLet

I am trying to loop through my SQL result with PHP and JavaScript to set markers on a LeafLet Map. The Data contains the name, latitude, longitude and number.
Here is my code:
var ticker = <?php echo mysqli_num_rows($result); ?>;
for ( let i = 0; i < ticker; i++) {
var latitude = <?php echo json_encode($row["latitude"]); ?>;
var longitude = <?php echo json_encode($row["longitude"]); ?>;
var marker = L.marker([latitude, longitude]).addTo(map);
var popup = <?php echo json_encode($row["name"] . " " . $row["number"]); ?>;
marker.bindPopup(popup);
}
It should add two markers, but somehow it only generates one marker with the data from the first entry.
Ok i found a solution. Thanks for any help!
PHP
$result = $conn->query($sql);
$values = [];
while($value = mysqli_fetch_array($result, MYSQLI_NUM)) {
$values[] = $value;
}
JavaScript
var data = <?php echo json_encode($values); ?>;
for ( let i = 0; i < data.length; i++) {
var name = data[i][0];
var lat = data[i][1];
var lon = data[i][2];
var ums = data[i][3];
var popup = name + ums;
var marker = L.marker([lat, lon]).addTo(map);
marker.bindPopup(popup);
}

Get JSON Array into another file via Ajax

I'm trying to add a JSON array from a separate file into another array in my main page via Ajax. For some reason my Ajax is not working, There are 4 arrays, I need to store each of them in separate arrays in my main page. This is what I got.
load file:
<?php
session_start();
if(!isset($_SESSION['usersId']))
{
header("Location: ../index.php");
exit();
}
else
{
include_once 'includes/dbh.inc.php';
}
$id = $_SESSION['userId'];
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT sensor1, sensor2, sensor3 FROM `$id`;";
$result = mysqli_query($conn, $sql);
$jsonsensor1 = array();
$jsonsensor2 = array();
$jsonsensor3 = array();
$jsonsensorsum = array();
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
$jsonsensor1[] = intval($row['sensor1'] * ($p = pow(10, 2))) / $p;
$jsonsensor2[] = intval($row['sensor2'] * ($p = pow(10, 2))) / $p;
$jsonsensor3[] = intval($row['sensor3'] * ($p = pow(10, 2))) / $p;
$jsonsensorsum[] = intval(($row['sensor1'] + $row['sensor2'] + $row['sensor3']) * ($p = pow(10, 2))) / $p;
}
}
echo json_encode($jsonsensor1);
echo json_encode($jsonsensor2);
echo json_encode($jsonsensor3);
echo json_encode($jsonsensorsum);
?>
Output from the load file:
[5,10,10.99,10.99,13,5,14.31,1,1,5,5,5,1,5,3,3,5,5,1,5,10.32,10.32,5,8,5,10,5,5,19,5,7.36,7.36,5,12.2,12.2,2.2,2.2,23.3,5,10.87,6.87,6.87,5,5,10,10,10,10,5,5,5,5,5,0,5,5]
[8,12.5,12.5,12.53,12.53,8,10.11,1,1,8,8,8,1,8,3,3,8,8,1,8,12.83,32.32,8,8,8,10,8.31,8,10,8,18.2,18.2,8,10.3,10.3,2.29,2.29,12.3,8,8.23,2.23,2.23,8,8,10,10,10,20,5,5,5,5,8,0,8,2]
[6,8.86,8.86,8.87,8.87,6,8.33,1,2,6,2,3,1,6,3,8,6,6,1,6,8.32,7.32,6,8,6,10,3.31,6,12,6,12.3,12.3,6,11.1,11.1,4.09,4.09,33.1,6,5.16,12.16,2.16,6,6,10,20,30,30,30,30,5,0,6,0,6,5]
[19,31.36,32.36,32.4,34.4,19,32.76,3,4,19,15,16,3,19,9,14,19,19,3,19,31.47,49.96,19,24,19,30,16.62,19,41,19,37.86,37.86,19,33.6,33.6,8.6,8.6,68.7,19,24.26,21.26,11.26,19,19,30,40,50,60,40,40,15,10,19,0,19,12]
What I tried in my main page:
$(document).ready(function(){
$.getJSON("loadchart.php", function(jsonsensor1){
var sensor1 = [$jsonsensor1];
var sensor2 = [$jsonsensor2];
var sensor3 = [$jsonsensor3];
var sensorsum = [$jsonsensorsum];
});
});
Don't use multiple encode/echo calls. This will just create invalid json. Instead put your data into a single container(an object or array) and encode echo that.
For instance using a normal array:
$data = [$jsonsensor1,$jsonsensor2,$jsonsensor3,$jsonsensorsum];
echo json_encode($data);
And on the front end access them accordingly
$.getJSON("loadchart.php", function(data){
//get the arrays based on what position you put them
//in the array in the backend
//change this if you end up using a different container,
//eg php associative array or object
var sensor1 = data[0];
var sensor2 = data[1];
//and so on
});
Replace this code :
echo json_encode($jsonsensor1);
echo json_encode($jsonsensor2);
echo json_encode($jsonsensor3);
echo json_encode($jsonsensorsum);
With this code :
$data=array("jsonsensor1"=>$jsonsensor1,"jsonsensor2"=>$jsonsensor2,"jsonsensor3"=>$jsonsensor3,"jsonsensorsum"=>$jsonsensorsum);
echo json_encode($data);

Parse returned 2D-Array from PHP-Script to Javascript-Variable inside a Wordpress-Codeblock

So I have a standard php-script, which is stored in an external php-file that is located on the server in the main folder (in this case /html/mysite/getlocations.php).
<?php
function getData() {
// MySQL-Connection-Variables
$servername = "xxxxxxxxxx.hosting-data.io";
$username = "xxxxxxxxxxxxxxxxxx";
$password = "xxxxxxxxxxxxxx";
$dbname = "xxxxxxxxxxxx";
// Create connection
$conn = mysqli_connect( $servername, $username, $password, $dbname );
$conn_number = mysqli_connect( $servername, $username, $password, $dbname );
// Check connection
if ( !$conn ) {
die( "Connection failed: " . mysqli_connect_error() );
}
// SQL-Query for Locations
$sql = "SELECT ID, Beschreibung, Straße, Hausnummer, PLZ, Ort, Bezirk, Leiter, Email, Telefon, Website FROM Locations";
//SQL-Query for Number of Entries
$sql_number = "SELECT COUNT(*) FROM Locations;"
$result = mysqli_query( $conn, $sql );
// Size of MySQL-Table
$size = mysqli_query( $conn_number, $sql );
$counter = 0;
// 2D-Array with all the needed informations for further processing
$returnarray = array();
// Number of Table-Entries > 0
if ( mysqli_num_rows( $result ) > 0 ) {
// Iterate over all Entries
while ( $row = mysqli_fetch_assoc( $result ) ) {
$desription = $row[ "Beschreibung" ];
$street = $row[ "Straße" ];
$number = $row[ "Hausnummer" ];
$plz = $row[ "PLZ" ];
$city = $row[ "Ort" ];
$bezirk = $row[ "Bezirk" ];
$leiter = $row[ "Leiter" ];
$email = $row[ "Email" ];
$phone = $row[ "Telefon" ];
$website = $row[ "Website" ];
$returnarray[$counter] = array();
$returnarray[$counter]['name'] = $desription;
$returnarray[$counter]['street'] = $street;
$returnarray[$counter]['number'] = $number;
$returnarray[$counter]['plz'] = $plz;
$returnarray[$counter]['city'] = $city;
$returnarray[$counter]['bezirk'] = $bezirk;
$returnarray[$counter]['leiter'] = $leiter;
$returnarray[$counter]['email'] = $email;
$returnarray[$counter]['telefon'] = $telefon;
$returnarray[$counter]['website'] = $website;
$counter = $counter + 1;
}
}
// Close connection
mysqli_close( $conn );
return $returnarray;
}
echo getData();
?>
This php-scripts connects to a mysql-database, fetches information and stores it in a twodimensional array.
Now I want to retrieve this returned array and put it in a javascript-variable, so I can use it for further processing inside a Wordpress-Codeblock.
So my attempt was this:
<script type="text/javascript">
var data_from_ajax;
$.get('/html/mysite/getlocations.php', function(data) {
data_from_ajax = data;
});
</script>
But this didnt work like I intended it would.
You can create a JSON string using PHP's built-in json_encode function and parse it in JS with JSON.parse.
I don't think you can pass variables directly to Javascript without serialization.

ajax error, the data is burried

this is my code
main.js
var save_method, table;
//Menerapkan plugin datatables
$(function(){
table = $('.table').DataTable({
"processing" : true,
"ajax" : {
"url" : "ajax/ajax_user.php?action=table_data",
"type" : "POST"
}
});
});
ajax_user.php
<?php
include "../config/database.php";
include "../library/view.php";
if ($_GET['action'] == "table_data") {
$query = mysqli_query($mysqli, "SELECT p.*, v.nama_provinsi, k.nama_kota, j.nama_tagihan FROM pelanggan P
INNER JOIN provinsi v ON p.id_provinsi = v.id_provinsi
INNER JOIN kota k ON p.id_kota = k.id_kota
INNER JOIN jenis_tagihan j ON p.id_jenis_tagihan = j.id_jenis_tagihan
ORDER BY p.id DESC");
$data = array();
$no = 1;
while($p = mysqli_fetch_assoc($query)) {
$row = array();
$row[] = $no;
$row = $p['nama_masjid'];
$row = $p['nama_pengurus'];
$row = $p['id_pelanggan'];
$row = $p['tagihan'];
$row = $p['nama_provinsi'];
$row = $p['nama_kota'];
$row = $p['nama_tagihan'];
$data[] = $row;
$no++;
}
$output = array("data" => $data);
echo json_encode($output);
}
?>
and this is my error
The last data in the array appears but the previous data disappears what's wrong ?
try this :
$data = [];
$i=0;
while($p = mysqli_fetch_assoc($query)) {
$data[$i]['nama_masjid'] = $p['nama_masjid'];
$data[$i]['nama_pengurus']= $p['nama_pengurus'];
$i++;
}
echo json_encode($data);

XML not parsing in jQuery

When I try to parse my PHP-generated XML file using the jQuery Feeds plugin, it doesn't do what it's supposed to - loop through the template below and output the XML <title> tag in the place of <!=title!>. Instead, it returns just one instance of the template with nothing in place of <!=title!>.
Nothing is returned in the Chrome JavaScript console.
Strangely, I have a similar PHP-generated XML file that works just fine.
Here's the jQuery I'm using:
$('.feed').feeds({
feeds: {
feed1: 'http://www.comfyshoulderrest.com/scrape.php?id=1' // this one doesn't work
},
//max: 3,
loadingTemplate: '<h1 class="feeds-loader">Loading items...</h1>',
entryTemplate: '<div class="item"><div class="image"><img src="images/tie.jpg" style="width: 100%;"></div>' +
'<div class="text"><ul class="list-inline">' +
'<li><span class="price text-warning"><strong>£7.00</strong></span> <span class="text-muted"><strike>£14.00</strike></span></li>' +
'<li class="text-muted"><strong>Topman</strong></li></ul>' +
'<!=title!>' +
'</div></div>'
});
Here's the code that generates the XML file:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country) {
header("Content-Type: application/xml; charset=UTF-8");
$xml = new SimpleXMLElement('<rss/>');
$xml->addAttribute("version", "2.0");
$channel = $xml->addChild("channel");
$channel->addChild("product_url", $product_url);
$channel->addChild("shop_name", $shop_name);
$channel->addChild("photo_url", $photo_url);
$channel->addChild("was_price", $was_price);
$channel->addChild("now_price", $now_price);
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html)) {
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i]
);
$item = $channel->addChild("item");
$item->addChild("product_url", $result['product_url']);
$item->addChild("shop_name", $result['shop_name']);
$item->addChild("photo_url", $result['photo_url']);
}
//print_r($result);
}
else
{
echo "this is empty";
}
echo $xml->asXML();
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result)) {
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location - $row['was_price_location'];
$now_price_location - $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
}
mysqli_close($con);
?>

Categories

Resources