How to save multiple dynamic data in database - javascript

I am making a survey question portal in which certain questions will appear on certain conditions like if age-band='18-25' and residential status='Homeowner' then questions like what brand is your washing machine and Do you have any mortgage will appear. If age-band = 26-30 and residential-status ='Rent Council' then question "Do you have a life insurance?" This will appear. Now I have written the code to display the questions but I am unable to save the respective questions and answers in the database.
This is what I have tried so far.
(//Code for first.php)
<?php
include 'connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<form method="POST" action="display1.php">
<select name="age_id">
<?php
$query = mysqli_query($con,"select * from age");
while ($rows = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $rows['id']?>"><?php echo $rows['age']; ?></option>
<?
}
?>
</select><br>
<select name="res_id">
<?php
$query = mysqli_query($con,"select * from residential");
while ($rows = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $rows['id']?>"><?php echo $rows['residential_status']; ?></option>
<?
}
?>
</select><br>
<input type="submit" name="sub" value="SUBMIT">
</form>
</body>
</html>
(//code for display1.php)
<?php
include 'connect.php';
$age_id = $_POST['age_id'];
$res_id = $_POST['res_id'];
$res = mysqli_query($con,"select * from parent_questions where age_id ='$age_id' && residential_id = '$res_id'");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<style type="text/css">
#new{display: none;};
</style>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery#3.6.0/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<!-- cdn link for ajax -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="submit.php">
<tbody>
<?php
while($rows=mysqli_fetch_assoc($res)){
$opt_arr=explode("|",$rows['qoption']);
?>
<tr id="div_<?php echo $rows["qid"]; ?>">
<td><?php echo $rows['question']; ?></td>
<td>
<select class="form-control" name="<?php echo $rows['qid']; ?>">
<option value="">Select</option>
<?php
foreach($opt_arr as $v){
?>
<option value="<?php echo trim($v); ?>"><?php echo $v; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<?php
}
?>
</tbody>
<input type="submit" name="sub" value="SUBMIT">
</form>
<script type="text/javascript">
function newfun(datavalue){
document.getElementById('new').style.display='block';
$.ajax({
url: 'backend.php',
type: 'POST',
data: { datapost : datavalue},
success: function(result){
$('#getdata').html(result);
}
});
}
</script>
</body>
</html>
Now I can't use a static name for select because it will keep changing so I am just confused how will I be able to insert the respective question's option in the database like the washing machine question's option in washing machine field and insurance and mortgage options in mortagage field respectively.

You can use array based names like:
<select class="form-control" name="Rows[<?php echo $rows['qid']; ?>]">
and in php get it as $_POST['Rows']['mortagage'] or anything else.
all inputs will available in $_POST['Rows'] array
you can use <?= "s.th" ?> instead of <?php echo "s.th" ?>

Related

JS/HTML/PHP in one PHP program and MYSQL Updates via Server Sent Events

I'm building a two-way chat application that stores messages into a MySQL database. I would like to use Server Sent Events and have the PHP and HTML all in one page but the problem I'm facing is that the header cannot be set to text/event-stream or I will break the HTML.
My question is how can I have the PHP, JS and HTML on the same page when using Server Sent Events?
Here is my opening JS. I set the EventSource to index.php even though this might be wrong.
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index.php");
source.onmessage = function(event) {
document.getElementsByClassName("message").innerHTML = event.data;
};
}else {
document.getElementsByClassName("message").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream");
}
else {
header("Content-Type: text/html");
}
//Database Stuff
$connect = mysqli_connect('localhost', 'user', 'Pass');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
?>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<?php echo "data: ".$row['mymessages']; flush();?>
</div>
</div>
<?php
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
?>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<?php echo "data: ".$row['yourmessages']; flush();?>
</div>
</div>
<?php
}
}
?>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
EDIT: I have tried separating the PHP the HTML and put the PHP logical part outside the HTML. I'm able to get Server Sent Events via inspector in Chrome but not sure how to loop through the DB entries in JS. I'm not comfortable with JS syntax.
<?php
$SSE = (#$_SERVER["HTTP_ACCEPT"] == "text/event-stream");
if($SSE){
header("Content-Type: text/event-stream");
header('Cache-Control: no-cache');
if(isset($_POST['submit'])){
$send = $_POST['mymessage'];
$sendmsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('".$send."', '')";
}
if (!empty($_GET['yourmessage'])){
$recieve = $_GET['yourmessage'];
$recievemsg = "INSERT INTO lora_messages (mymessages, yourmessages) VALUES ('', '".$recieve."')";
}
$connect = mysqli_connect('localhost', 'root', 'Walcott34');
mysqli_select_db($connect,"allmessages");
$sql = "SELECT *, if(mymessages > yourmessages, mymessages, yourmessages) FROM lora_messages";
$sqlrecieve = mysqli_query($connect, $recievemsg);
$sqlsend = mysqli_query($connect, $sendmsg);
$results = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($results)) {
if ($row ['mymessages'] > $row ['yourmessages']){
echo "data: ".$row['mymessages']."\n\n";
}
elseif ($row ['mymessages'] < $row ['yourmessages']){
echo "data: ".$row['yourmessages']."\n\n";
}
ob_flush();
flush();
}
}
else {
?>
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("index2.php");
source.onmessage = function(e){
document.getElementById("mymessages").innerHTML = event.data;
document.getElementById("yourmessages").innerHTML = event.data;
};
}else {
document.getElementsById('message').innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<h1>LoRa Chat</h1>
<div class='chat'>
<div class='mine messages'>
<div class='message'>
<div id='mymessage'>
</div>
</div>
</div>
<div class='chat'>
<div class='yours messages'>
<div class='message'>
<div id='yourmessage'>
</div>
</div>
</div>
<div class="fixed">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" Method="POST">
<input type="text" id="body" name="mymessage">
<input type="submit" value="Submit" name="submit">
</form>
</div>
<br>
</body>
</html>
<?php } ?>
If your after it being in one file you just need the one outer if statement which separates the two logical parts.
<?php
if ($_SERVER["HTTP_ACCEPT"] === 'text/event-stream') {
// event stream code
...
while (true) {
...
} else {
// client side code
?>
<head>
<meta name="viewport" content="w
...
<?php }
You cant intertwine the two parts like your doing:
<div class='message'>
<?php echo "data: $row['mymessages']"; flush();?>
</div>
Your serverside part is incomplete but that's beyond the scope of the question,ive commented with a link to a working example.

Create table column headers from selected values of a drop down list

I am using this example of a multiple selection dropdown list
index.php
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | How to Use Bootstrap Select Plugin with PHP JQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<br />
<h2 align="center">How to Use Bootstrap Select Plugin with PHP JQuery</h2>
<br />
<div class="col-md-4" style="margin-left:200px;">
<form method="post" id="multiple_select_form">
<select name="framework" id="framework" class="form-control selectpicker" data-live-search="true" multiple>
<option value="Laravel">Laravel</option>
<option value="Symfony">Symfony</option>
<option value="Codeigniter">Codeigniter</option>
<option value="CakePHP">CakePHP</option>
<option value="Zend">Zend</option>
<option value="Yii">Yii</option>
<option value="Slim">Slim</option>
</select>
<br /><br />
<input type="hidden" name="hidden_framework" id="hidden_framework" />
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
</form>
<br />
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
$('#framework').change(function(){
$('#hidden_framework').val($('#framework').val());
});
$('#multiple_select_form').on('submit', function(event){
event.preventDefault();
if($('#framework').val() != '')
{
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
//console.log(data);
$('#hidden_framework').val('');
$('.selectpicker').selectpicker('val', '');
alert(data);
}
})
}
else
{
alert("Please select framework");
return false;
}
});
});
</script>
It works fine but I am trying to adjust the code mentioned on the page according my needs. I want to create a dynamic table with columns name what i selected from the Dropdown list
so instead of creating the table manually and giving names of the columns as my code here
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ser="10.90.294.23";
$db="Framework";
$user="test";
$pass="test0";
$query = 'SELECT Laravel, Symfony, Codeigniter, CakePHP FROM Framework.list';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=10.90.294.23,1456;Database=Framework;Port=1456", $user, $pass);
?>
<!DOCTYPE html>
<html>
<head>
<title>HTML table using Jquery with PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container" style="width:700px;">
<h3 class="text-center">HTML table using Jquery with PHP</h3><br />
<div class="table-responsive" id="employee_table">
<table class="table table-bordered">
<tr>
<th width="10%">Laravel</th>
<th width="30%">Symfony</th>
<th width="10%">Codeigniter</th>
<th width="50%">CakePHP</th>
</tr>
<?php
foreach ($dbDB->query($query) as $row) {
?>
<tr>
<td><?php echo $row['Laravel']; ?></td>
<td><?php echo $row['Symfony']; ?></td>
<td><?php echo $row['Codeigniter']; ?></td>
<td><?php echo $row['CakePHP']; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<br />
</body>
</html>
I want the columns headers will be created automatically from the selected values.
I was thinking about storing the selected value in variable for example : Laravel,CakePHP,Yii,Slim then I create the header based on each text between the comma ","
Can anyone help with this please ? I have tried many ways but still can't make it work. Thank you.
If this is the same as the example then I would have thought your table would have one row and be comma delimited. This really isn't the best way but for your example you need to do.
$row = $dbDB->query($query);
$rows = explode(",",$row);
?>
<tr>
<?php
foreach ($rows as $r ) {
?>
<td><?php echo $r; ?></td>
<?php
}
?>
</tr>

Simple ajax post Uncaught ReferenceError

Hello I have a simple ajax call but I can not see the result. What am I doing wrong ? Thank You.
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function prova(SelectedFriend){
$.post("result.php", {Selected:Selected});
return false;
}
</script>
</head>
<body>
<?
$user="name1";
?>
<div onclick="prova(<? echo $user; ?>)" style="cursor:pointer;">
<? echo $user; ?>
</div>
<?
$user="name2";
?>
<div onclick="prova(<? echo $user; ?>)" style="cursor:pointer;">
<? echo $user; ?>
</div>
<?
$user="name3";
?>
<div onclick="prova(<? echo $user; ?>)" style="cursor:pointer;">
<? echo $user; ?>
</div>
<div id="Result"></div>
</body>
</html>
and result.php
<?
echo $_POST['Result'];
?>
The console of my browser says "Uncaught ReferenceError: name1 is not defined" when I click on name1.
The $user must be placed inside simple quotes:
<div onclick="prova('<? echo $user; ?>')" style="cursor:pointer;">
Also your function is not using the parameter as it should:
function prova(SelectedFriend){
$.post("result.php", {SelectedFriend:SelectedFriend});
return false;
}
And the result.php file must be corrected as well:
<?php
echo $_POST['SelectedFriend'];

JQuery Autocomplete from Database

I need to to do autocomplete suggestion for my website and the data should be retrieved from database. I want to use JQuery autocomplete. here is my code but it doesn't work!
This is my php file with the name of gethint.php:
<?php
require_once ('config.php');
$q=$_REQUEST["q"];
$sql="SELECT `fname` FROM `Property` WHERE fname LIKE '%$q%'";
$result = mysql_query($sql);
$json=array();
while($row = mysql_fetch_array($result)) {
$json[]=array(
'value'=> $row['fname'],
'label'=> $row['fname']
);
}
echo json_encode($json);
?>
and then this is my html file :
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#hint").autocomplete({
source:'gethint.php',
minLength:1
});
});
</script>
</head>
<body>
<form class="sansserif" action="view.php" method="post">
Name: <input type="text" id="hint" name="hint" >
<input type="submit" name="submit" value="View">
</form>
</html>
It took a lot of time but I couldn't find the problem. I was wondering if someone could help me.
Thanks.
<?php
require_once ('..\config.php');
$q=$_REQUEST["term"];
$sql="SELECT `fname` FROM `Property` WHERE fname LIKE '%$q%'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$json[]=array(
'value'=> $row['fname'],
'label'=> $row['fname']
);
}
echo json_encode($json);
?>
All I changed was the $_REQUEST["q"] to $_REQUEST["term"].
I did some changes, maybe you need to fix something but take a look to see if helps...
The php:
<?php
require_once ('config.php');
$q=$_REQUEST["q"];
$sql="SELECT `fname` FROM `Property` WHERE fname LIKE '%$q%'";
$result = mysql_query($sql);
$json=array();
while($row = mysql_fetch_array($result)) {
array_push($json, $row['fname']);
}
echo json_encode($json);
?>
The html+jquery:
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
</head>
<body>
<form class="sansserif" action="view.php" method="post">
Name: <input type="text" id="hint" name="hint" />
<input type="submit" name="submit" value="View">
</form>
<script type="text/javascript">
$(function() {
$( "#hint" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "gethint.php",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
});
});
</script>
</body>
</html>
Your PHP script should be accepting a term parameter, not q.

