Cannot set property 'innerHTML' of null in AJAX Call - javascript

I have looked through about 30 different articles about this error on this site and have not found the answer I need.
I am getting the dreaded Cannot set property 'innerHTML' of null message when I click a cell in my div table i created. I have checked the order of the page load to make sure that the JS is below the html tags.
I think is may have to do with using a variable name in the getElementById syntax.
Here is my code I am using (sorry for the noobish style of coding):
<HTML>
</HEAD>
<BODY>
<table border=1>
<tr><td colspan="11"><center><h2>Away Team</h2></center></td></tr>
<?php
$ROWMAX=3;
$COLMAX=3;
//Rows = j
for($j=-1;$j<=$ROWMAX-1;$j++){
echo "<tr>";
//Columns = i
for($i=-1;$i<=$COLMAX-1;$i++) {
if($i == -1 && $j == -1){
echo "<th class='header-cols'></th>"; }
elseif($i == -1 && $j >= 0){
echo "<th class='header-rows'><h1>$j</h1></th>";
}
elseif($j<0){
echo "<th class='header-cols'><h1>$i</h1></th>";
}
else {
$sql = "SELECT name FROM picks WHERE col=$i AND row=$j LIMIT 1";
$data = $conn->query($sql);
while($rows=$data->fetch_assoc()){
$currName = $rows['name'];
$cellStatus = $rows['status'];
}
echo "<td class='grid-cells'>
<div id='cell-$j-$i' class='$cellStatus' onclick='setCoords($j,$i);'>
<div class='grid-num'>" . (($i+1)+($j*$COLMAX)) . "</div>
<div class='grid-name-$j-$i'>$currName</div>
</div>
</td>";
$currName="";
}
}
echo "</tr>";
} ?>
</table>
<form method="post" onSubmit="setSquare()">
<div>
<h3>Submit Your Picks:</h3>
<label for="name" class="ui-hidden-accessible">Name:</label>
<input type="text" name="name" id="nameid" placeholder="Name"><br />
<label for="email" class="ui-hidden-accessible">Email:</label>
<input type="text" name="email" id="emailid" placeholder="Email"><br />
<input type="submit" data-inline="true" id='submitbtn' class='btndisabled' value="Make Picks" disabled>
<div id='row-div'></div>
<div id='col-div'></div>
</div>
</form><SCRIPT>
function setCoords(row_coords, col_coords){
var txt_name = document.getElementById("nameid").value;
var txt_email = document.getElementById("emailid").value;
if (txt_name != "" && txt_email != ""){
document.getElementById("cell-"+row_coords+"-"+col_coords).className = "picked";
setSquare(row_coords, col_coords);
document.getElementById("submitbtn").className = "btnenabled";
}
else
{ alert("Please fill in your name and email before making a pick"); }
}
function setSquare(row,col)
{
//get id vales from form
var name_id = document.getElementById("nameid").value;
var email_id = document.getElementById("emailid").value;
var row_id = row;
var col_id = col;
var gridname = "grid-name-"+row+"-"+col;
//run the ajax code here
if(name_id != ""){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById(gridname).innerHTML = this.responseText;
//alert("grid-name-"+row_id+"-"+col_id);
//alert(this.responseText);
}
};
xmlhttp.open("POST","save-square.php?name="+name_id+"&email="+email_id+"&row="+row_id+"&col="+col_id,true);
xmlhttp.send();
}
}
</SCRIPT>
</BODY>
</HTML>

Spot the differences:
<div id='cell-$j-$i' class='$cellStatus' onclick='setCoords($j,$i);'>
^^
<div class='grid-name-$j-$i'>$currName</div>';
^^^^^
var gridname = "grid-name-"+row+"-"+col;
document.getElementById(gridname).innerHTML = this.responseText;
^^
class is NOT an id, and will NOT be found by a getElementById() - note the ID part of that function name.

