Pass php variable to use in html script - javascript

This is my page and I want to pass my php variable witch is number from my sql database to html script function. If i replace values with anything it ruin everything. If I fetch data from input it works fine. Sql part work and I can display data through php echo but i cant pass it to html script function.
I use template chart to display my data from mysql on my webpage. All i need to do is pass my php values (that part works) to .myfunc on the bottom. In other words I need to change myValues, and myValues2 with my php values (that part i didnt figure up)
<?php
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = ''; // Password
$db_name = 'esp8266_baza'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT vrijeme_unosa, temp, hum from temp_hum where p_key = (SELECT MAX(`p_key`) FROM `temp_hum`)';
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$ptemp = $row['temp'];
$phum = $row['hum'];
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<html>
<head>
<link href="css/meter.css" rel="stylesheet" type="text/css" />
</head>
<body>
<br>
<?php echo $ptemp;
echo $phum; ?>
<br>
<input id="myValues" />
<br>
<input id="myValues2" />
</body>
<script src="js/jquery.js"></script>
<script src="js/temp.js"></script>
<script type="text/javascript">
$("#myValues").myfunc({divFact:2,eventListenerType:'keyup'});
$("#myValues2").myfunc({divFact:2,eventListenerType:'keyup'});
</script>
</html>

Why not do everything in php echo? That way you can use all variables.
echo "
<script>
$jsvar = $row[varhere]
</script>
";

Related

JavaScript to PHP variable value pass error (document.write command is not working)

After sending the country name "US" in JavaScript to PHP code, I will try to receive the results of PHP's work back to JavaScript and use them.
To do this I used the below code.
$ctryNm_php_temp = "document.write(ctryNm);";
As a result, it seemed that the value 'US' of the ctryNm variable was well transfered to php code.
The cryNm value and $SQL value printed on the screen contain 'US'.
However, the results of the SQL query were returned to an empty value, so we checked.
The IF statement shows that ctryNm and 'US' are different values.
(The output on the screen shows the same value and data type as string.)
I printed $result_obj and found no value.
echo and console.log command result for checking:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var ctryNm = "US";
</script>
<?php
$ctryNm_php_temp = "<script language='javascript'>document.write(ctryNm);</script>";
$ctryNm_php = $ctryNm_php_temp;
echo $ctryNm_php . "<br><br>";
echo "--------------" . "<br>";
echo gettype($ctryNm_php) . "<br>";
if ($ctryNm_php == 'US') {
echo "Same" . "<br>";
} elseif ($ctryNm_php != 'US') {
echo "Different" . "<br>";
}
$conn = new mysqli("...", "...", "...");
mysqli_select_db($conn, '...');
mysqli_query($conn, "set names utf8");
$sql = "SELECT * FROM acst_covid_who WHERE country_code = '$ctryNm_php'";
echo $sql . "<br>";
$result_obj = mysqli_query($conn, $sql);
echo "result_obj :" . $result_obj . "<br>";
$date_adjust = 0;
$latestDate_trend = '';
while ($row = mysqli_fetch_array($result_obj)) {
if ((int)$row['confirmed_new'] !== 0) {
$latestDate_trend = $row['date'];
$date_adjust = 1;
} elseif ((int)$row['confirmed_new'] === 0) {
$latestDate_yester_trend = strtotime($row['date'] . "-1 days");
$latestDate_trend = date("Y-m-d", $latestDate_yester_trend);
$date_adjust = 0;
};
};
$result_obj = mysqli_query($conn, $sql);
$total_rows_trend = mysqli_num_rows($result_obj) - $date_adjust;
$arr_trend = array();
while ($row = mysqli_fetch_array($result_obj)) {
array_push($arr_trend, $row);
}
echo $total_rows_trend;
echo json_encode($latestDate_trend);
?>
<script>
var latestDate_js_trend = <?php echo json_encode($latestDate_trend) ?>;
var arr_js_trend = <?php echo json_encode($arr_trend) ?>;
var arr_length_trend = <?php echo $total_rows_trend ?>;
console.log(latestDate_js_trend);
console.log(arr_js_trend);
console.log(arr_length_trend);
</script>
</body>
</html>
this sadly does not work like this.
PHP code is executed first on the server, so before the website is even shown in the browser. The order you write it does not matter.
The process is like this:
You type the address in the browser and it asks the server for the page.
The server literally runs an app called php, that reads what you wrote in the code, reads only what is between <?php and ?>, nothing else (technically the first one can be <?=)
When it is done, the server sends the page to browser
The browser reads html and fires JavaScript, long after PHP was already changed.
This is simplified but show why your code will not work.

Getting the value of dropdownlist in php