Using Javascript to load image into a div onClick

I've been trying for two days to figure out what I am doing wrong. I really think that this code should work, but it doesn't. If I swap out the variable on line 57 it will bring up a file onClick. So logically the problem is the variable. But when I trace the variable on line 60, the variable is returning the correct value. So why won't the image load correctly? When I click on the button, simply nothing happens.
++EDIT++
I've tried a bunch of things, and the problem is absolutely with the variable $file. No matter how I test it, $file corresponds to the id number of the item on the list. But when I hit the button, it always pulls item 1. I even went back and edited the code to read:
<img id="loadingImage" src="../maps/<?php echo $name['id']?>.gif" style="visibility:hidden"/>
There is no reason on earth that I can find that this isn't working. 'id' is iterating properly. So why does it think 'id'=1 only after I hit the button?
Here's the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html lang="en">
<head>
<meta charset="utf-8">
<title>List of Parks</title>
<link href="guide.css" rel="stylesheet" type="text/css">
<style type="text/css"></style>
<script type="text/javascript" src="../jQuery/jQuery.js"></script>
<script type="text/javascript">
<!--
function showImage() {
document.getElementById('loadingImage').style.visibility = 'visible';
}
-->
</script>
</head>
<body>
<div id="container">
<div id="state"></div>
<div id="list">
<?php foreach ($datas as $name):
{
if ($name['state'] == 'PA')
{
?>
<input type="hidden" name="id" value="<?php echo $name['id']; ?>">
<h2><?php echo htmlspecialchars($name['name'], ENT_QUOTES, 'UTF-8');?></h2>
<?php htmlspecialchars($name['site'], ENT_QUOTES, 'UTF-8');?>
<?php $link = $name['site']; ?>
<ul id="link">
<li class="l1"><?php echo "<a href=$link>$link</a>" ?></li>
</ul>
<br>
<?php echo htmlspecialchars($name['description'], ENT_QUOTES, 'UTF-8');?>
<?php echo htmlspecialchars($name['street'], ENT_QUOTES, 'UTF-8');?>
<br>
<?php echo htmlspecialchars($name['city'], ENT_QUOTES, 'UTF-8');?> ,
<?php echo htmlspecialchars($name['state'], ENT_QUOTES, 'UTF-8');?>
<?php echo htmlspecialchars($name['zip'], ENT_QUOTES, 'UTF-8');?>
<?php $file = $name['id'];
$image = '../maps/'.$file.'.gif';?>
<input type="button" value="click for map" onclick="showImage();" />
<div id="trailmap">
**<img id="loadingImage" src="<?php $image ?>" style="visibility:hidden" />**
</div>
<?php echo $image?>
<hr width="100%" size="3" black />
<?php
}
}
endforeach; ?>
</div>
</div>
<div class="fixbox">
<div id="statemap"></div>
<div id="home"></div>
<div id="guide"></div>
</div>
</body>
</html>

Categories

Resources