Change the Html code below
<div class='grid-name-$j-$i'>$currName</div>
to
<div id='grid-name-$j-$i'>$currName</div>
Because you are reference them by ID in your code
document.getElementById(gridname).innerHTML = this.responseText;

Related

Edit input name when chceckbox clicked

I try to edit name field for the specific input. I need this to get all the variables from this site and add them to my invoice script. I have two divs with client select and service select
HTML:
<div class="service-select">
<?php
$query = "SELECT id,service_name,quantity,net_price,gross_value FROM service";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
?>
<div class='single-service-<?php echo $row["id"]; ?>'>
<input type='checkbox' name=''>
<input type="text" name="service_name" class='name' value="<?php echo $row["service_name"]; ?>" placeholder='NAZWA USŁUGI' disabled/>
<label>Ilość:</label><input type="number" name="quantity" value="<?php echo $row["quantity"]; ?>" placeholder='ILOŚĆ' disabled/>
<label>Cena netto:</label><input type="number" name="net_price" value="<?php echo $row["net_price"]; ?>" placeholder='CENA NETTO' disabled/>
</div>
<?php
}
$result->free();
}
?>
</div>
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for(var i=0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', function() {
var div = this.parentNode;
var name_input = div.getElementsByClassName("name");
var name = name_input.name;
var parent_div = div.parentNode;
var x = div.childNodes;
console.log(name_input);
if (parent_div.className == 'service-select') {
if (name_input.name != 'service_chcecked[]') {
name_input.name = 'service_chcecked[]';
}
else {
name_input.name = 'service_name';
}
}
else {
if (name != 'client_chcecked[]') {
name_input.name = ['client_chcecked[]'];
}
else {
name_input.name = ['client_name'];
}
}
for(y=0; y < x.length; y++) {
if(x[y].type === "number" || x[y].type === "text") {
x[y].disabled = !x[y].disabled;
}
}
}, false);
};
My problem is that currently the given name is added to the div :/

Uploaded file is not passing through JavaScript to PHP

