Using PHP to populate Javascript Variables - javascript

I'm trying to populate a Drop-Down menu from a csv file located on a network share.
I've come as far to get the file to create all the options successfully when the file is in the wwwroot folder however, now I'm faced with the external url reference issue.
Ajax does not support local File:/// directories and when attempting to use the network share location it also fails: \\Server\Folder\File.csv
Is there any way to read the data from the csv file using php or other server-side language in order to perform my work on the data?
Code Below for your reference:
<script>
function SubmitBy(){
$.ajax({
url: encodeURI('./PrinterLookup.csv'),
success: function(data) {
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Looking for something like this,,, to bypass the ajax url limitation:
<script>
function SubmitBy(){
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = $Data;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Any assistance on this will be greatly appreciated.
Thank you in advance.

in this line var data = $Data; you need to print $Data see below
<script>
function SubmitBy(){
<?php
$Datapath = "file:///Server/Folder/Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = <?php echo $Data; ?> //correction here
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>

Please check first this is .php file .
If this is .php file.
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
<script>
function SubmitBy(){
var data = <?php print_r( $data ); ?>;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>

Related

Suggest a way to store the value form csv into dropdown with javascript variable perform operations on it

<script> //script loading the csv and reading the files to out into an array of variables which are used in dropdown
var $csvData = [],
$colNames = [];
function _ReadCSV($a) {
var $f = $a.files[0];
if($f) {
var reader = new FileReader();
reader.onerror = function($e) {
div.innerHTML = 'The file can\'t be read! Error ' + $e.target.error.code;
}
reader.onload = function($e) {
var $data = $e.target.result.split("\n");
$colNames = $data[0].split(","); //split to separate the column inside the csv
$data.splice(0, 1);
for(var $b = 0; $b < $data.length; $b++) {
var $tmpJSON = {},
$colData = $data[$b].split(",");
for(var $c = 0; $c < $colData.length; $c++) $tmpJSON[$colNames[$c]] = $colData[$c];
$csvData.push($tmpJSON);
document.getElementById("try").innerHTML = "Value: "+ $colData; //just to check the value
}
_CreateDropdown();
}
reader.readAsText($f);
}
}
function _CreateDropdown() {
var $tmpHTML = '<select onchange="_UpdateFields(this.value)">';
for(var $a = 0; $a < $csvData.length; $a++) $tmpHTML += '<option value="' + $a + '">' + $csvData[$a][$colNames[0]] + '</option>';
$tmpHTML += '</select>';
document.getElementById("dropdown").innerHTML = $tmpHTML;
_UpdateFields(0);
}
function _UpdateFields($a) {
var $values = '';
for(var $b = 0; $b < $colNames.length; $b++) {
console.log($colNames[$b], $csvData[$a][$colNames[$b]]);
if($csvData[$a][$colNames[$b]] != "") $values += $colNames[$b] + ': <input id="' + $colNames[$b] + '" name="' + $colNames[$b] + '" type="text" value="' + $csvData[$a][$colNames[$b]] + '" /><br />';
}
document.getElementById("fields").innerHTML = $values;
}
window.onload = function() {
document.getElementById('fileBox').onchange = function(){ _ReadCSV(this); }
}
</script>
Currently I have two columns in csv and need to pick the value of one of the column item. Which is selected upon the dropdown selected by the user and then need to modify the value. The $values variable stores both the columns values.

How on Ajax request genereate once divs for data and then on next ajax request update only the data in the divs?

Hi there I'm trying to populate div with data from ajax request, the idea is to use Ajax to get temperature from multiple sensors and for every sensor temperature data I want a separate div column with the data, So on document.ready I use ajax get once to popualte the main page div with the div columns to get the results, but after that I want to use ajax again every 10 seconds to update the data, but how can I do it not generating the containers for the data again? Because of waht I have right now I can't make it to work when I try to make a filter to show/hide the div for specific location.
$(document).ready(function(){
var menu_list = [];
var tr_str = [];
var temp_int= [];
$.ajax({
url: 'getData.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var location = response[i].location;
temp_int[i] = response[i].temp_int;
var temp = response[i].temp;
var hum = response[i].hum;
var dew = response[i].dew;
tr_str[i] = "<div id='locc" + i + "' class='location'>" +
"<span class='title'>" + location + "</span>" +
"<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " &degC</span></div>" +
"<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
"<div><span>Punkt rosy: </span><span>" + dew + " &degC</span></div>" +
"</div>";
menu_list[i] = "<label for='loc" + i + "'>" +
"<input type='checkbox' id='loc" + i + "' checked='checked'/>" +
"<span class='css-checkbox'></span>" +
"<p>" + location + "</p>" +
"</label>";
}
$("#nav").append(menu_list);
$("#data").html(tr_str);
for(var i=0; i<len; i++){
if (temp_int[i] >= 250) {
$(".temp" + i).css("background-color", "#ff0000");
}
else if (temp_int[i] >= 235) {
$('.temp' + i).css("background-color","#f1c40f");
}
else {
$('.temp' +i).css("background-color","#3498db");
}
}
}
});
$("#loc1").change(function () {
if (this.checked){
$("#locc1").show(!this.checked);
}else {
$("#locc1").hide(!this.checked);
}
});
});
setTimeout(fetchdata,5000);
function fetchdata(){
var tr_str = [];
var temp_int= [];
$.ajax({
url: 'getData.php',
type: 'get',
dataType: 'JSON',
cache: false,
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var location = response[i].location;
temp_int[i] = response[i].temp_int;
var temp = response[i].temp;
var hum = response[i].hum;
var dew = response[i].dew;
tr_str[i] = "<div id='locc" + i + "' class='location'>" +
"<span class='title'>" + location + "</span>" +
"<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " &degC</span></div>" +
"<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
"<div><span>Punkt rosy: </span><span>" + dew + " &degC</span></div>" +
"</div>";
}
$("#data").html(tr_str);
for(var i=0; i<len; i++){
if (temp_int[i] >= 250) {
$(".temp" + i).css("background-color", "#ff0000");
}
else if (temp_int[i] >= 235) {
$('.temp' + i).css("background-color","#f1c40f");
}
else {
$('.temp' +i).css("background-color","#3498db");
}
}
},
complete:function(){
setTimeout(fetchdata,5000);
}
});
}
function openNav() {
document.getElementById("nav").style.width = "350px";
document.getElementById("data").style.marginLeft = "350px";
}
function closeNav() {
document.getElementById("nav").style.width = "0";
document.getElementById("data").style.marginLeft = "0";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="lib/style.css">
</head>
<body>
<div id="nav" class="menu">
×
<button>Uncheck all</button>
</div>
<div class="nav-wrapper">
<span onclick="openNav()">☰</span>
</div>
<div id="data" class="wrapper"></div>
</body>
</html>
You can see that I use almost the same Ajax request again, is there a way to get teh data at first and generate the divs for the data and then just get the data every 10 seconds and update it only withou generating again the divs?
I'm thinking that what I have right now is making tis unable to work
var $checkboxes = $("#nav :checkbox");
var $button = $("#nav button");
function allChecked(){
return $checkboxes.length === $checkboxes.filter(":checked").length;
}
function updateButtonStatus(){
$button.text(allChecked()? "Uncheck all" : "Check all");
}
function handleButtonClick(){
$checkboxes.prop("checked", allChecked()? false : true)
}
$button.on("click", function() {
handleButtonClick();
updateButtonStatus();
checking();
});
$checkboxes.on("change", function(){
updateButtonStatus();
});
function openNav() {
document.getElementById("nav").style.width = "250px";
}
function closeNav() {
document.getElementById("nav").style.width = "0";
}
function checking() {
var temps = <?php echo json_encode($temps); ?>; //I know this is wrong I would change the loop iteration but it is not working even for one static element when I change it.
$.each( temps, function( index, value ){
$('#loc'+index).change(function () {
if( this.checked ) {
$('#locc'+index).show(!this.checked);
} else {
$('#locc'+index).hide(!this.checked);
}
}).change();
});}
Here is the php file code I'm geting using ajax:
<?php
require 'lib/locations.php';
$search = array('STRING: ', '"');
$search2 = array('INTEGER: ', '"');
$replace = array('','');
$return_arr = array();
for ($i = 0; $i < $c; $i++) {
$temp_int = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.3.1.0");
$temp_int = str_replace($search2,$replace,$temp_int);
$temp = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.1.0");
$temp = str_replace($search,$replace,$temp);
$hum = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.2.0");
$hum = str_replace($search,$replace,$hum);
$dew = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.3.0");
$dew = str_replace($search,$replace,$dew);
$loc = $location[$i];
$return_arr[] = array("location" => $loc,
"temp_int" => $temp_int,
"temp" => $temp,
"hum" => $hum,
"dew" => $dew);
}
echo json_encode($return_arr);
?>
The generated data is an array of one integer and strings
something like this:
var response =[{
"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
},
{"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
}, etc.]

Populate dropdown dynamically using JSON data

I am having problems displaying the names of golf courses in my dropdown menu. I have a PHP script that when ran, returns the names of the courses in my database. The problem is that when I apply this to my index.html dropdown page and display it in the browser, the content is not displaying the dropdown.
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));;
$courses = array();
while ($row = mysqli_fetch_array($result))
{
array_push($courses, $row["name"]);
}
echo json_encode($courses);
?>
The above code successfully generates the data from the database
$(document).ready(function () {
$.getJSON("getCourseDD.php", success = function(data){
var options = "";
for(var i=0; i< data.length; i++){
options += '<option value ="' + data[i] + '">' + '</option>';
}
$("#selectCourse").append(options);
});
});
The above code is not populating the course names into the dropdown menu.
The id of my dropdown menu is selectCourse.
<form> <select id="selectCourse" </select> </form>
Thanks for any help in advance.
You need to put text in options as below :
var dummyData = ['English','Spanish','French','Mandarin'];
$(document).ready(function () {
var data = dummyData, //This data comes from the ajax callback
courseOptions = "";
for(var i=0; i< data.length; i++){
courseOptions += '<option value ="' + data[i] + '">'+data[i]+'</option>';
}
$("#selectCourse").append(courseOptions);
});
Working Demo : jsFiddle
Currently you are not setting text of option also, use
options += '<option value ="' + data[i] + '">' + data[i] + '</option>'
instead of
options += '<option value ="' + data[i] + '">' + '</option>';
As you're currently utilizing jQuery, you may want to go for this solution:
for(var i=0; i< data.length; i++)
{
$("#selectCourse").append(
$('<option>').text(data[i]).val(data[i])
);
}
Use .html(options); in place of .append(options); .
append() add data after tag but html() insert data between tag.
and you should also assign something between tag, like
options += '<option value ="' + data[i] + '">' + data[i] + '</option>'
First log your data like console.log(data) and check in browser firebug console whether it outputs json string or object. If it's string you need to convert it into object using JSON.parse().

Getting an image source from JSON data

I'm attempting to call a PHP file and have it return a result (a single record's 'pageLocation') from a database table ('page'). I then want to get that result into a variable, so I can use it while creating an image in html.
Currently, the image is being created but the source is not feeding into it, leaving a default empty image at the correct size.
Javascript:
// Loads a list of comics created by the user from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Non-relevant code affecting layout if no comics are found.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
// Gets image source from database.
imgSrc = "";
tempID = arr[i].comicID;
$.post("getCover.php", {'comicID':tempID}, function(result)
{
imgSrc += ("" + result);
}
);
// Creates image item and associated radio button.
out += "<hr><br><img name = '" + ('com' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + imgSrc + "'><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT FIRST (pageLocation) FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$conn->close();
echo ($result);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
Thanks for any help provided.
You need to get he data from the result, like:
$row = $result->fetch_assoc()
Also, yes, Jim G is right, you need to escape that POST variable.

XML or text declaration not at start of entity error - PHP and Javascript

Hi I'm trying to get the xml data from php to javascript using DOM document and it keeps giving me : XML or text declaration not at start of entity error.(on firebug)
I tried saving it to a real xml file and it outputs a well formatted xml.
I guess the reason for this is white space on top of the xml file. I tried using ob_start(); and ob_end_flush(); but couldn't get that working
BTW I'm new to Ajax!
JS script
var xh = createRequest();
var xhrObject = false;
if (window.XMLHttpRequest)
{
xHRObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData()
{
if ((xh.readyState == 4) &&(xh.status == 200))
{
alert("hi");
var serverResponse = xh.responseXML;
var header = serverResponse.getElementsByTagName("good");
var spantag = document.getElementById("sp");
var x;
spantag.innerHTML = "";
x = "<table cellpadding='1' cellspacing='6' border='0'>";
x += "<tr><td>ID</td><td>price</td><td>quantity</td><td>Total</td><td>Remove</td></tr>";
for (i=0; i<header.length; i++)
{
var id = header[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
var price = header[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
var qty = header[i].getElementsByTagName("quantity")[0].childNodes[0].nodeValue;
var total = header[i].getElementsByTagName("total")[0].childNodes[0].nodeValue;
if(qty=="0")
{
continue;
}
x += "<tr>"
+ "<td>" + id + "</td>"
+ "<td>" + price + "</td>"
+ "<td>" + qty + "</td>"
+ "<td>" + total + "</td>"
+ "<td>" + "<a href='#' onclick='AddRemoveItem(\"Remove\","+id+");'>Remove Item</a>" + "</td>"
+ "</tr>";
}
x += "</table>";
if (header.length != 0)
spantag.innerHTML = x;
}
}
PHP code
function toXml($shop_goods)
{
$doc = new DomDocument();
$goods = $doc->createElement('goods');
$goods = $doc->appendChild($goods);
foreach ($shop_goods as $Item => $ItemName)
{
$good = $doc->createElement('good');
$good = $goods->appendChild($good);
$title = $doc->createElement('ID');
$title = $good->appendChild($title);
$value = $doc->createTextNode($Item);
$value = $title->appendChild($value);
$price = $doc->createElement('price');
$price = $good->appendChild($price);
$value3 = $doc->createTextNode($ItemName["price"]);
$value3 = $price->appendChild($value3);
$quantity = $doc->createElement('quantity');
$quantity = $good->appendChild($quantity);
$value2 = $doc->createTextNode($ItemName["qty"]);
$value2 = $quantity->appendChild($value2);
$total = $doc->createElement('total');
$total = $good->appendChild($total);
$value3 = $doc->createTextNode($ItemName["total"]);
$value3 = $total->appendChild($value3);
}
$strXml = $doc->saveXML();
//echo("<br>----- DATA RECOREDED!!! ----");
return $strXml;
}
As others have noted, this could be an encoding issue.
Check your code for the Xml byte order mark.
Check the document is returning the correct mime type.
Not sure of your constraints but have you considered serializing your data to Json format. It's much easier to work with in the browser.
Finally consider using a library like JQuery to handle your ajax requests, much easier for cross browser compatibility.

Categories

Resources