I am working on a demo webpage which put some products' volumes onto Google Map in some geojson polygons.
The code that to put volume onto Google Map:
map.data.addListener('click', function(event){
//Get area-information from polygon
var area_information = event.feature.getProperty('area');
/*var product_volume = showVolume(area_information); DOES NOT WORK
instead, I am sending the result to a div called p_volume and assign the value of p_volume to product_volume*/
var infowWindow_contentString = '<b>Area: </b>' + area_information+ '<br>' + '<b>Volume: </b>' + product_volume;
polygon_infoWindow.setContent(infowWindow_contentString);
polygon_infoWindow.open(map);
polygon_infoWindow.setPosition(event.latLng);
});
Now the showVolume() function:
function showVolume(area_information){
var xhr;
var result;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var areainfo = "areainfo=" + area_information;
xhr.open("POST", "get-data.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(areainfo);
xhr.onreadystatechange = display_data;
//Display Data
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementbyId('p_volume').textContent = xhr.responseText;
}
else {
alert('There was a problem with the request.');
}
}
}
};
Which calls the get-data.php.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$db_name = "mockdata";
$areainfo = $_POST['areainfo'];
$con = mysqli_connect($servername, $username, $password, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$stmt = $con->prepare('SELECT Volume from mockdata WHERE Area = ?');
$stmt->bind_param('s', $areainfo);
$stmt->execute();
$result = $stmt->get_result();
//echo $areainfo; //Testing if parameter passed into php
while ($row = $result->fetch_assoc()) {
// do something with $row
echo "{$row["Volume"]}";
}
mysqli_close($con);
?>
For each query, I am expecting only one integer from the Volume in my table. I checked the parameter is passed to get-data.php by simply
echo $areainfo;
I learned:
var product_volume = showVolume(area_information);
does not work....
Edit
It seems that the
<div><id = p_volume></div>
is getting the query result. However, my product_volume still couldn't get the result from the p_volume by simply doing
product_volume = getElementbyId('p_volume').innerHTML;
I am wondering what is wrong.
I am new to all these 3 languages. Please be gentle when criticizing "Go learn xxx language".
Thanks in advance.
Okay, I got them to work finally. My code was right when sending the parameter to PHP and have the PHP to process it. Then we need a container (<div>) to receive the data by doing getElementbyId('p_volume') = xhr.responseText.
Then in the Google Map
map.data.addListener('click', function(event){
//Get FSA from polygon
var areainfo = event.feature.getProperty('area');
showVolume(areainfo);
var product_volume = document.getElementById("p_volume").innerHTML;
var infowWindow_contentString = '<b>FSA: </b>' + FSA + '<br>' +'<b>Volume: </b>' + product_volume;
polygon_infoWindow.setContent(infowWindow_contentString);
polygon_infoWindow.open(map);
polygon_infoWindow.setPosition(event.latLng);
});
The data will be retrieved from the hidden <div><id = "p_volume", style = "display: none;">
Please do comment on the security/malpractice aspect since I really want to learn.
Edit
Update:
The code does not update the <div> immediately, it took a couple of clicks more to get the data updated. Can someone explain the synchronization issue in the code? I also have a mouseover action on the polygons in Google Map, they have the same issue.
Related
I know this site doesn't like "spot my mistake" code, but I'm desperate. I have a website that needs to access user-specific data from a database (PHP), convert the data into a JSON file, and then change a HTML header to display that specific data. The database table has the user email, password, and class name, among other things. I have a login page that establishes the session variables for the email and the password. When the user logs in, I want their class name to be entered into HTML text. I've used dozens of sources, mostly W3schools, and came up with this code:
PHP:
<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
if (!$obj) {
die(mysqli_error());
}
$servername = "localhost";
$username = "id5143969_enviroquest1";
$password = "codeteam1";
$database = "id5143969_enviroquest1";
$link = mysqli_connect($servername, $username, $password, $database);
$result = $link->query("SELECT UserClassName FROM ".$obj->UserInfo1." WHERE ".$obj->UserEmail."= '". mysqli_real_escape_string($link,
$_SESSION['useremail']) . "' and ".$obj->UserPassword." = '" . mysqli_real_escape_string($link, $_SESSION['userpassword']) . "'");
if (!$result) {
die(mysqli_error());
}
$_SESSION['classname'] = $result->fetch_assoc();
if (!$_SESSION['classname']) {
die(mysqli_error());
}
echo json_encode($_SESSION['classname']);
Javascript:
function getclassname() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "UserInfo1":"UserClassName"};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("UserClassName").innerHTML = myObj;
}
};
xmlhttp.open("GET", "php2.php" + dbParam, true);
xmlhttp.send();
}
HTML:
<h1 class="text-center" id="UserClassName" name="UserClassName" onload=
"getclassname()"> </h1>
I have no idea what's going wrong, and am too new to coding to figure it out by myself.
Try this (I can't test it, but)—
PHP:
Remove the ?> at the end of the file. Pure-PHP files should always leave off the closing tag.
Change (MYSQLI_ASSOC) to just () - per this and the docs, you don't need it.
Javascript:
Remove the session_start() call
Change
for (x in myObj) {
txt += myObj[x].name + "<br>";
}
to
txt = myObj.UserClassName
The fetch_assoc() call in PHP gives you a mapping that uses the database field names ("each key in the array represents the name of one of the result set's columns" per the docs) for a single row. Therefore, if the JSON encode/decode worked OK, you should be able to refer directly to the field.
To test this, in the developer tools, set a breakpoint at the txt = ... line and see what myObj is.
I don't think you need $obj, dbParam, or ?x=, but I would not suggest changing them unless the above doesn't help.
Good luck!
function create(x) {
var field=document.createElement('fieldset');
var t=document.createElement('table');
t.setAttribute("id","myTable");
document.body.appendChild(t);
field.appendChild(t);
document.body.appendChild(field);
var row=document.createElement('th');
newHeader = document.createElement("th");
newHeader.innerText = x;
row.appendChild(newHeader);
var row1=document.createElement('tr');
var col1=document.createElement('td');
var col2=document.createElement('td');
var row2=document.createElement('tr');
var col3=document.createElement('td');
var col4=document.createElement('td');
var row3=document.createElement('tr');
var col5=document.createElement('td');
var col6=document.createElement('td');
col1.innerHTML="Name";
col2.innerHTML="<input type='text' name='stateactivityname' size='40' required>";
row1.appendChild(col1);
row1.appendChild(col2);
col3.innerHTML="Registration Applicable";
col4.innerHTML="<select name='regapp' required><option></option><option>Yes</option><option>No</option></select>";
row2.appendChild(col3);
row2.appendChild(col4);
col5.innerHTML="Registers Applicable";
col6.innerHTML="<select name='registers' required><option></option><option>Yes</option><option>No</option></select>";
row3.appendChild(col5);
row3.appendChild(col6);
t.appendChild(row);
t.appendChild(row1);
t.appendChild(row2);
t.appendChild(row3);
addrow('myTable');
}
PHP code for storing data to database is:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$conn=new mysqli("localhost","root","","newcomplyindia");
if($conn->connect_errno){
echo("connection error");
}
$actname=$_POST["actname"];
$industry=$_POST['industrytype'];
$centralorstate=$_POST["cors"];
$sql="insert into acts (actname,centralorstate) value ('".$actname."','".$centralorstate."')";
$regapp=$_POST["regapp"];
if($regapp=='Yes'){
$regapp=true;
}
else{
$regapp=false;
}
$registers=$_POST["registers"];
if($registers=='Yes'){
$registers=true;
}
else{
$registers=false;
}
$sub=$_POST["sub"];
if($sub=='Yes'){
$sub=true;
}
else{
$sub=false;
}
if($conn->query($sql)==true){
echo 'act name added ';
}
$lastid=$conn->insert_id;
$sql1="insert into actsstate (actid,registrationrequired,registersapplicable,sublocation)"
. "values('$lastid','$regapp','$registers','$sub')";
if($conn->query($sql1)==true){
echo '<br>name and central/state added';
}
$stateactivity=$_POST["stateactivityname"];
$activityname=$_POST["activityname"];
$activitymonth=$_POST["month"];
$activitydate=$_POST["date"];
$sql2="insert into activity (name,actid,activityname,activitymonth,activitydate)"
. "values('$stateactivity','$lastid','$activityname','$activitymonth','$activitydate')";
if($conn->query($sql2)){
echo 'activity added';
}
else{
echo 'no record';
}
$conn->close();
?>
i have a javascript like this. The table is created dynamically. And i want to store the data inside this table to database. am using mysqli for database connection
Am new to javascript. Can anyone help me to do this
Here's a way using Vanilla JS (pure js)
var xhttp = new XMLHttpRequest();
var url = "save.php";
xhttp.open("POST", url, true);
// uncomment this if you're sending JSON
// xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { // Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
// the 4 & 200 are the responses that you will get when the call is successful
alert(xhttp.responseText);
}
}
xhttp.send('the data you want to send');
And here's a way to save to the database (mysql in my case) with Flat PHP (pure php)
$servername = "localhost";
$username = "db_username";
$password = "db_password";
$dbname = "db_name";
// connect to the DB
$conn = new mysqli($servername, $username, $password, $dbname);
// check if you're connected
if ($conn->connect_error) {
echo "Connection failed: " . $conn->connect_error;
}
else {
// echo "connecting to DB succeeded <br> ";
}
// uncomment the following if you're recieving json
// header("Content-Type: application/json");
// $array = json_decode(file_get_contents("php://input"), true);
$sql = "INSERT INTO table_name (columns,names) VALUES (columns,values)";
if ($conn->query($sql) === TRUE) {
echo "Data was saved successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
to learn more about the sql commands I suggest the w3schools tutorials
Of course you can by using AJAX:
$.post("php_script.php",{javascript variables}, function(result) {
alert(result);
});
I've been trying lately to use this sample of AJAX to compare form data to an SQL database from one http://www.example.com domain. My issue is that the readyState is always 1 and my Status is always 0. It is expecting 4 and 200 respectively. It also always returns responseText="" I've looked all over StackOverflow but have unsuccessfully found anything helpful.
I've boggled my mind over what could be the issue, but I just can't seem to get it to work.
*I've also tried to set file permissions on both the JS and PHP, but it functions the same.
*I'm using a dedicated web server to host all this, and I have no problem running most scripts.
//HTML GenerateRep.html
Excuse the lack of < and > tags missing, the code won't appear without them.
form id="formgen" onsubmit="GenRep(this)"
....form stuff....
button id="submit" type="submit">Submit</button
//JAVASCRIPT GenerateRep.js
function GenRep(formgen) {
var email = formgen['repemail'];
var hash = formgen['reppass'];
var first = formgen['firstname'];
var last = formgen['lastname'];
var territory = formgen['territory'];
hash.value = CryptoJS.SHA256(hash.value);
var login = email + ";" + hash.value + ";" + first + ";" + last + ";" + territory;
Login(login);
}
function Login(login) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText == "VALID") {
window.location.href = "success.html";
} else if (xhttp.responseText == "INVALID") {
$("#login_error").text("Failed! Plese check your info.");
} else {
window.location.href = "error.php";
}
}
};
xhttp.open("GET", "Validate.php?q=" + login, true);
xhttp.send();
}
//PHP Validate.php
<?php
header('Access-Control-Allow-Origin: *');
include ("ConnectDB.php");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//THIS IS A TEST TO SEE IF reponseText FUNCTIONS. IT DOES NOT.
//echo "testecho";
$whole = $_REQUEST['q'];
$userPass = explode (";", $whole);
$sql1 = "SELECT UName FROM Reps WHERE UName = '$userPass[0]'";
$result = $conn->query($sql1);
if ($result->num_rows > 0) {
$conn->close();
echo "INVALID";
} else {
$sql = "INSERT INTO Reps (UName, Pass, FName, LName, Territory) VALUES ('$userPass[0]', '$userPass[1]', '$userPass[2]', '$userPass[3]', $userPass[4])";
if ($conn->query($sql) === FALSE) {
$conn->close();
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
echo "VALID";
}
?>
I previously "commented" instead of creating an "Answer" because I wasn't suggesting a fix, just a debug step to make sure what you thought was happening, was actually happening.
Since my suggestion helped you figure out the problem, I created this "Answer" in case you want to give me "credit". :-)
So following my last question I want to use the value that is submitted in the input tag to get the matching id in my database. I have created two files for it but I can't figure out how to link them. Also note I made a database with a few values(id, firstname, etc.) and when the user fills in 1 I want it to display id 1 & the firstname.
This code is from the last question & I've added xmlhttp:
Input code
Choose a number between 1 and 5
Your info shall be shown here
Click me!
var myButton = document.getElementById('btn');
myButton.onclick = function(){
alert(document.getElementById('myid').value);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var dbText = xmlhttp.responseText;
document.getElementById('dbinfo').innerHTML = dbText;
}
}
xmlhttp.open("POST", "LinkToDataFile", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
That is what the user sees and the number is displayed correctly however I now need to link it to my file data.php which I have tried but it cannot get the value.
Data Code
<?php
require_once('input_code');
//Get the data from the database and echo them here
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "db_name";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT `id`, `firstname`, FROM `db_name` WHERE `id` = :myid"); //Here it needs to grab the value but it does not work.
$statement->bindParam(':id', $id);
$id = $_POST['id'];
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['firstname'];
}
}
catch(PDOException $e)
{
echo "The following error occurred : ".$e->getMessage();
}
echo $data;
?>
So what am I doing wrong? am I missing something obvious like the $id again or is it a series of errors, the only thing it does now is giving me an alert with the number.
By adding a line and moving $id before $statement it is all fix thanks to Dante Javier
Input code
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //Under this add the following lines:
var id = document.getElementById('myid').value;
xmlhttp.send("id="+id);
Data Code
$id = $_POST['id']; //Move this above the $statement = $connection->prepare.
I looked a lot on the internet and wasn't able to find the answer i need, so here i come to you.
What i have : A database which look like this :
name latitude longitude
---- --------- ----------
foo 13.323 -51.356
foo 54.698 2.487
What i want to do : I need to retrieve the latitude and longitude from a mysqli request done with php and use it in a function that i defined.
My problem : I'm trying to use xmlrequest but it apparently doesn't work.
The code : JS :
var selI = document.getElementById("nameIti");
selI.onchange = function(){
var val = this[this.selectedIndex].getAttribute("value");
showMark(val);
}
function showMark(str){
var xhr;
if(str==""){
return;
}
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
var object = JSON.parse(xhr.responseText);
for(var a in object){
newMark(v['lat'], v['lng']);
document.getElementById("pi").innerHTML=JSON.parse(xrh.responseText); // This is a test to display any kind of result.
}
}
}
xhr.open("GET", "getpos.php?q="+str, true);
xhr.send();
}
PHP :
<?php
$nom = $_GET['q'];
include("connexion.php");
$con = connect_LIF4();
$req1= "SELECT Latitude, Longitude FROM etape LEFT JOIN itineraires ON NomLieu=nomEtape WHERE nomIti LIKE '%$nom%'";
$result1 = mysqli_query($con, $req1);
$data = array();
while($row = mysqli_fetch_array($result1){
$data['lat'] = $row['Latitude'];
$data['lng'] = $row['Longitude'];
$resp[] = $data;
}
echo json_encode($resp);
mysqli_close($con);
?>
I tried to use newMark(lat, lng)(Which i coded and works fine) with random values, in showMark outside the onreadystatechange and it works, but i need to use it with the values retrieved from the php.
One problem with your PHP is that
while($row = mysqli_fetch_array($result1){
is missing the second brace. It should be:
while($row = mysqli_fetch_array($result1)){
Also the URL in the ajax request should be the full URL, not just getpos.php
Thirdly you have written xrh.responseText (should be xhr).
Basically there's loads of syntax errors in your code - you should use the javascript console to debug the front end ones, and PHP logging or error display for the back end ones. You should only need help here once you've debugged all obvious syntax errors.
EDIT - below is a working example (although I haven't done the MySQL part)
JS + HTML:
<span id='pi'></span>
<select id='nameIti'>
<option value='foo'>foo</option>
<option value='bar'>bar</option>
</select>
<script>
function newMark(lat,lng) {
console.log(lat);
console.log(lng);
}
var selI = document.getElementById("nameIti");
selI.onchange = function(){
var val = this[this.selectedIndex].getAttribute("value");
showMark(val);
}
function showMark(val){
var str=val;
var xhr;
// if(str==""){
// return;
// }
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
var result = JSON.parse(xhr.responseText);
console.log(result);
for(var a in result){
newMark(result[a]['lat'], result[a]['lng']);
document.getElementById("pi").innerHTML = result[a]['lat'] + ', ' + result[a]['lng'];
}
}
}
// xhr.open("GET", "getpos.php?q="+str, true);
xhr.open("GET", "getpos.php?q="+str, true);
xhr.send();
}
</script>
PHP:
<?php
$nom = $_GET['q'];
$data = array();
if($nom == 'foo') {
$data['lat'] = '5.12';
$data['lng'] = '0.34';
$resp[] = $data;
}
else if($nom == 'bar') {
$data['lat'] = '2.34';
$data['lng'] = '1.34';
$resp[] = $data;
}
echo json_encode($resp);
?>