I have the following the html/php code :
<!DOCTYPE html>
<html>
<head>
<title>Voiture</title>
</head>
<body>
Welcome<br>
<form method="post" action="">
Liste de voiture<select name="selected" id="selected">
<?php
$sql = 'select Type from voiture';
$result = $conn->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
if(!in_array($row['Type'], $json)){
$json[] = $row['Type'];
echo '<option name = "'.$row['Type'].'">'.$row['Type'].'</option>';
}
}
?>
</select> <br>
<span id="sel" name="sel"></span>
<table border="1">
<tr id="header">
<td>Type</td>
<td>Model</td>
<td>Couleur</td>
<td>Prix</td>
<td>User</td>
<td>Action</td>
</tr>
</table>
<input type="submit" name="submit" hidden>
</form>
<script src="jquery-3.2.1.js"></script>
<script>
$(function(){
$('#selected').on('change',function(){
$('#sel').text(document.getElementById('selected').value);
$.getJSON('phpVoiture.php',function(data){
for (var x = 0 ; x < data.length ; x++){
$('<tr><td>'+data[x]['type']+'</td>'+'<td>'+data[x]['Model']+
'</td><td>'+data[x]['Couleur']+'</td>'+
'<td>'+data[x]['Prix']+'</td>'+'<td></td></tr>').insertAfter($('#header'));
}
});
});
});
</script>
</body>
</html>
And the following php page :
<?php
require_once ('./dbConnect.php');
include ('./Voiture.php');
$sel = $_POST['selected'];
$conn = mysqli_connect(servername, username, password, db ,port);
$query = "select * from voiture where Type = '".sel."'";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$json[] = [
'type' => $row['Type'],
'model' => $row['Model'],
'couleur' => $row['Couleur'],
'prix' => $row['Prix']
];
}
}
else{
echo mysqli_num_rows($result);
}
echo json_encode($json);
The problem is that when I select an option in the drop down list nothing happens. I want the query in the second php page to select the cars that have the type that I selected in the drop down list. I tried troubleshooting by echo an alert in both pages that have the value of the selected option, but this step also failed, so I think there is an issue with retrieving the value of the selected option. Any help would be appreciated.
You're not sending the selected value to the server. Add it to the AJAX call:
$.getJSON('phpVoiture.php', { selected: $('#selected').val() }, function(data){
//...
});
Also, your <option> elements don't have values. You used name instead, but that belongs on the <select>. Use value:
echo '<option value="'.$row['Type'].'">'.$row['Type'].'</option>';
Additionally, you're using a GET request instead of a POST request. So you need to look for the value in the $_GET array:
$sel = $_GET['selected'];
You have other typos too, such as an incorrect use of a variable in PHP:
"...".sel."..."
would be:
"...".$sel."..."
Though this brings up a point about SQL injection. You really shouldn't be directly concatenating the variable like that at all. Instead, use prepared statements with query parameters.
It's entirely possible that there continue to be other mistakes in the code I simply haven't spotted yet. You'll want your debugging to include two things:
Looking at your PHP logs for errors.
Using your browser's debugging tools to observe the AJAX request/response.

Display data in dropdown lists from another file (php,mysql,javascript)