Here i'm trying to pass uploaded file and a text input from HTML->JavaScript->PHP. But it is only passing the text input and failed to pass the file , i'm not getting that file in PHP. As a result it is showing undefined index error for "$u_file" in the PHP file. I don't understand where is the problem.
Here goes the HTML file
<body>
<div class="container">
<form class="form-horizontal" action="">
<h2><b>Post your job</b></h2><br><br>
<div class="form-group">
<label class="control-label col-sm-2">Job Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="jName" placeholder="Enter job name" name="jName" required>
<p id="jErr"></p>
</div>
</div>
<div class="form-group">
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
<label class="control-label col-sm-2">Add some detailed description:</label>
<div class="col-sm-10">
<input id="u_file" value="u_file" type="file" name="u_file" size="5000000" multiple onchange="showname()"><br><br>
</div>
</form>
</div>
<div class="container-fluid text-center">
<br><button name="submitJob" id="submitJob" type="submit" class="btn btn-default" onclick="job_checker()">Submit</button>
<p id="submitJobErr"></p></div>
</form>
</div>
</body>
Here goes the JavaScript file
signFlagj = 0;
function job_checker() {
checkJobName();
databasejobEntry();
}
function checkJobName() {
var jobnameET = document.getElementById("jName");
var jobnameError = document.getElementById("jErr");
jobname = jobnameET.value;
console.log(jobname);
var regex = /^[a-zA-Z ]*$/;
if(!regex.test(jobname)){
jobnameError.innerHTML = "Only letters and white space allowed";
signFlagj = 1;
}
else {
jobnameError.innerHTML = "";
}
}
function showname() {
jobFilename = document.getElementById('u_file');
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log('Selected file: ' + jobFilename.files.item(0).size);
console.log('Selected file: ' + jobFilename.files.item(0).type);
}
function databasejobEntry() {
if(signFlagj==1) {
console.log("fill up correctly!");
alert("Sign up correctly!");
}
else
{
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log(jobname);
var submitError = document.getElementById("submitJobErr");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
console.log(response);
submitError.innerHTML=response;
alert(response);
if(String(response.trim()) === "Success") {
alert("Successfully submitted :)");
window.location.href = "uploadJob.html";
}
}
}
xhttp.open("GET", "uploadJob.php?jobname="+jobname+"&jobFilename="+jobFilename,true);
xhttp.send();
}
}
Here goes the PHP file
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$val="";
$jobName = $_GET["jobname"];
echo "$jobName";
$u_file = $_FILES['jobFilename'];
$file_type = $_FILES['jobFilename']['type'];
$file_size = $_FILES['jobFilename']['size'];
$file_name = $_FILES['jobFilename']['name'];
print_r($u_file);
//echo "****************";
$currentdir = getcwd();
$targetfolder = $currentdir . "/testupload/";
// echo "****************";
print_r($targetfolder);
$targetfile = $targetfolder . basename( $_FILES['jobFilename']['name']) ;
//print_r($targetfolder);
print_r($currentdir);
//echo "****************";
$uploadOk=1;
print_r($file_type);
if ($file_type != "application/pdf" && $file_type != "image/png" && $file_type != "image/jpeg" && $file_type != "image/jpg") {
echo "Sorry, only JPG, JPEG, PNG & PDF files are allowed.";
$uploadOk = 0;
}
if (file_exists($targetfile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if($uploadOk==0){
echo "Problem in uploading file";
}
else {
if(move_uploaded_file($_FILES['jobFilename']['tmp_name'], $targetfile)) {
$fileUpQueryjob = "INSERT INTO jobs (job_name,job_filename) VALUES ('$jobName','$file_name')";
$upJob = $db->query($fileUpQueryjob);
if ($upJob == true) {
$val = "Success";
echo "The file ". basename( $_FILES['jobFilename']['name']). " is uploaded";
}
else
echo "Error: " . $fileUpQueryjob . "<br>" . mysqli_error($db);
}
}
//echo "$val";
$db->close();
Use POST request instead of GET request. If necessary warp it in new FormData and post it.

how to solve theproblem with saving the data in an appended textbox

please help me out, i use isset to check if the index is defined but instead of saving the value of the textbox it stores 0.how shoul i do it? cause if i wont check if the index is defined ,when i only fill out one textbox it will throw an error, but if i fill out all five it works fine. please take a look at y code, the variables in javascript is used for its inout name, the count is for the stop adding of input text when it reach 5
HTML and PHP
<form class="form-horizontal" method= "POST">
<div class="control-group">
<div class="inc">
<div class="controls">
<button style="margin-left: 50px" class="btn btn-info" type="submit" id="append" name="append">
Add Textbox</button>
<br>
<br>
</div>
</div>
<input type="submit" class="btn btn-info" name="submit" value="submit"/>
</div>
<?php
$host = "localhost";
$dbname = "lala";
$user = "root";
$pass = "";
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
if(isset($_POST['submit'])){
for($i=1; $i<=5; $i++){
if(isset($_POST["textbox$i"]) && $_POST["textbox$i"] !=""){
$sasa = $_POST["textbox$i"];
$sql="INSERT into sasa (sasa) values('$sasa')";
echo $sql."<br>";
$q=$conn->query($sql);
}
}
}
?>
javascript;
<script type="text/javascript">
jQuery(document).ready( function () {
var val = 1;
var me = 0;
var count = 0;
$("#append").click( function() {
if(count<5){
if(me==0){
val=1;
me = me + 1;
count = count +1;
$(".inc").append("<div class='controls'><input class='form-control' type='text' name='textbox"+ val +"' placeholder='textbox"+ val +"'><a href='#' class='remove_this btn btn-danger'>remove</a> <br> <br> </div");
return false;
}
else{
val = val + 1;
me = me + 1;
count = count +1;
$(".inc").append("<div class='controls'><input class='form-control' type='text' name='textbox"+ val +"' placeholder='textbox"+ val +"'><a href='#' class='remove_this btn btn-danger'>remove</a> <br> <br> </div");
return false;
}
}
else{
}
});
jQuery(document).on('click', '.remove_this', function() {
me = me - 1;
count = count - 1;
jQuery(this).parent().remove();
return false;
});
});
both your JS and PHP are wrong. You need to post an array rather than naming each textbox. In other words, your textbox names should be something like name='textbox[]'. Redo it like this:
JS:
$(document).ready(function () {
$("#append").click(function (e) {
e.preventDefault();
var textboxes = $(".textbox").length;
if (textboxes < 5) {
$(".inc").append("<div class='controls'>\
<input class='textbox form-control' type='text' name='textbox[]' >\
<a href='#' class='remove_this btn btn-danger'>remove</a>\
</div>");
}
});
$(document).on('click', '.remove_this', function (e) {
e.preventDefault();
$(this).parent().remove();
});
});
PHP:
if (isset($_POST['submit'])) {
if (!empty($_POST['textbox'])) {
$host = "localhost";
$dbname = "lala";
$user = "root";
$pass = "";
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
$textboxes = $_POST['textbox'];
foreach ($textboxes as $value) {
$sql = "INSERT into sasa (sasa) values('$value')";
echo $sql . "<br>";
$q = $conn->query($sql);
}
}
}
Ok, it seems like your goal is to send a multidimensional array to PHP. In other words, you want PHP to be able to receive something in this format:
array (size=2)
0 =>
array (size=2)
'text' => string 'some text' (length=9)
'box' => string 'some box' (length=8)
1 =>
array (size=2)
'text' => string 'some text' (length=9)
'box' => string 'some box' (length=8)
In order for you to achieve this, you need to create a function that indexes your input textboxes when you create them and when you delete them so that you can end up with inputs with indexed name attributes like so:
<input name="data[0][text]">
<input name="data[0][box]">
<input name="data[1][text]">
<input name="data[1][box]">
With that said, this is the JS I would use:
<script>
$(document).ready(function () {
function re_index($cont) {
$cont.find(".textbox_group").each(function (i) {
$(this).find('.text').attr("name", "data[" + i + "][text]");
$(this).find('.box').attr("name", "data[" + i + "][box]");
});
}
$("#append").click(function (e) {
e.preventDefault();
var $cont = $(".inc");
if ($(".textbox_group").length < 5) {
$cont.append("<div class='controls textbox_group'>\
<input class='text form-control' type='text' >\
<input class='box form-control' type='text' >\
<a href='#' class='remove_this btn btn-danger'>remove</a>\
</div>");
re_index($cont);
}
});
$(document).on('click', '.remove_this', function (e) {
e.preventDefault();
$(this).parent().remove();
var $cont = $(".inc");
re_index($cont);
});
});
</script>
Then in PHP you can capture the data and iterate to insert it with SQL:
$data = $_POST['data'];
foreach ($data as $input) {
var_dump($input['text']);
var_dump($input['box']);
}

POST Json to PHP get VAR

i have a form like this:
<?php
include '../db/baza.php';
?>
<?php include 'vrh.php' ?>
<div id="stranica">
<div id="stranicaOkvir">
<form action="dodaj_sliku_obrada.php" method="POST" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Dodaj sliku</legend>
<?php $upit = "SELECT kategorija_ID, kategorija_naziv FROM kategorije ORDER BY kategorija_ID ASC";
$ispis = mysql_query($upit) or die(mysql_error());
$blok_ispis = mysql_fetch_assoc($ispis);
$ukupno = mysql_num_rows($ispis); ?>
<p><strong>Obavezno odaberite kategoriju kojoj slika pripada</strong></p>
<p> <select name="kategorija" id="kategorija">
<?php do { ?>
<option value="<?php echo $blok_ispis['kategorija_ID']; ?>"> <?php echo $blok_ispis['kategorija_naziv']; ?></option>
<?php } while ($blok_ispis = mysql_fetch_assoc($ispis)); ?>
<?php mysql_free_result($ispis);?>
</select>
</p>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="Dodaj sliku">
<div class="progresbar">
<span class="progresbar-puni" id="pb"><span class="progresbar-puni-tekst" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will apper here.
<script src="js/dodaj_Sliku.js"></script>
<script>
document.getElementById('submit').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'dodaj_sliku_obrada.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
uspjesno_Dodano = document.createElement('div'),
neuspjelo_Dodavanje = document.createElement('div'),
anchor,
span,
x;
if(data.neuspjelo_Dodavanje.length){
neuspjelo_Dodavanje.innerHTML = '<p>Nazalost, sljedece nije dodano: </p>';
}
uploads.innerText = '';
uploads.textContent = '';
for( x = 0; x < data.uspjesno_Dodano.length; x = x + 1){
anchor = document.createElement('a');
anchor.href = '../slike/galerija/' + data.uspjesno_Dodano[x].file;
anchor.innerText = data.uspjesno_Dodano[x].name;
anchor.textContent = data.uspjesno_Dodano[x].name;
anchor.target = '_blank';
uspjesno_Dodano.appendChild(anchor);
}
for( x = 0; x < data.neuspjelo_Dodavanje.length; x = x + 1){
span = document.createElement('span');
span.innerText = data.neuspjelo_Dodavanje[x].name;
span.textContent = data.neuspjelo_Dodavanje[x].name;
neuspjelo_Dodavanje.appendChild(span);
}
uploads.appendChild(uspjesno_Dodano);
uploads.appendChild(neuspjelo_Dodavanje);
},
error: function(){
console.log('Ne radi!');
}
});
});
</script>
<script>
</script>
</div>
</fieldset>
</form>
</div>
</div>
<?php include 'dno.php' ?>
The .js looks like this
var app = app || {};
(function(o){
"use strict";
//Privatne metode
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uspjesno_Dodano;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4){
if(this.status === 200){
uspjesno_Dodano = JSON.parse(this.response);
if(typeof o.options.finished === 'function'){
o.options.finished(uspjesno_Dodano);
}
} else {
if(typeof o.options.error === 'function'){
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event){
var percent;
if(event.lengthComputable === true){
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1){
data.append('file[]', source[i]);
}
data.append('ajax', true);
data.append('kategorija', o.options.kategorija);
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined){
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined){
o.options.progressText.innerText = value ? value + '%' : '';
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(o.options.files !== undefined){
ajax(getFormData(o.options.files.files));
}
}
}(app));
On the process.php part i want to listen the option value from select
"<select name="kategorija" id="kategorija">"
on the process.php when i
<?php
$kategorija = $_POST['kategorija'];
echo echo $kategorija;
?>
i alwasy get a 0 value, so what i am doing wrong? The file[] processing is working fine, but can't get it to work with a addtional variable.
You don't need to echo echo $kategorija; It should be echo $kategorija; If this causes an issue, which it might, try var_dump($kategorija) to view the contents of the variable.
Also, you're including your js throughout the page, this should be refactored and included properly in the head. The php should not be in the form of the document, it should be contained outside and included like you are doing with '../db/baza.php'; Finally, look into using PDO to connect to your db.

storing values in db if selected

question was updated thanks for ur help this code works fine but when i click Confirm Choices the booked count should increase in db and if the user select booked img it should display room has been booked can u please help..
<?php
mysql_connect("localhost","root","");
mysql_select_db("hotel");
error_reporting(E_ALL ^ E_NOTICE);
$notify = "";
$sql = "SELECT * FROM room";
$getquery = mysql_query($sql);
$submit=$_POST['submit'];
if($submit)
{
if($booked)
{
$insert=mysql_query("INSERT INTO room (booked) VALUES ('$taken')");
echo $insert;
}
}
?>
<!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" >
<head>
<title>sample</title>
<script type="text/javascript">
numPremSeatsPerRow = 6;
PremRowNames = ['A','B','C','D'];
numCheapSeatsPerRow = 10;
CheapRowNames = ['E','F','G','H','I'];
statusPics = new Array();
statusPics['avail'] = new Image();
statusPics['mine'] = new Image();
statusPics['taken'] = new Image();
statusPics['vacate'] = new Image();
statusPics['avail'].src = 'blue.jpg';
statusPics['mine'].src = 'green.jpg';
statusPics['taken'].src = 'red.jpg';
statusPics['vacate'].src = 'blue1.jpg';
function createSeats(oSeatsContainer,seatsPerRow,rowNames){
var oRow = document.createElement('tr');
oRow.appendChild(document.createElement('th'));
for(i=1; i <= seatsPerRow; i++){
var oTh = document.createElement('th');
oTh.appendChild(document.createTextNode(i));
oRow.appendChild(oTh);
}
oSeatsContainer.appendChild(oRow); //this row contains the seat numbers
for(i=0; i < rowNames.length; i++){
var oRow = document.createElement('tr');
var oCell = document.createElement('td');
oCell.innerHTML = rowNames[i];
oRow.appendChild(oCell);
for(j=0; j < seatsPerRow; j++){
oCell = document.createElement('td');
var oImg = document.createElement('img');
oImg.src = statusPics['avail'].src;
oImg.status = 'avail';
oImg.id = rowNames[i]+(j+1);
oImg.onclick=function(){
this.status = (this.status == 'avail')? 'mine' : 'avail';
this.src = (this.status == 'avail')? statusPics['avail'].src : statusPics['mine'].src;
oTotalprice.innerHTML = '';
oBookedSeatNos.innerHTML = '';
}
oCell.appendChild(oImg);
oRow.appendChild(oCell);
}
oSeatsContainer.appendChild(oRow);
}
}
function confirmChoices(){
premSeatsSelected = new Array();
for(i=0; i < oPremSeats.length; i++){
if(oPremSeats[i].status == 'mine'){
premSeatsSelected.push(oPremSeats[i].id);
oPremSeats[i].src=statusPics['taken'].src
}
if(oPremSeats[i].status == 'taken'){
premSeatsSelected.push(oPremSeats[i].id);
oPremSeats[i].src=statusPics['vacate'].src
}
}
cheapSeatsSelected = new Array;
for(i=0; i < oCheapSeats.length; i++){
if(oCheapSeats[i].status == 'mine'){
cheapSeatsSelected.push(oCheapSeats[i].id);
oCheapSeats[i].src=statusPics['taken'].src
}
if(oPremSeats[i].status == 'taken'){
premSeatsSelected.push(oPremSeats[i].id);
oPremSeats[i].src=statusPics['vacate'].src
}
}
}
window.onload=function(){
oTblPremium = document.getElementById('tblPremium');
oTblCheap = document.getElementById('tblCheap');
oPremSeats = oTblPremium.getElementsByTagName('img');
oCheapSeats = oTblCheap.getElementsByTagName('img');
oTotalprice = document.getElementById('totalprice');
oBookedSeatNos = document.getElementById('bookedSeatNos');
createSeats(oTblPremium,numPremSeatsPerRow,PremRowNames); //create premium seats
createSeats(oTblCheap,numCheapSeatsPerRow,CheapRowNames); //create cheap seats
document.getElementById('confirm').onclick=confirmChoices;
document.getElementById('btnReset').onclick=function(){
oTotalprice.innerHTML = '';
oBookedSeatNos.innerHTML = '';
for(i=0; i < oPremSeats.length; i++){
oPremSeats[i].src = statusPics['avail'].src;
oPremSeats[i].status = 'avail';
}
for(i=0; i < oCheapSeats.length; i++){
oCheapSeats[i].src = statusPics['avail'].src;
oCheapSeats[i].status = 'avail';
}
}
document.getElementById('imgAvail').src = statusPics['avail'].src;
document.getElementById('imgMine').src = statusPics['mine'].src;
document.getElementById('imgTaken').src = statusPics['taken'].src;
document.getElementById('imgvacate').src = statusPics['vacate'].src;
}
</script>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('avilable').value;
var wpm = document.getElementById('booked').value;
var sex = document.getElementById('vacated').value;
var queryString = "?avilable=" + avilable ;
queryString += "&booked=" + wpm + "&vacated=" + sex;
ajaxRequest.open("GET", "s2-ex.php" +
queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<style>
.tab{
margin-top:10px;
border-radius: 7px;
border: 2px solid #CCCCCC;
margin-bottom:20px;
}
body { margin: auto 48px; }
</style>
</head>
<body>
<form action="s2.php" method="POST">
<div id="header"></div>
<div id="wrapper">
<div id="myTickets">
<h1>hotel Room</h1>
<div id="myTicket">
<h3>Your room Selection:</h3>
</div>
<div>
<table>
<thead>
<tr>
<tr>Total</tr>
<tr> </tr>
<tr>Avilable</tr>
<tr> </tr>
<tr>Booked</tr>
<tr> </tr>
<tr>Vacated</tr>
<br>
</tr>
</thead>
<tbody>
<?php
while($row = mysql_fetch_array($getquery)) {
echo '<br>';
echo '<tr>' . $row['total'] .'</tr>';
echo '<tr>' . ' '.' '.' '.' '.' '.' '.' '.'</tr>';
echo '<tr>' . $row['avilable'] .' '.' '.'</tr>';
echo '<tr>' . ' '.' '.' '.' '.' '.' '.' '.'</tr>';
echo '<tr>' . $row['booked'] .' '.' '.' '.' '.' '.'</tr>';
echo '<tr>' . ' '.' '.' '.' '.' '.' '.' '.'</tr>';
echo '<tr>' . $row['vacated'] .'</tr>';
echo '</table>';
}
?>
</tbody>
</table>
</div>
<div id="key">
<p> <img id="imgAvail" src="" alt="Available" /> = Available; <img id="imgMine" src="" alt="Mine" /> = Mine;
<img id="imgTaken" src="" alt="Taken" /> = Taken; <img id="imgvacate" src="" alt="vacate" /> = vacated;</p>
</div>
</div>
<div id="seating">
<h2 align="center">Raised Premium Rooms</h2>
<table id="tblPremium" class="tab" bgcolor="#999999" cellspacing="4" align="center"> </table>
<h2 align="center">Regular Seats Rooms</h2>
<table id="tblCheap" class="tab" bgcolor="#999999" align="center"></table>
<h5></h5>
<div style="clear:both">
</div>
<br />
<div id="theButtons">
<input type="button" value="Confirm Choices" id="confirm" />
<input type="submit" name="submit" value="book">
<input type="reset" id="btnReset" value="Reset" />
</div>
</div>
</div>
</form>
</body>
</html>
One cannot use javascript to connect to a db. You have to use something like php or jsp on this page to connect to a db
just do with ajax, and use PHP to store in db
Connect Javascript to PHP using AJAX
Connect PHP to MySQL
First,
you need to write a file similar to <myServer.php> and put on the server. And make it accessible to client calls. Generally, if you put <index.php> in your apache htdocs folder with php.exe installed and configured to run for .php files, your browser call to localhost will generally bring this parsed with php executable.
Second,
You need to put php code in your client code (the one you pasted above) something similar to this...
<?php
// Create connection
$con=mysqli_connect("localhost","your username to mysql","password for it","your mysql db instance name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
// execute the queries you intend DDL or DML statements
}
?>
Note This process will take at least a day to finally debug and make everything work.
You can use Jquery Ajax, to send and get the response.
$.ajax({
type:'POST',
url: 'confirm.php',
data: "really=yes&sure=yes",
success:function(data){
//Need to split data here
}
});
And then use response (in JSON) to do some rules.

Categories