I have a little website I am building to help me learn HTML/PHP/Javascript. On this website I have a Leaflet map where I display the locations of tweets I have stored in a postgreSQL/POSTGIS database. I had this working when I hardcoded the SQL query into my PHP code, but now I wanted to add a feature that allows the user to provide text input which will be used to query one of the columns of the database (hashtag column). Here is where I am running into problems, as I cannot seem to get the input text to work in my query. I am using $_GET to pass the value from the input text box to the PHP page which uses that value to perform the query. However, when I use echo to see what value $_GET['input'] was returning, I found that it returns some HTML string:
[
For the website I have created 4 scripts. The first is the main page which contains my HTML code, the second is a javascript code which creates the leaflet map and defines a function when people click on the map features, the third is another javascript code which uses ajax to get data from the database (by interacting with the 4th script) and loading them to my leaflet map.
Below are the four pages:
Page 1, main HTML:
<html>
<head>
<title>Leaftet Map</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"></script>
<link rel="stylesheet" href="./style.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<h1> Welcome to my Leaftlet Map </h1>
<p> Search for a City and if we have tweets for it they will display on the map! (Currently only #Tokyo and #Berlin are supported) </p>
<!-- insert to input box here -->
<form name="input" method="get">
<input type='text' value="#Berlin" id='input' name='input'/>
<input type='button' value='Search hashtag' id='search' onclick="loadData();"/>
</form>
<div id = "mapid"></div>
<!--If we put the script before the div, then the script will run but div doesnt exist yet, so the map won't show up!-->
<script src="./mapLoad.js"></script>
<script>
function loadData() {
var value = $("#input").val();
if (value.length != 0) {
$.getScript("ajax.js")
}
}
</script>
</body>
</html>
Page 2, Leaflet map creation:
var mymap = L.map('mapid').setView([51.505, -0.09], 5);
L.tileLayer('https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=wq2dobtMr2Zc1pJFS7rB',
{attribution: '© MapTiler © OpenStreetMap contributors'
}
).addTo(mymap);
// create a function to perform when someone mouses on each feature
function func_name (feature, layer) {
layer.bindPopup(feature.properties.tweet)
};
Page 3, Ajax script:
// JQuery script that runs the load from database script
$.ajax({url:'loadFromDB.php', // loadfromDB.php is the fourth script/page (see below)
success: function(response){
feats = JSON.parse(response);
L.geoJSON(feats, {onEachFeature: func_name}).addTo(mymap);
},
error: function(xhr, status, error){
alert("ERROR: "+error);
}
}
);
Page 4, PHP script to connect to DB, query, and return result
<?php
// ***********************Connect to the database***********************
try{
$myPDO = new PDO("pgsql:host=localhost;dbname=PostGIS_DB","postgres","password");
}
catch(PDOException $e){
echo $e->getMessage();
}
// ***********************Define function***********************
function getData($input){
// Query the polygon table
$result = $myPDO->query("SELECT json_build_object(
'type', 'Feature',
'geometry', ST_AsGeoJSON(geog)::JSONB,
'properties', to_jsonb(row) - 'gid' - 'geog'
) FROM (SELECT *
FROM tweets_point
WHERE tweets_point.hashtag = '".$input."'
UNION ALL
SELECT *
FROM tweets_poly
WHERE tweets_poly.hashtag = '".$input."')
row;");
// Loop through rows of the result and append to the feature collection
$features = array();
foreach($result AS $rows){
//since $row['jsonb_build_object'] is in json format but is currently wrapped in a string we decode the json from the string
$j = json_decode($rows['jsonb_build_object']);
array_push($features, $j);
}
$feature_collect=["type"=>"FeatureCollection", "features"=>$features];
echo json_encode($feature_collect);
}
// ***********************Get the input value to display tweets***********************
$input = '';
if(isset($_GET['input'])){
$input = $_GET['input'];
getData($input);
};
?>
But as I stated above, I think the problem comes down to the code I have written for the text input and the $_GET['input'] variable. Maybe someone has some ideas?
Related
On load my web app is producing this error:
DataTables warning: table id=data-table - Requested unknown parameter '9' for row 21, column 9. For more information about this error, please see http://datatables.net/tn/4
Code.gs
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate();
}
//GET DATA FROM GOOGLE SHEET AND RETURN AS AN ARRAY
function getData(){
var spreadSheetId = "1VzHY8fTq8OsXhpHYHESSSPxeVNOnqxpjcsyWJpbuEOs"; //CHANGE
var dataRange = "Base Stats!A2:L"; //CHANGE
var range = Sheets.Spreadsheets.Values.get(spreadSheetId,dataRange);
var values = range.values;
return values;
}
//INCLUDE JAVASCRIPT AND CSS FILES
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!--INCLUDE REQUIRED EXTERNAL JAVASCRIPT AND CSS LIBRARIES-->
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.23/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/dataTables.bootstrap4.min.css">
<?!= include('JavaScript'); ?> <!--INCLUDE JavaScript.html FILE-->
</head>
<body>
<div class="container">
<br>
<div class="row">
<table id="data-table" class="table table-striped table-sm table-hover table-bordered">
<!-- TABLE DATA IS ADDED BY THE showData() JAVASCRIPT FUNCTION ABOVE -->
</table>
</div>
</div>
</body>
</html>
JavaScript.html
<script>
/*
*THIS FUNCTION CALLS THE getData() FUNCTION IN THE Code.gs FILE,
*AND PASS RETURNED DATA TO showData() FUNCTION
*/
google.script.run.withSuccessHandler(showData).getData();
//THIS FUNCTION GENERATE THE DATA TABLE FROM THE DATA ARRAY
function showData(dataArray){
$(document).ready(function(){
$('#data-table').DataTable({
data: dataArray,
//CHANGE THE TABLE HEADINGS BELOW TO MATCH WITH YOUR SELECTED DATA RANGE
columns: [
{"title":"Date Added"},
{"title":"SpotRacer"},
{"title":"Brand"},
{"title":"Model"},
{"title":"Acceleration"},
{"title":"Speed (MPH)"},
{"title":"Speed (KPH)"},
{"title":"Handling (%)"},
{"title":"Star Rating"},
{"title":"Comments"},
{"title":"Score (Cumlative)"},
{"title":"Score (Weighted)"}
]
});
});
}
</script>
I'm not sure what is causing the error with that specific row and column, but perhaps has something to do with the column not displaying plain text? Column 9 is 'Star Rating'.
Google Sheet: SpotRacers Fanbase Database
In your script, Sheets.Spreadsheets.Values.get of Sheets API is used. In this case, the retrieved values are 2-dimensional array. But, for example, when all rows are not embedded by the cell values (for example, the 1st row has the values in the columns "A", "B", "C", and the 2nd row has the values in the columns "A" and "B".), the lengths of all rows are different. I'm worried about this situation. So, I thought that the reason for your issue might be due to this.
If my understanding of your current issue was correct, how about the following modification?
From:
function getData(){
var spreadSheetId = "###"; //CHANGE
var dataRange = "Base Stats!A2:L"; //CHANGE
var range = Sheets.Spreadsheets.Values.get(spreadSheetId,dataRange);
var values = range.values;
return values;
}
To:
function getData(){
var spreadSheetId = "###"; // Please set your Spreadsheet ID.
var sheet = SpreadsheetApp.openById(spreadSheetId).getSheetByName("Base Stats");
var values = sheet.getRange("A2:L" + sheet.getLastRow()).getDisplayValues();
return values;
}
In this modification, the values are retrieved using getDisplayValues(). And, the data is retrieved from the data range.
Note:
When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.
You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".
Reference:
getDisplayValues()
I have a little project going to log temperatures and such to a MySQL database, and I'd like to provide for accessing that info from anywhere.
My initial crude attempt worked pretty well (simply a PHP file getting the MySQL data into an HTML table)
Now I'd like to use some pretty graphs in this project and I've failed despite many many many hours of googling.
Here's the PHP and js/HTML files.
(edit: removed all the mysql stuff to focus on the php->js connection)
this is the php file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<?php
$phpvar = ( {labels: ['One', 'Two', 'Three'], series: [[8, 13, 21]] });
$jsvar = json_encode($phpvar);
?>
</body>
</html>
Next, the js/HTML page where I'm trying to pull the data from the PHP script in so that it can be displayed using chartist...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<! include chartist>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<! include ajax jquery >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<div class="ct-chart ct-double-octave" id="chart1"></div>
<div id="testdiv">
</div>
<script type="text/javascript">
$.getJSON('stackphp.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);
var sample= {
labels: ['One', 'Two', 'Three'],
series: [
[8, 13, 21],
[1, 2, 3]
]
}
var chart = new Chartist.Bar('.ct-chart', sample);
</script>
</body>
</html>
#T.Shah... Interestingly, this code does display a sample graph sucessfully...IF if remove the three lines 1 $.getJSON('stackphp.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);`
Leaveing those three line in however, breaks the whole page... even thought the jsvar variable isn't used in the chartist function. Not sure why that is.
This project is making it clear to me how little I've actually dabbled in web code before. If I can get a fingertip's worth of grip on what I'm missing, I'll pound away at this as much as needed.
Many thanks.
so this project has taught me just tons about javasript, php, and the rest of the webstack.
I’ll try to outline the answer to my original question in case someone else finds this via google.
First, getting data out of mysql using php was pretty easy. Here’s that code…
Setting up a convenient set of variables…
<?php
$hostname = "localhost";
$username = “mysqladminusername”;
$password = “mysqladminpass”;
$db = “tablename”;
$dbconnect=mysqli_connect($hostname,$username,$password,$db);
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
?>
then pulling the data….
<?php
set_time_limit (60); //needed to prevent timeout error mysql reports the unlimited script takes ~30sec
$query = mysqli_query($dbconnect, "SELECT * FROM tablename ORDER by idcolumnname DESC limit 2000")
or die (mysqli_error($dbconnect));
?>
Then reading the data and putting into an html table…. and creating php arrays with the contents of each mysql column.
<?php
while ($row = mysqli_fetch_assoc($query)) {
echo
"<tr>
<td>{$row[‘col1name’]}</td>
<td>{$row[‘col2name’]}</td>
<td>{$row['col3name’]}</td>
<td>{$row[‘col4name’]}</td>
</tr>\n";
$phpcol1[] = $row[‘col1name’];
$phpcol2[] = $row[‘col2name’];
$phpcol3[] = $row[‘col3name’];
$phpcol4[] = $row[‘col4name’];
}
?>
At this point the php arrays are formatted as normal php “associative arrays”… something like this….
array(10) { [0]=> array(1) { [“col1name”]=> string(3) "658" } [1]=> array(1) { [“col1name”]=> string(3) "657" } [2]=> array(1) { [“col1name”]=> string(3) "658" }
….which is not very useful since chartist doesn’t understand it.
So we need to convert it to the format chartist expects, e.g. [232,345,4545,343,235,32]
(keep in mind that this array is one of two that chartist requires, it needs an array of “labels” and an array of “series”… and then the chartist demo code puts those together and uses them in the final bit of code that actually creates the chartist graph.)
We do this conversion using json encoding.
This can be done in stages, using variables to separate the code for readability, or as a oneliner for compactness.
The compact version is the method I chose in the end.
e.g….
<script type=“text/javascript”>
var jsonlabelsdatavariable = <?php echo json_encode($phpcol1) ?>;
var jsonseriesdatavariable = <?php echo json_encode($phpcol2) ?>;
//comment…here I found it useful to print the formatted array data to the screen so I could see the change with my eyes. To do this, I created an html dviv element like this….
<div class="container" id=“showmethedata”></div>….
in the body of the html page then I put the array data in with the following code…
document.getElementById(“showmethedata”).innerHTML
//comment… while I was testing this, I used placeholder data in the chartist demo code so that I could switch back and forth between the working demo code, and the broken custom code, and use developer tools to see the problems. so below you’ll see that the chartist demo code starts out filled with my placeholder data, then gets emptied out, and then overwritten with the real data from the json variable.
//This is the chartist demo code…..(notice the line feed, I was testing for characters that would break the chartist display, since a problem I had at that time was all the label data being shown in one point of the graph. Turns out this problem was not from bad characters, but that I was pushing my label data into a single label array element.
var data = {
labels: ['2222-02-13_09:12:00','2018-02-13_09:11:00','2018-02-13_09:10:00','2018-02-
13_09:09:00','2018-02-13_09:08:00'],
series: [
[5,2,4,2,0]
]
};
//Now I blank the placeholder arrays…
data.labels.length = 0;
data.series.length = 0;
//now I fill the arrays with the real data…note that two methods are used. this is due to the formatting that chartist expects… the labels array is a single array with elements… while the series array contains an inner array, and that inner array contains the elements. using the push method on the labels array resulted in the labels array being shows as a label for a single data point on the graph.
data.labels = data.labels.concat(jsonlabelsdatavariable);
data.series.push(jsonlight);
//finally we can build the chartist graph…
new Chartist.Line('.ct-chart', data, { width:10000, showArea:true, reverseData: true, });
//and lastly, we close the javascript tag.
</script>
I’ll also note i woulnd up using a few custom functions that edited the contents of my php array elements to do things like remove spaces, add or remove quote marks around each element, etc… but i don’t think any of that was actually necessary.
e.g.
function addquotes ($element){
return "'{$element}'";
}
$withquotes = array_map("addquotes", $sourcearray);
function killspace ($anothersourcearray){
return str_replace(' ' , '_', $anothersourcearray);
}
$phpkillspace = array_map("killspace", $anothersourcearray);
$unspecial = preg_replace("/[^a-zA-Z 0-9]+/", "", $finalsourcearray );
What an adventure.
Cheers!
I was flowing #David 's code and had problems in few spots, so for reference, here is my complete code:
<?php
//here is connection information
require "cont.php";
$db = db_connect();
$upit = "SELECT * FROM (
SELECT * FROM meteo LIMIT 1000
) sub
ORDER BY id ASC";
$rezultat = mysqli_query ($db, $upit);
db_disconnect($db);
$label = array();
$series = array();
if ($rezultat != null)
{
$i = 0;
$j = 0; //vairable for sciping few database enteries.
while($red = mysqli_fetch_assoc($rezultat))
{
$j++;
if ($j == 1)
{
$t = date_create($red['at']);
$label[$i] = date_format($t, 'H:i');
$series[$i] = array($red['dht_temp'], $red['bmx_temp']);
//$series[$i] = array($red['id'], $red['dht_temp'], $red['bmx_temp'], $red['hum'], $red['press'], $red['w_speed'], WindDirectionToString($red['w_dir']));
$i++;
}
// how meny entries to scip
if($j == 10) {
$j = 0;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
</head>
<body>
<div class="ct-chart ct-perfect-fourth"></div>
<script type="text/javascript">
var data = {
labels: <?php echo json_encode($label) ?>,
series: <?php echo json_encode($series); ?>
};
var options = {
width: 1000,
height: 500
};
new Chartist.Line('.ct-chart', data, options);
</script>
</body>
</html>
You need to make sure that '100.php' file return data in the format that chartist expects. If you can make sure of that, then your html file could be like this. Then remove the random data part.
<!DOCTYPE html>
<html>
<head>
<! include chartist>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<! include ajax jquery >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
<div class="ct-chart ct-double-octave" id="chart1"></div>
<div id="testdiv">
</div>
<script type="text/javascript">
$.getJSON('100.php', function(data) {
var jsvar = JSON.parse(data);
console.log(jsvar);
// jsvar = {
// // random test data just to build a visible chart
// labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
// // random test data just to build a visible chart
// series: [
// [5, 2, 4, 2, 0]
// ]
// };
// Create a new line chart object where as first parameter we pass in a selector
// that is resolving to our chart container element. The Second parameter
// is the actual data object.
new Chartist.Bar('.ct-chart', jsvar);
});
</script>
</body>
</html>
I have a google sheet, I want to prompt a user to select ranges to get information from, store that into an array, and then create a chart in an html popup. I have read a bit about the google.script.run functionality, and understand that without the withSuccessHandler(HTMLFunction).FunctionToCall() syntax at the end, the HTML script moves onto the next line. I have a .gs file below, and an .html file, and I was able to get the graph to work when I just entered a static array in my .gs function. However, I seem to be struggling with how to return focus to the editor to get a range, and then to bring the HTML dialog box with the chart back up and get the right data to the function that plots the chart. I saw here that I could use the google.script.host to call the editor.focus() function so the user can now select cells, but I can't seem to get the focus back to the HTML popup without calling the HTML file all over again. Here is my .gs function:
function RetrieveData(){
var ss = SpreadsheetApp.getActive();
var sheets = ss.getSheets();
var s = sheets[1];
var UI = SpreadsheetApp.getUi();
var response = UI.prompt("Please enter the first cell in the category").getResponseText();
var ir = s.getRange(response);
var n= 0;
var stored = [];
stored.push(["Income Category", "Frequency"]);
while (ir.getValue()!= "") {
n = n +1;
ir = ir.offset(1, 0);
}
ir = ir.offset(-n,0)
for(i =0; i<n;i++) {
stored.push([ir.getValue(),ir.offset(n+2,0).getValue()]);
ir = ir.offset(1, 0);
}
return stored;
}
Here is my html that is within the body (Stack Overflow is a little strict, so I am not going to go through the trouble of showing all the HTML; this is just within the body and it is what is communicating with the .gs file):
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(getdata);
function getdata() {
google.script.run.withSuccessHandler(drawChart).RetrieveData();
google.script.host.editor.focus();
}
function drawChart(stored) {
//This apparently shows a log of the object
//console.log(stored);
var data = new google.visualization.arrayToDataTable(stored);
console.log(data);
var options = {'title':'Income',
'width':400,
'height':300,
'is3d':true};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.script.run.withSuccessHandler(drawChart).RetrieveData();
}
One last thing I tried was to call the
SpreadsheetApp.getUi().showModalDialog(html, "Title") function one more time, but without calling the html file all over again, and creating an endless loop, I don't seem to have a way to do that. Any idea how to accomplish this?
Here's a simple example of picking a range with a modeless dialog. With just a few extra features thrown in for good measure.
Code.gs:
function selRange()//run this to get everything started. A dialog will be displayed that instructs you to select a range.
{
var output=HtmlService.createHtmlOutputFromFile('pickRange').setWidth(300).setHeight(200).setTitle('Select A Range');
SpreadsheetApp.getUi().showModelessDialog(output, 'Range Selector');
}
function selCurRng()
{
var sso=SpreadsheetApp.getActive();
var sh0=sso.getActiveSheet();
var rg0=sh0.getActiveRange();
var rng0A1=rg0.getA1Notation();
rg0.setBackground('#777700');
return rng0A1;
}
function clrRange(range)
{
var sso=SpreadsheetApp.getActive();
var sh0=sso.getActiveSheet();
var rg0=sh0.getRange(range);
rg0.setBackground('#ffffff');
}
pickRange.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var grange='';
function selectRange()
{
$('#btn1').prop('disabled',true);
$('#btn2').prop('disabled',false);
google.script.run
.withSuccessHandler(setResponse)
.selCurRng();
}
function setResponse(r)
{
grange=r;
var msg='You have select the range ' + r;
$('#instr').css('display','none');
$('#rsp').text(msg);
}
function clearAndClose()
{
google.script.run.clrRange(grange);
google.script.host.close();
}
console.log('My Code');
</script>
</head>
<body>
<div id="rsp"></div>
<div id="instr">Please select your desired range.</div>
<input type="button" id="btn1" value="Range Selected" onClick="selectRange();" />
<br /><input type="button" id="btn2" value="close" onClick="clearAndClose();"; disabled="true" />
</body>
</html>
In a class, I was asked to make a dynamic drop-down menu in a form using HTML5 and JavaScript. I did that here.
Now, I need to call data from a JSON file. I looked at other answers on SOF and am still not really understanding how to use JQuery to get info from the JSON file.
I need to have 2 fields: the first field is a Country. The JSON key is country and the value is state. A copy of the JSON file and contents can be found here. The second drop-down field adds only the values / arrays related to its associated Country.
Here is a copy of my HTML5 file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a copy of the JS file I wrote so far that tries to get the data from the JSON file and fails:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the content from the other JS file that adds the field instruction:
var selectYourCountry = document.getElementById('selectCountry');
selectYourCountry.innerHTML = "Select Your Country: ";
var selectYourState = document.getElementById('selectState');
selectYourState.innerHTML = "Select Your State";
This was supposed to at least add the values to the field, but nothing but empty boxes appear on the web page.
I then need to make a conditional statement like the one at here but calling or referencing data from the JSON file.
I have only taken some HTML and JavaScript courses, not JQuery and JSON. So, your help will greatly increase my knowledge, which I will be very grateful for.
Thank you!!
I found this SOF answer and changed my JS file to the following:
$(document).ready(function()
{
$('#locationSelector').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"countryState.JSON",
dataType: "json",
success: function (data) {
$.each(data.country,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#locator');
});
}
});
});
});
And, I edited my HTML document as follows:
<form id="locationSelector" enctype='application/json'></form>
I removed and added back the <select> tags and with the following at least I get a blank box:
`<form id="locationSelector" enctype='application/json'>
<select id="locator"></select>
</form>`
I feel like I am getting closer, but am still lost.
Can you try this:
$.get("countryState.JSON", function( data ) {
var html = "";
$.each(data.d, function(i, el) {
console.log(el);
html += "<option value='"+Your value+"'>"+Your displayed text+"</option>";
});
$('#state').html(html);
});
I'm trying to get the html of www.soccerway.com. In particular this:
that have the label-wrapper class I also tried with: select.nav-select but I can't get any content. What I did is:
1) Created a php filed called grabber.php, this file have this code:
<?php echo file_get_contents($_GET['url']); ?>
2) Created a index.html file with this content:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>test</title>
</head>
<body>
<div id="response"></div>
</body>
<script>
$(function(){
var contentURI= 'http://soccerway.com';
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
});
var LI = document.querySelectorAll(".list li");
var result = {};
for(var i=0; i<LI.length; i++){
var el = LI[i];
var elData = el.dataset.value;
if(elData) result[el.innerHTML] = elData; // Only if element has data-value attr
}
console.log( result );
</script>
</html>
in the div there is no content grabbed, I tested my js code for get all the link and working but I've inserted the html page manually.
I see a couple issues here.
var contentURI= 'http:/soccerway.com #label-wrapper';
You're missing the second slash in http://, and you're passing a URL with a space and an ID to file_get_contents. You'll want this instead:
var contentURI = 'http://soccerway.com/';
and then you'll need to parse out the item you're interested in from the resulting HTML.
The #label-wrapper needs to be in the jQuery load() call, not the file_get_contents, and the contentURI variable needs to be properly escaped with encodeURIComponent:
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
Your code also contains a massive vulnerability that's potentially very dangerous, as it allows anyone to access grabber.php with a url value that's a file location on your server. This could compromise your database password or other sensitive data on the server.