I'm trying to visualize sql database. At the end I hope to see some kind of chart but I can't transform values from php to js and html. In my database are two entries from the same form. First file is a php file and I called it "read.php":
<?php
$con=mysqli_connect("localhost","root","password","databasename");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tablename");
while($row = mysqli_fetch_array($result)) {
$data[] = array(
'join_date' => $row['join_date'],
'column1' => $row['column1'],
'column2' => $row['column2'],
'column3' => $row['column3'],
'column4' => $row['column4']
);
echo json_encode($data);
}
mysqli_close($con);
?>
When I open this file I see it as json. I would like to see these columns in a html file so I made "readjson.html":
<!DOCTYPE html>
<html>
<body>
<h2> Database in html</h2>
One: <p1 id="origname1"></p1><br>
two: <span id="origname2"></span><br>
<script type="text/javascript" >
var baza = "<?php ($data )[http://localhost/read.php]; ?>";
document.getElementById("origname1").innerHTML=baza[0].join_date + ", " + baza[1].column1 + ", " + baza[0].column2 + ", " + baza[0].column3 + ", " + baza[0].column4;
document.getElementById("origname2").innerHTML=baza[1].join_date + ", " + baza[1].column1 + ", " + baza[1].column2 + ", " + baza[1].column3 + ", " + baza[1].column4;
</script>
</body>
</html>
When I open the readjson.html I see:
Database in html
One: undefined, undefined, undefined, undefined, undefined
two: undefined, undefined, undefined, undefined, undefined
Instead of undefined I would like to see the database entries. Please help.
Firsly, I want to know how you came up with this:
"<?php ($data )[http://localhost/read.php]; ?>";
This is no PHP syntax. What you want is to include that file, and in read.php do not print json_encode
<?php
$con=mysqli_connect("localhost","root","password","databasename");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tablename");
$data = array();
while($row = mysqli_fetch_array($result)) {
$data[] = array(
'join_date' => $row['join_date'],
'column1' => $row['column1'],
'column2' => $row['column2'],
'column3' => $row['column3'],
'column4' => $row['column4']
);
}
mysqli_close($con);
?>
Then including it:
<?php
include 'read.php';
?>
<!DOCTYPE html>
<html>
<body>
<h2> Database in html</h2>
One: <p1 id="origname1"></p1><br>
two: <span id="origname2"></span><br>
<script type="text/javascript" >
var baza = JSON.parse(<?php echo '"' . json_encode($data) . '"'; ?>);
document.getElementById("origname1").innerHTML=baza[0].join_date + ", " + baza[1].column1 + ", " + baza[0].column2 + ", " + baza[0].column3 + ", " + baza[0].column4;
document.getElementById("origname2").innerHTML=baza[1].join_date + ", " + baza[1].column1 + ", " + baza[1].column2 + ", " + baza[1].column3 + ", " + baza[1].column4;
</script>
</body>
</html>
I can't assure you this will work but do try it out!
Related
So I am trying to display the information that I have retrieved from a database and I'm using Javascript to pass these info to their corresponding tags using the IDs. I have no problem with outputting the text, but I am having a hard time to output the images in the database which is a MediumBLOB.
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var buffer = new Buffer(userid.images);
var bufferBase64 = buffer.toString('base64');
$('#img').attr("src", "data:image/jpeg;base64," + bufferBase)
});
$('#viewModal').modal("show");
}
As for the update.php, here is the condition that receives the Post method.
<?php
$conn = mysqli_connect('localhost', 'root', '', 'phpfinals');
if($conn->connect_error)
{
echo "$conn->connect_error";
die("Connection Failed : ".$conn->connect_error);
}
//Sending details to be viewed
if(isset($_POST['sendview']))
{
$user_id = $_POST['sendview'];
$stmnt = mysqli_query($conn,"SELECT `username`, `password`, `firstname`, `middlename`, `lastname` , `gender`, `yearlevel`, `position`, `accesslevel`, `images` FROM phpfinals.records WHERE `username` = $user_id");
$result=array();
while($row = mysqli_fetch_assoc($stmnt))
{
$result = $row;
}
echo json_encode($result);
}
else
{
$response['status'] = 200;
$response['message'] = "Invalid or data not found";
}
?>
try creating an URL object
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var objectURL = URL.createObjectURL(userid.images);
$('#img').attr("src", objectURL)
});
$('#viewModal').modal("show");
}
and as a suggestion not related to your question instead of echo should be better use return for send the result
return json_encode($result);
I am attempting to assign a PHP variable to a JavaScript variable. When I do 'console.log(ca)'; the console logs it as being an empty variable. But if I click "view page source code" it shows the variable being set correctly.
JavaScript:
function checkAnswer(o, header) {
x = document.getElementById(o);
var ca = "<?php echo $value['a']; ?>";
if (x.value == ca) {
document.getElementById(header).className = 'header bg-green';
console.log("test");
} else {
document.getElementById(header).className = 'header bg-red';
console.log("User: " + x.value + " Answer: " + ca);
}
}
Console Response:
User: Driller Answer:
Page Source Code:
function checkAnswer(o, header) {
x = document.getElementById(o);
var ca = "Driller";
if (x.value == ca) {
document.getElementById(header).className = 'header bg-green';
console.log("test");
} else {
document.getElementById(header).className = 'header bg-red';
console.log("User: " + x.value + " Answer: " + ca);
}
}
HTML/PHP that is calling the function:
<input type='radio' id='".$value['id']."1' name='".$value['id']."' value='".$value['o1']."' onChange='checkAnswer(\"".$value['id']."1\", \"header_".$value['id']."\")'/>
Can you help explain what you are trying to achieve?? as it is very unclear
x.value cannot equal "ca" from the description you gave.
Also you need to add the element with the id header_* to your question
<div id = 'header_" . $value['id'] ."'>
</div>
So that the onchange function can actually run.
The problem is that you are setting an element's property which does not exist in your DOM HTML.
That's why it is showing an error in console. [See Image]
You need to create an element of id header OR comment on the lines which are changing the header's class.
See below code which I have tested.
<?php
$value = array('id'=>1, 'o1' => 'Driller', 'a' => 'Driller');
echo "<input type='radio' id='" . $value['id'] . "1' name='" . $value['id'] . "' value='" . $value['o1'] . "' onChange='checkAnswer(\"" . $value['id'] . "1\", \"header_" . $value['id'] . "\")'/>
";
?>
<script>
function checkAnswer(o, header) {
x = document.getElementById(o);
var ca = "<?php echo $value['a']; ?>";
if (x.value == ca) {
//document.getElementById(header).className = 'header bg-green';
console.log("test");
} else {
//document.getElementById(header).className = 'header bg-red';
console.log("User: " + x.value + " Answer: " + ca);
}
}
</script>
I have the following code which checks the form before submitting on the server side, what I would like to include (if possible) is to check the message for URLs and if present to prevent the message from being sent.
if (!empty($_POST['name']) && !empty($_POST['fromemail']) && !empty($_POST['message']) && $go == TRUE)
{
//data has been filled
$name = Filter::no_html($_POST['name']);
$from = Filter::no_html($_POST['fromemail']);
$start_dt = Filter::no_html($_POST['start_dt']);
$end_dt = Filter::no_html($_POST['end_dt']);
$comments = Filter::no_html($_POST['message']);
$validate->isEmpty($name, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_NAME);
$validate->isEmpty($from, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_EMAIL);
$validate->isSingleEmail($from, LANG_JAVASCRIPT_PLEASE_ENTER_EMAIL);
$validate->isEmpty($start_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_START_DATE);
$validate->isEmpty($end_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_END_DATE);
$validate->isEmpty($comments, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_MESSAGE);
$modules->call_hook('contact_owner_submit', ''); // Call any module functions
$id = (int) #$_POST['ownerid'];
$vehicle = (int) #$_POST['listingid'];
if ($validate->isError())
{
You could search the message using the stristr method for certain criteria within the string:
$has_url = (stristr($comments, 'http') || stristr($comments, 'www.'));
if($has_url) {
// prevent submit
}
More info on the stristr method here:
https://www.php.net/manual/en/function.strstr.php
So your code could look like this:
if (!empty($_POST['name']) && !empty($_POST['fromemail']) && !empty($_POST['message']) && $go == TRUE) {
$has_url = (stristr($_POST['message'], 'http') || stristr($_POST['message'], 'www.'));
if($has_url) {
// whatever happens if contains url
}
$name = Filter::no_html($_POST['name']);
$from = Filter::no_html($_POST['fromemail']);
$start_dt = Filter::no_html($_POST['start_dt']);
$end_dt = Filter::no_html($_POST['end_dt']);
$comments = Filter::no_html($_POST['message']);
$validate->isEmpty($name, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_NAME);
$validate->isEmpty($from, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_EMAIL);
$validate->isSingleEmail($from, LANG_JAVASCRIPT_PLEASE_ENTER_EMAIL);
$validate->isEmpty($start_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_START_DATE);
$validate->isEmpty($end_dt, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_END_DATE);
$validate->isEmpty($comments, LANG_JAVASCRIPT_PLEASE_ENTER . " " . LANG_YOUR_MESSAGE);
$modules->call_hook('contact_owner_submit', ''); // Call any module functions
$id = (int) #$_POST['ownerid'];
$vehicle = (int) #$_POST['listingid'];
if ($validate->isError())
// whatever goes here
{
}
Hello there am trying to get the data from database using ajax posts but i didn't get any data properly. first column data is splinting in another columns(Member names are coming in image field and info field). Image also shared please check that. And also datatables are not working while fetching the data using Ajax. Help me out from this problem...
Thanks & Regards
<body>
<label>Party</label>
<select id='partydropdown' name='partydropdown' onchange="partyFunction();">
<option>--select a party--</option>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<option value="<?php echo $row["Id"];?>">
<?php echo $row["PartyName"];?>
</option>
<?php }}?>
</select>
<div id="showhide"></div>
</body>
<script type="text/javascript">
function partyFunction(){
debugger;
$("#showhide").empty();
$("#showhide").html('');
$("#showhide").append("<table class='table table-bordered text-center table-responsive' border='1px' id='example'>"+
"<tr>"+
"<th>PartyMemberName</th>"+
"<th>Image</th>"+
"<th>Info</th>"+
"</tr>"+
"<tbody id='partyBody'>"+
"</tbody>"+
"</table>"
);
$postdata = {};
$postdata["Id"]=$("#partydropdown").val();
console.log($("#partydropdown").val());
$.post('test_data.php',$postdata,function (data) {
debugger;
console.log(data);
console.log(data["data"][0].candiateName);
$("#partyBody").empty();
$("#partyBody").html('');
console.log(data["data"]);
console.log(data["data"].length);
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
$("#partyBody").append("<tr>"+
"<td id='resdata"+i+"'></td>"+
"<td id='resdata1"+i+"' ></td>"+
"<td id='resdata2"+i+"'></td>"+
"</tr>");
$("#resdata"+i).text(data["data"][i].candiateName);
$("#resdata1"+i).append("<img id='photo"+i+"'>");
$("#resdata2"+i).text(data["data"][i].Background);
$("#photo"+i).attr('src', 'http://aptsvotes.com/wp-content/themes/apts2019/img'+data["data"][i].Photo );
}
}
});
};
</script>
here is the test_data.php code
<?php
include_once "conn.php";
include_once "voterdbclass.php";
session_start();
$tbl_name2="Parties";
$dbObj = new Database1();
$values1 = array("all");
$querys = "SELECT c1.CandidateName,c1.Photo,c1.Background ,c1.Type FROM aptsv1_votes.Parties p1 LEFT JOIN aptsv1_votes.Candidates c1 ON c1.CurrentPartyId = p1.Id where p1.Id ='" . $_POST['Id'] . "' limit 21";
$res = $dbObj->SelectRecord($tbl_name2,$values1,"","$querys");
$data=array();
$i=0;
while ($rs = $res->fetch_array(MYSQLI_ASSOC)) {
$data[$i]['candiateName']=$rs['CandidateName'];
$data[$i]['Photo']=$rs['Photo'];
$data[$i]['Background']=$rs['Background'];
$i++;
}
$json_array= array(
"data" =>$data
);
echo json_encode($json_array);
?>
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
var imge = data["data"][i].Photo;
var name = data["data"][i].candiateName;
var bg = data["data"][i].Background;
$("#partyBody").append("<tr>"+
"<td id='resdata" + i + "'>" + name+"</td>"+
"<td id='resdata1" + i + "' ><img id= 'photo" + i + "' src='http://aptsvotes.com/wp-content/themes/apts2019/img'" + imge+"></td>"+
"<td id='resdata2" + i + "'>" + bg+"</td>"+
"</tr>");
}
}
You have to parse JSON data into the first script. While ajax result you posting with json_encode, I found missing
var data = $.parseJSON(data);
console.log(data["data"].length);
into code
$.post('test_data.php',$postdata,function (data) {
// debugger;
console.log(data);
var data = $.parseJSON(data); // Add this line in your code and verify
console.log(data["data"].length);
Thank you!
So I'm trying to create a weekly calendar.
I coded a loop in javascript creating the empty table and then afterwards modified the innerHTML of the appropriate td's from values taken from an SQL table using php and javascript.
My problem is that when I set the rowspan of the specific td instead of merging with the next td's it is moving them to the end of my table. If I have 2 more reputation points i will post pictures to show my problem.
Here is my code if you want to take a look at it
// Declare usefull information about the database and host
$mysql_host = "-host info-";
$mysql_database = "-database info-";
$mysql_user = "user";
$mysql_password = "pass";
// open the connection
$link = mysql_connect($mysql_host,$mysql_user, $mysql_password, $mysql_database);
// connect to the database
mysql_select_db($mysql_database, $link) or die('database not selected'. mysql_error());
// Select * from the table created in the database
$result = mysql_query("SELECT * FROM Appointment;")
or die("Could not query:" . mysql_error());
echo "<script type='text/javascript' > "
. "var hours = new Array('9:00','9:30','10:00','10:30','11:00','11:30', "
. "'12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30');"
. ""
. "var days = new Array('Mon','Tue','Wed','Thu','Fri','Sat');"
. ""
. "for ( i = 0; i < 14 ; i++ ) "
. "{"
. "document.write('<tr id='+hours[i]+':00'+'>');"
. "document.write('<th>'+ hours[i]+'</th> '); "
." for ( k = 0 ; k < 6; k++)"
."{"
. "document.write('<td id='+days[k] +'> </td>'); "
. "}"
. "document.write('</tr>');"
."}"
. " </script> ";
while( $row = mysql_fetch_array( $result ))
{
$timestamp = strtotime($row['Date']);
$day = date('D', $timestamp);
$from = $row['StartTime'];
$to = $row['EndTime'];
$rowspan = determinRowSpanBetween($from,$to);
echo "<script type='text/javascript'> "
. " var divToAddTo = GetElementInsideContainer('".$from."','".$day."');"
. "divToAddTo.className = 'busy';"
. "divToAddTo.rowspan='".$rowspan."';"
. "divToAddTo.innerHTML='Something to do';"
. "function GetElementInsideContainer(containerID, childID) {"
. " var elm = {};"
. " var elms = document.getElementById(containerID).getElementsByTagName('*');"
. " for (var i = 0; i < elms.length; i++) {"
. " if (elms[i].id === childID) {"
. " elm = elms[i];"
. " break;"
. " }"
. "}"
. "return elm;"
. "}"
. " </script>" ;
}
the function determinRowSpanBetween is created later on in the code.
Having a rowspan > 1 in a td that is only supposed to take up one space (i.e. one that is not merged with other td's) will cause a whole bunch of errors. Make sure you account for every row you add to rowspan.