I am trying to pass a php array to a javascript variable as an object to use in google maps on the same page/file. I am not able to send out an alert when testing the array in javascript.
PHP
while( $row = $query->fetch_assoc() ){
$street_address = $row['street_address'];
$zip = $row['zip'];
$state = $row['state'];
$lat = $row['lat'];
$lng = $row['lng'];
$test = $row['sellerDB_test'];
$firstName = $row['first_name'];
$lastName = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
/* Each row is added as a new array */
$locations = array( 'streetAddress'=>$street_address, 'state'=>$state, 'zip'=>$zip, 'lat'=>$lat, 'lng'=>$lng, 'test'=>$test, 'first name'=>$firstName, 'last name'=>$lastName, 'email'=>$email, 'phone'=>$phone);
JS
var map;
var Markers = {};
var infowindow;
var locations = '<?php echo json_encode($locations); ?>';
var location = JSON.parse(loactions);
alert(locations[0]);
I am getting this error
Uncaught ReferenceError: loactions is not defined
at account:299
#Ghost is right. I did not notice that the $locations is inside while loop. So You should define $locations = []; before while loop.
And then keep adding multiple records from while loop. So the updated code should be like:
$locations = [];
while( $row = $query->fetch_assoc() ){
$street_address = $row['street_address'];
$zip = $row['zip'];
$state = $row['state'];
$lat = $row['lat'];
$lng = $row['lng'];
$test = $row['sellerDB_test'];
$firstName = $row['first_name'];
$lastName = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];
/* Each row is added as a new array [] */
$locations[] = array( 'streetAddress'=>$street_address, 'state'=>$state, 'zip'=>$zip, 'lat'=>$lat, 'lng'=>$lng, 'test'=>$test, 'first name'=>$firstName, 'last name'=>$lastName, 'email'=>$email, 'phone'=>$phone);
}
And after this, you should put the JS code snippet.
And use it like this:
JS cpde:
var map;
var Markers = {};
var infowindow;
var locations = <?php echo json_encode($locations); ?>;
var location = JSON.parse(loactions);
alert(location.streetAddress);
Related
I've been trying to get data from my database into a table on my website using js/php but I can't get the php to give a valid xml to the script.
This is the php code:
<?php
$serverName = "localhost";
$userName = "***";
$password = "***";
$DBName = "DataBase1";
// Connect to DB
$connection = mysqli_connect($serverName, $userName, $password, $DBName);
if (!$connection)
{
die("Connection failed: " . mysqli_connect_error());
} else {
//echo "Connected to DB<br>";
}
// Collect data
$selectionSD = $connection->query("SELECT * FROM `SensorData`");
$selectionSL = $connection->query("SELECT * FROM `SensorLog`");
// Generating XML file
//$xmlSD = new XMLWriter();
//$xmlSD->openUri("php://output");
//$xmlSD->startDocument();
//$xmlSD->setIndent(true);
//$xmlSD->startElement("SensorDataTable");
//while ($row = mysqli_fetch_assoc($selectionSD))
//{
// $xmlSD->startElement("SensorData");
// $xmlSD->startElement("ID");
// $xmlSD->writeRaw($row["ID"]);
// $xmlSD->endElement();
// $xmlSD->startElement("SID");
// $xmlSD->writeRaw($row["SID"]);
// $xmlSD->endElement();
// $xmlSD->startElement("Value");
// $xmlSD->writeRaw($row["Value"]);
// $xmlSD->endElement();
// $xmlSD->startElement("Comment");
// $xmlSD->writeRaw($row["Comment"]);
// $xmlSD->endElement();
// $xmlSD->startElement("DateTime");
// $xmlSD->writeRaw($row["DateTime"]);
// $xmlSD->endElement();
// $xmlSD->endElement();
//}
//$xmlSD->endElement();
//header("Content-type: text/xml");
//$xmlSD->flush();
//$xmlSD->endDocument();
// Test code
$document = new DOMDocument('1.0', 'utf-8');
$document->formatOutput = true;
$root = $document->createElement('SensorDataTable');
$root = $document->appendChild($root);
while ($row = mysqli_fetch_assoc($selectionSD))
{
$node = $document->createElement('SensorData');
$node = $root->appendChild($node);
// ID
$dataNode = $document->createElement('ID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["ID"]);
$data = $dataNode->appendChild($data);
// SID
$dataNode = $document->createElement('SID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["SID"]);
$data = $dataNode->appendChild($data);
// Value
$dataNode = $document->createElement('Value');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Value"]);
$data = $dataNode->appendChild($data);
// Comment
$dataNode = $document->createElement('Comment');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Comment"]);
$data = $dataNode->appendChild($data);
// DateTime
$dataNode = $document->createElement('DateTime');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["DateTime"]);
$data = $dataNode->appendChild($data);
}
echo $document->saveXML();
// Close DB connection
$connection->close();
?>
I've tried to generate the xml a different way but no luck (the commented lines was what I tried first).
To get the xml into a table I use js with this code:
console.log(xml);
let i;
const xmlDoc = xml.responseXML;
if (xmlDoc === null) {
console.log("Failed to get response.");
}
let table = "<tr><th>SID</th><th>Value</th></tr>";
const x = xmlDoc.getElementsByTagName("SensorData");
for (i = 0; i < x.length; i++) {
table += "<tr><td class='center'>" +
x[i].getElementsByTagName("SID")[0].childNodes[0].nodeValue +
"</td><td class='center'>" +
x[i].getElementsByTagName("Value")[0].childNodes[0].nodeValue +
"</td></tr>";
}
console.log("Changing DB display");
document.getElementById("DB").innerHTML = table;
Where xml = the path to the php file.
When trying to run this it gives an error that xmlDoc is null. If I run this using an actual xml file on my drive it works fine.
If I call the php file directly and inspect the source it shows this:
<?xml version="1.0" encoding="utf-8"?>
<SensorDataTable>
<SensorData>
<ID>1</ID>
<SID>1</SID>
<Value>19.50</Value>
<Comment>DHT_Temp</Comment>
<DateTime>2021-10-04 12:57:51</DateTime>
</SensorData>
<SensorData>
<ID>2</ID>
<SID>2</SID>
<Value>57.50</Value>
<Comment>DHT_Humi</Comment>
<DateTime>2021-10-04 12:57:55</DateTime>
</SensorData>
<SensorData>
<ID>3</ID>
<SID>1</SID>
<Value>19.60</Value>
<Comment>DHT_Temp</Comment>
<DateTime>2021-10-04 12:58:29</DateTime>
</SensorData>
<SensorData>
<ID>4</ID>
<SID>2</SID>
<Value>57.20</Value>
<Comment>DHT_Humi</Comment>
<DateTime>2021-10-04 12:58:32</DateTime>
</SensorData>
</SensorDataTable>
How can I fix this issue, I’ve searched the web but the solutions I've come across did not work (creating the xml in a different way for example).
Fixed: change in the php code, added header("Content-type: text/xml"); back:
<?php
$serverName = "localhost";
$userName = "***";
$password = "***";
$DBName = "LIDAc";
// Connect to DB
$connection = mysqli_connect($serverName, $userName, $password, $DBName);
if (!$connection)
{
die("Connection failed: " . mysqli_connect_error());
}
// Collect data
$selectionSD = $connection->query("SELECT * FROM `SensorData`");
$selectionSL = $connection->query("SELECT * FROM `SensorLog`");
// Generate XML file
$document = new DOMDocument('1.0', 'utf-8');
$document->formatOutput = true;
$root = $document->createElement('SensorDataTable');
$root = $document->appendChild($root);
while ($row = mysqli_fetch_assoc($selectionSD))
{
$node = $document->createElement('SensorData');
$node = $root->appendChild($node);
// ID
$dataNode = $document->createElement('ID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["ID"]);
$data = $dataNode->appendChild($data);
// SID
$dataNode = $document->createElement('SID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["SID"]);
$data = $dataNode->appendChild($data);
// Value
$dataNode = $document->createElement('Value');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Value"]);
$data = $dataNode->appendChild($data);
// Comment
$dataNode = $document->createElement('Comment');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Comment"]);
$data = $dataNode->appendChild($data);
// DateTime
$dataNode = $document->createElement('DateTime');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["DateTime"]);
$data = $dataNode->appendChild($data);
}
header("Content-type: text/xml");
echo $document->saveXML();
// Close DB connection
$connection->close();
?>
I have a code that can get the Amazon product price if you gave it's "ASIN" (It's Amazon product identification number)... below you can find the code (I don't think there is a need to read the code anyway).
<?php
class AmazonAPI {
var $amazon_aff_id;
var $amazon_access_key;
var $amazon_secret_key;
var $url_params;
var $itemID;
var $xml;
var $operation;
var $signature;
var $response_groups = "Small,Images,OfferSummary";
var $error_message;
var $error=0;
public function __construct($affid, $access, $secret)
{
$this->amazon_aff_id = $affid;
$this->amazon_access_key = $access;
$this->amazon_secret_key = $secret;
}
public function build_url()
{
$url = "http://webservices.amazon.com/onca/xml?";
$this->response_groups = str_replace(",", "%2C", $this->response_groups);
$url_params = "AWSAccessKeyId=" . $this->amazon_access_key;
$url_params .= "&AssociateTag=" . $this->amazon_aff_id;
if(!empty($this->itemID)) {
$url_params .= "&ItemId=" . $this->itemID;
}
$url_params .= "&Operation=" . $this->operation;
$url_params .= "&ResponseGroup=" . $this->response_groups;
$url_params .= "&Service=AWSECommerceService";
$url_params .= "&Timestamp=" . rawurlencode(gmdate("Y-m-d\TH:i:s\Z"));
$url_params .= "&Version=2013-08-01";
$this->url_params = $url_params;
$url .= $url_params;
$url .= "&Signature=" . $this->generate_signature();
return $url;
}
public function generate_signature()
{
$this->signature = base64_encode(hash_hmac("sha256",
"GET\nwebservices.amazon.com\n/onca/xml\n" . $this->url_params,
$this->amazon_secret_key, True));
$this->signature = str_replace("+", "%2B", $this->signature);
$this->signature = str_replace("=", "%3D", $this->signature);
return $this->signature;
}
public function item_lookup($id)
{
$this->operation = "ItemLookup";
$this->itemID = $id;
$url = $this->build_url();
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
curl_close($ch);
$this->xml = simplexml_load_string($output);
return $this;
}
public function check_for_errors()
{
if(isset($this->xml->Error)) {
$this->error_message = $this->xml->Error->Message;
$this->error = 1;
}
if(isset($this->xml->Items->Request->Errors)) {
$this->error_message = $this->xml->Items->Request->Errors->Error->Message;
$this->error = 1;
}
return $this->error;
}
public function get_item_price($product)
{
$price = 0;
if(isset($product->LowestNewPrice)) {
$price = $product->LowestNewPrice->Amount;
} elseif(isset($product->LowestUsedPrice)) {
$price = $product->LowestUsedPrice->Amount;
} elseif(isset($product->LowestCollectiblePrice)) {
$price = $product->LowestCollectiblePrice->Amount;
} elseif(isset($product->LowestRefurbishedPrice)) {
$price = $product->LowestRefurbishedPrice->Amount;
}
return $price;
}
public function get_item_data()
{
if($this->check_for_errors()) return null;
$product = $this->xml->Items->Item;
$item = new STDclass;
$item->detailedPageURL = $product->DetailPageURL;
$item->link = "https://www.amazon.com/gp/product/".$this->itemID."/?tag=" . $this->amazon_aff_id;
$item->title = $product->ItemAttributes->Title;
$item->smallImage = $product->SmallImage->URL;
$item->mediumImage = $product->MediumImage->URL;
$item->largeImage = $product->LargeImage->URL;
$item->price = $this->get_item_price($product->OfferSummary);
return $item;
}
}
?>
Then i echo the price with this code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup("ASIN")->get_item_data();
echo $item->price;
Now if i have a csv sheet like this
https://ibb.co/dHS4EK
can i update the prices on column D and E given the asin found on column B and C,
so for example the value of cell D2 will get it using the following code
$amazon = new AmazonAPI("associate-id", "access-key", "secret-key");
$item = $amazon->item_lookup(Value on cell D2)->get_item_data();
echo $item->price;
then save the csv file after updating it's prices, is there a simple easy way to do that in maybe php especially that i'm very new to coding?
Edit 1: I need the csv file to import it using WooCommerce import tool which only accept csv files
Thanks in advance
What you have to do is:
Parse the CSV file into an array. You can use PHP functions for that like str-getcsv
Find the correct line inside the array with either array_filter or a simple foreach loop.
Update the respective value with the new price
Create a CSV file from the array with fputcsv
How come autocomplete doesnt work when I got json data that has items in it? I can se that it is becoming a list, but it is not filling with names.
Example of my json data: http://nettport.com/no/stram/search.php?term=e
<script>
$(function() {
$( "#inp_meal_a_0" ).autocomplete({
source: 'search.php'
});
$('#inp_meal_a_0').on('autocompleteselect', function (e, ui) {
var val = $('#inp_size_a_0').val();
var energy = ui.item.energy;
var proteins = ui.item.proteins;
var carbohydrates = ui.item.carbohydrates;
var fat = ui.item.fat;
$("#inp_energy_a_0").val((energy*val)/100);
$("#inp_proteins_a_0").val((proteins*val)/100);
$("#inp_carbs_a_0").val((carbohydrates*val)/100);
$("#inp_fat_a_0").val((fat*val)/100);
});
});
</script>
Search.php
<?php
header('Content-type: text/html; charset=windows-1252;');
// Make a MySQL Connection
$host = $_SERVER['HTTP_HOST'];
if($host == "127.1.1.0"){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("n") or die(mysql_error());
}
// Quote smart
function quote_smart($value){
// Stripslashes
if (get_magic_quotes_gpc() && !is_null($value) ) {
$value = stripslashes($value);
}
//Change decimal values from , to . if applicable
if( is_numeric($value) && strpos($value,',') !== false ){
$value = str_replace(',','.',$value);
}
if( is_null($value) ){
$value = 'NULL';
}
// Quote if not integer or null
elseif (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
if(isset($_GET['term']) && $_GET['term'] != ''){
$term = $_GET['term'];
$term = strip_tags(stripslashes($term));
$term = trim($term);
$term = strtolower($term);
$term = $term . "%";
$part_mysql = quote_smart($term);
//get matched data from skills table
$x = 0;
$query = "SELECT cc_id, cc_food_name, cc_manufactor_name, cc_serving_size, cc_serving_mesurment, cc_energy, cc_proteins, cc_carbohydrates, cc_fat FROM stram_calorie_calculation WHERE cc_food_name LIKE $part_mysql";
$r = mysql_query($query);
while ($row = mysql_fetch_array($r, MYSQL_NUM)) {
$get_cc_id = $row[0];
$get_cc_food_name = $row[1];
$get_cc_manufactor_name = $row[2];
$get_cc_serving_size = $row[3];
$get_cc_serving_mesurment = $row[4];
$get_cc_energy = $row[5];
$get_cc_proteins = $row[6];
$get_cc_carbohydrates = $row[7];
$get_cc_fat = $row[8];
if($get_cc_food_name == ""){
$result = mysql_query("DELETE FROM stram_calorie_calculation WHERE cc_id='$get_cc_id'") or die(mysql_error());
}
$data[$x] = array('food_name' => $get_cc_food_name, 'energy' => $get_cc_energy, 'proteins' => $get_cc_proteins, 'carbohydrates' => $get_cc_carbohydrates, 'fat' => $get_cc_fat);
//$data[$x] = $get_cc_food_name;
$x++;
}
//return json data
echo json_encode($data);
}
?>
I have the following js function, which makes an ajax request, but it is not doing it for some reason. I checked alerting url and it displays it as it supposed to be, so all variables are declared.
var request = new XMLHttpRequest();
var url = "ajax_js/q_ajax.php?q="+ques+
"&ans="+ans+
"&a="+inp[0].value+
"&b="+inp[2].value+
"&c="+inp[4].value+
"&d="+inp[6].value+
"&cor="+checked+
"&def="+input+
"&q_n="+q_name+
"&c_id="+c_id;
request.onreadystatechange=function (){
if(request.readyState==4 && request.status==200){
alert(request.responseText);
}
request.open("GET", url, true);
request.send();
}
Here is the code from php file.
<?php
require("db_conx.php");
$q = $_GET['q'];
$ans = $_GET['ans'];
$a = $_GET['a'];
$b = $_GET['b'];
$c = $_GET['c'];
$d = $_GET['d'];
$cor = $_GET['cor'];
$def = $_GET['def'];
$q_n = $_GET['q_n'];
$c_id = $_GET['c_id'];
$q = mysqli_escape_string($con, $q);
$ans = mysqli_escape_string($con, $ans);
$a = mysqli_escape_string($con, $a);
$b = mysqli_escape_string($con, $b);
$c = mysqli_escape_string($con, $c);
$d = mysqli_escape_string($con, $d);
$cor = mysqli_escape_string($con, $cor);
$def = mysqli_escape_string($con, $def);
$q_n = mysqli_escape_string($con, $q_n);
$c_id = mysqli_escape_string($con, $c_id);
/* Modify id for the system */
$query = mysqli_query($con, "INSERT INTO course_quiz (course_id, quiz_name, question, des_answer, ChoiceA,
ChoiceB, ChoiceC, ChoiceD, correct, def)
VALUES ('$c_id', '$q_n', '$q', '$ans', '$a', '$b', '$c', '$d', '$cor', '$def')");
echo('Question has been saved');
/* header('Location: ../instr_home.php'); */
I also have an another ajax call(works perfect) in the same page, which I think the reason of the problem. Variables for XMLHttpRequest are named different as well.
Thank You in advance!
Just replaced ajax, by Jquery ajax,
Make sure all the URL variables are initialized before passing through url.
Change the $_GET method to $_POST in your PHP file.
Just Copy-Paste the solution.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function ajax()
{
var urlString ="q="+ques+"&ans="+ans+"&a="+inp[0].value+"&b="+inp[2].value+"&c="+inp[4].value+"&d="+inp[6].value+"&cor="+checked+"&def="+input+"&q_n="+q_name+"&c_id="+c_id;
$.ajax
({
url: "ajax_js/q_ajax.php",
type : "POST",
cache : false,
data : urlString,
success: function(response)
{
alert(response);
}
});
}
</script>
In your PHP file,
<?php
require("db_conx.php");
$q = $_POST['q'];
$ans = $_POST['ans'];
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
$d = $_POST['d'];
$cor = $_POST['cor'];
$def = $_POST['def'];
$q_n = $_POST['q_n'];
$c_id = $_POST['c_id'];
$q = mysqli_escape_string($con, $q);
$ans = mysqli_escape_string($con, $ans);
$a = mysqli_escape_string($con, $a);
$b = mysqli_escape_string($con, $b);
$c = mysqli_escape_string($con, $c);
$d = mysqli_escape_string($con, $d);
$cor = mysqli_escape_string($con, $cor);
$def = mysqli_escape_string($con, $def);
$q_n = mysqli_escape_string($con, $q_n);
$c_id = mysqli_escape_string($con, $c_id);
/* Modify id for the system */
$query = mysqli_query($con, "INSERT INTO course_quiz (course_id, quiz_name, question, des_answer, ChoiceA,
ChoiceB, ChoiceC, ChoiceD, correct, def)
VALUES ('$c_id', '$q_n', '$q', '$ans', '$a', '$b', '$c', '$d', '$cor', '$def')");
echo('Question has been saved');
/* header('Location: ../instr_home.php'); */
?>
Change you code with this and you find your error
request.onreadystatechange=function (){
//if(request.readyState==4 && request.status==200){
alert(request.responseText);
//}
}
request.open("GET", url, false);
request.send();
Question
I'm trying to place markers on a map by retrieving them via php, looping them into javascript arrays then looping the arrys to add the markers.
db query
require_once("func/connect.php");
$query = "SELECT * FROM site_locations;";
$stmt = $db->prepare($query);
$stmt->execute();
creating creating js arrays
<script type="text/javascript">
var lat = new Array();
var lon = new Array();
var site = new Array();
<?php
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$lat = json_encode($row['latitude']);
$long = json_encode($row['longitude']);
$site = json_encode($row['site_name']);
?>
lat.push(<?php echo '\'';
echo $lat;
echo '\''; ?>);
lon.push(<?php echo '\'';
echo $lon;
echo '\''; ?>);
site.push(<?php echo '\'';
echo $site;
echo '\''; ?>);
<?php
}
?>
</script>
Finally adding looping the js arrays to add markers
markers: [
for (i = 0; i < lat.length; i++) {
{
latLng: [lat[i], lon[i]],
name: site[i]
},
}
]
As it currently stands, this does not work. The PHP side of things works.
Also tried
markers: [
for (var i = 0; i < lat.length; i++) {
{
latLng: [lat(i), lon(i)],
name: site(i)
},
}
]
You could make the work on the PHP side :
<?php
$points = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$point = new stdClass();
$coords = array();
$coords[] = floatval($row['latitude']);
$coords[] = floatval($row['longitude']);
$point->latLng = $coords;
$point->name = $row['site_name'];
array_push($points, $point);
}
?>
<script>
var points = <?php echo json_encode($points); ?>;
</script>
And then init your maps with the javascript variable :
markers: points
You already json_encode() the values, hence the single quotes in js are breaking it. Use:
site.push(<?php echo $site; ?>);