I got multiple database dropdown lists with javascript, and I want to display result in dropdown menu. But at this moment, nothing shows. It shows Regions (drop down menu), but dosn't show Countries (drop down menu)
My Core Code(I want to display result in Country drop down menu):
<html>
<body>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function abc(){
var e = document.getElementById("Region_ID");
var val = e.options[e.selectedIndex].value;
$.post("getSecondDropDown.php",{ Region_ID:val}, function( data ) {
$("#Country_ID").html(data);
});
}
</script>
<form action="/NewService.php" id="ServiceForm" method="post">
Name:<input type="text" name="Service_Name"></br>
Region: <select name="Region_ID" id="Region_ID" onchange="abc()" form="ServiceForm">
<?php
include('config.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Region_ID, Region_Name FROM Regions");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
</select></br>
Country: <select name="Country_ID" form="ServiceForm">
<script>document.write($("#Country_ID"))</script>
</select></br>
<input type="submit">
</form>
</body>
</html>
Second php file(getSecondDropDownMenu.php):
<?php
$Region_ID =$_POST['Region_ID'];
$option="";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='$Region_ID'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>";
}
echo $option;
?>
I Think that problem is here, but don't really know it :
Country: <select name="Country_ID" form="ServiceForm">
<script>document.write($("#Country_ID"))</script>
</select></br>
In the second file ( getSecondDropDownMenu ) you need to create a function
<?php
function functionName(){
$Region_ID =$_POST['Region_ID'];
$option[] = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='$Region_ID'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
array_push($option, "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>");
}
return option;
}
?>
Then in the other file the first one include it
include('getSecondDropDownMenu.php');
and do
$arrayForSecondDropdown[] = functionName();
and then do the foreach like
foreach($arrayForSecondDropdown as $v){
echo $v;
}
You can simplify the abc function by calling it with onchange='abc(this.value)' and the target dropdown requires an ID attribute to enable the callback to add the html data. Also, as you are not passing any variables to the sql statement you do not really require the prepared statement, a simple query should suffice.
<html>
<head>
<title>dependant select menu</title>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function abc( value ){
$.post("getSecondDropDown.php",{ Region_ID:value }, function( data ) {
$("#Country_ID").html( data );
}
);
}
</script>
</head>
<body>
<form action="/NewService.php" id="ServiceForm" method="post">
Name:<input type="text" name="Service_Name"></br>
Region: <select name="Region_ID" id="Region_ID" onchange="abc( this.value )" form="ServiceForm">
<?php
include('config.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->prepare( "SELECT Region_ID, Region_Name FROM Regions" );
$stmt->execute();
$result = $stmt->setFetchMode( PDO::FETCH_ASSOC );
foreach($stmt as $v) {
echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
</select>
</br>
Country: <select id='Country_ID' name="Country_ID" form="ServiceForm"></select>
</br>
<input type="submit">
</form>
</body>
</html>
I think your missed the config file to include in your Second php file(getSecondDropDownMenu.php):. So the scripts in this is not able to run. Why this happens means this page is able to get database connection .ou are fetching the country list from database on the basis of region so here no database connection is achieved.So please include config.php and try again.And also you have done another mistake in concatenation of php variable with the string .IE in the country fetching query you should concatenate the region variable with correct syntax.Please see the below code.
Second php file(getSecondDropDownMenu.php):
<?php
include('config.php');
$Region_ID =$_POST['Region_ID'];
$option="";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='".$Region_ID."'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>";
}
echo $option;
?>
I think this may help you.
You have written the code to display with the help of ID for the select tag but you have not been given any ID for the select tag
<script>document.write($("#Country_ID"))</script>
As per the script you have provided you have to add an ID Attribute for the select tag.
I would recommend not using document.write, especially after the page has loaded. It can lead to unexpected results. Just use this method:
Try Replacing with this:
document.getElementById('Country_ID').innerHTML = "something important";
If however, you are not willing to replace the whole innerHTML, you could append something to it:
document.getElementById('Country_ID').insertAdjacentHTML('beforeend', "something added");

How to auto-save and auto-update textarea

I'm currently attempting to create a test-website based on the "Secret Diary" project of a web developer course. I'm trying to create a page that saves all of the notes written into a textbox, and displays them when I log in again. Almost everything works - I can start a session and display the saved text when I log in, but the box is deleting the textbox's saved data when the page is loaded. I know that there are better ways of storing the info, I'm just looking for how to get this method to work. This should be all of the relevant code:
mainpage.php:
<?php include("updatediary.php"); ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form method="post">
<textarea class="form-control"><?php echo $diary; ?></textarea>
</form>
<script>
$("textarea").keyup(function() {
$.post("updatediary.php", function(){diaryInput:($("textarea").val());} );
});
</script>
updatediary.php:
<?php
include("connection.php");
$query = "SELECT content FROM users WHERE id='".$_SESSION['id']."' LIMIT 1";
$result = mysqli_query($dbCon,$query);
$row = mysqli_fetch_array($result);
$diary = $row['content'];
if ($_POST['diaryInput']!="") {
$updateQuery = "UPDATE `users` SET `content`='".mysqli_real_escape_string($dbCon, $_POST['diaryInput'])."' WHERE id='".$_SESSION['id']."' LIMIT 1";
if (mysqli_query($dbCon, $updateQuery)) {
echo "saved";
} else {
echo "not saved";
};
}
?>
connection.php:
$dbCon = mysqli_connect("localhost", "owenxwfg_admin", "(password)", "owenxwfg_users");
Any help would be awesome. I personally think that there's a problem with my $.post part.

ajax jquery form fetching mysql data

I have troubles with JQuery and Ajax forms. I'm new in Ajax and Jquery. I'm creating a webapp with a search form. The data I'm fetching from MYSQL Database. So I have a request page with a form, then the mysql processing file, a javascript to return the requested data and a html file, where the results are displayed. So, my problem is, that I can't display the results under index.html. Therefore I tried to action directly to landmarks.php and there I can see the reuslts in array like this
([{"id":"1","name":"Big Ben","latitude":"51.500600000000","longitude":"-0.124610000000"}]);
The request.html file
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<form method="post" action="landmarks.php">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<label for="l_name"><b>Name</b></label>
<input type="text" name="l_name" id="l_name" value="" />
<input class="submit" type="submit" value="Submit" />
</fieldset>
</div>
</form>
</body>
Then this file for mysql
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "test";
$password = "test132";
$database = "landmarks";
$l_name = $_POST["l_name"];
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude FROM landmarks WHERE l_name like '".$l_name."' ORDER BY l_name";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
my json callback looks like this
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'landmarks.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.latitude+'<br>'
+ item.longitude+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.')
}
});
});
and finally my final page, where the results should be displayed
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/load-json.js"></script>
</head>
<body>
<div id="output"></div>
</body>
</html>

Categories

Resources