storing values in db if selected - javascript

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.

Related

Basic multiple file upload not working on mobile

I created a very basic example of a multiple file upload form (reference), it works perfect on desktop but not on mobile, at least the ones I am testing with.
On Mobile (Xiaomi Mi4 [Android version: 6.1] - Google Chrome/Mozilla Firefox): When I click on Choose files I see this screen:
If I choose Google Photos and select multiple files, only the first file will be inserted into the form.
If I select the Gallery (native) app and select multiple files I get the correct number on the form but when I click upload I get the "Aw Snap" screen:
Any idea why this is happening?
Besides Google Photos and the native app I tried 5 different apps, the last one, Piktures actually worked!
Please tell me this is not an app thing... is there a way to get the files correctly?
Code attached:
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
If you wish to test: http://odedta.com/projects/jqueryfileupload/
Thanks!
Try this might help you this is only front end part of file upload with js
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("uploadImage");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div, null);
});
picReader.readAsDataURL(file);
}
});
}
}
<input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
<div id="result" class="uploadPreview">
I am not sure exactly about that mobile browsers are support multiple attribute I read some article it is not support or is not standart, any way If you want to post multiple image; You can see full code below
First Step;
You should use FileReader for load on browser as locally
Multiple file loading with FileReader
document.getElementById("filesToUpload").onchange = function () {
var fileIndex = 0;
for ( var x= 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
//Filename listing
li.setAttribute('id','li_'+x);
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
//FileReader create and set onload event
var reader = new FileReader();
reader.onload = function (data) {
data.target.result;
}
//Read file
reader.readAsDataURL(input.files[x]);
}
}
Second Step
You can set image content to textarea as base64 data for each file
reader.onload = function (data) {
//....
//Split base64 data from DataURL (// "data:image/png;base64,.....)
var b64 = data.target.result.split(',')[1];
var b64Input = document.createElement('textarea');
b64Input.setAttribute('name','file64[]');
b64Input.value = b64;
//...
}
Third Step
Then you can send to your php file whole data and save your content as image
for($i = 0; $i<count($_POST["fileName"]);$i++){
echo $_POST["fileName"][$i]."<br>";
//decode base64 content and put file
file_put_contents($_POST["fileName"][$i], base64_decode($_POST["file64"][$i]));
}
Full Code
HTML & JavaScript
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple />
<form method="post" action="multipleFileUpload.php" enctype="multipart/form-data" id="formMultipleFileUpload">
<ul id="fileList">
</ul>
<input type="submit" value="Upload" id="btnUpload">
</form>
<script type="text/javascript">
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
document.getElementById("filesToUpload").onchange = function () {
var fileIndex = 0;
for ( var x= 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.setAttribute('id','li_'+x);
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
var reader = new FileReader();
reader.onload = function (data) {
var li = document.getElementById('li_'+fileIndex);
var previewImg = document.createElement('img');
previewImg.setAttribute('width','50');
previewImg.setAttribute('height','50');
li.append(previewImg);
previewImg.src = data.target.result;
var b64 = data.target.result.split(',')[1];
var b64Input = document.createElement('textarea');
b64Input.setAttribute('name','file64[]');
b64Input.value = b64;
li.append(b64Input);
var fileName = document.createElement('input');
fileName.setAttribute('name','fileName[]');
fileName.value = input.files[fileIndex].name;
li.append(fileName);
fileIndex++;
}
reader.readAsDataURL(input.files[x]);
}
}
PHP (multipleFileUpload.php)
<?php
for($i = 0; $i<count($_POST["fileName"]);$i++){
echo $_POST["fileName"][$i]."<br>";
file_put_contents($_POST["fileName"][$i], base64_decode($_POST["file64"][$i]));
}
?>
Working screenshot

Cannot set property 'innerHTML' of null in AJAX Call

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;

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.

Simple image tagging page like facebook image tag

<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<title>IMAGE TAGGING</title>
<body>
<center>
<div id="container" style="width:800px">
<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;">Tag Your Friends</h1>
</div>
<div id="content" style="background-color:#EEEEEE; height:450px; width:800px; float:left;">
<div style="color:#0000FF">
<center>
<!--<img border="0" src="clock.jpg" onclick="myFunction(e)" width="800px" height="450">-->
<div id="pointer_div" onclick="myFunction(event)" style = "background-image:url('clock.jpg');width:800px;height:450px;">
</div>
</center>
</div>
</div>
<div id="planetmap">
</div>
<div id='form_panel'>
<div class='row'>
<div class='label' id='label'>Title</div><div class='field' id='field'><input type='text' id='title' name='title' /></div>
</div>
<div class='row'>
<div class='label'></div>
<div class='field'>
<input type='button' value='Add Tag' onclick='addTag()' id='addTag'/>
</div>
</div>
</div>
<div id="footer" style="background-color:#ADFF85; clear:both; text-align:center;" >
<h3>Your Friends Here: </h3><div id="demo" ></div>
</div>
</div>
</center>
<script>
var pos_x;
var pos_y;
function myFunction(e) // called when click on image to create span and textbox
{
$("#title").val("");
pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("pointer_div").offsetLeft;
pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("pointer_div").offsetTop;
x_pos = event.pageX;
y_pos = event.pageY;
x_pos = x_pos - 50;
y_pos = y_pos - 50;
var element = document.createElement('div');
element.id = "someID";
document.body.appendChild(element);
document.getElementById('someID').style.width='100px';
document.getElementById('someID').style.height='100px';
document.getElementById('someID').style.background='transparent';
document.getElementById('someID').style.border='thick solid #0000FF';
document.getElementById('someID').style.position = "absolute";
x = document.getElementById('someID').style.left=x_pos+'px';
y = document.getElementById('someID').style.top=y_pos+'px';
form(x_pos,y_pos);
}
</script>
<script>
jQuery(window).load(function(){
jQuery("#form_panel").hide();
$('#addTag').on('click',function (e) { //creates span dynamically
$('#demo').append('<span class="tags" id="'+$('#title').val()+'" data-y="'+'this.pos_y'+'" data-x="'+'this.pos_x'+'">'+$('#title').val()+', </span>');
console.log("#addTag'");
console.log(pos_x);console.log(this.data-y);
});
jQuery(".tags").live("mouseover",function(){
// $(this).find(".tagged_box").css("background-color","yellow");
console.log("mouseover");console.log(this.id);console.log(pos_y);
console.log(this.data-y); // here i have stuck
//over();
});
})
function over(){
console.log("demo over");
}
function form(x_pos,y_pos){ // to create textbox, call from myFunction()
jQuery("#someID").show();
var ele = document.getElementById('form_panel');
x_pos = x_pos - 25;
y_pos = y_pos - 80;
document.body.appendChild(form_panel);
document.getElementById('form_panel').style.width='180px';
document.getElementById('form_panel').style.height='70px';
document.getElementById('form_panel').style.background='#eee';
document.getElementById('form_panel').style.position = "absolute";
document.getElementById('form_panel').style.left=x_pos+'px';
document.getElementById('form_panel').style.top=y_pos+'px';
//console.log("form is showing in form()");
jQuery("#form_panel").show();
}
function addTag(){
var text = document.getElementById('title').value; //value of text box
//console.log(text);
var demoid = document.getElementById('demo'); //html of #demo
//console.log(demoid);
jQuery("#form_panel").hide();
jQuery("#someID").hide();
//console.log("in addTag");
}
</script>
</body>
</html>
I want to make a simple image tagging page like facebook image tag functionality, I am able to tag names but further I want to add one functionality. Whenever I will hover on names which are tagged, it should show me where it is tagged on image.
This is what I have made for image tagging. You can add tag and delete tag. And save those tagged name in text file so that on refresh tagged name should not disappear.
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<title>IMAGE TAGGING</title>
<body>
<center>
<div id="container" style="width:800px">
<div id="header" style="background-color:#FFA500;">
<h1 style="margin-bottom:0;">Tag Your Friends</h1>
</div>
<div id="content" style="background-color:#EEEEEE; height:450px; width:800px; float:left;">
<div style="color:gray">
<center>
<div id="pointer_div" class="pointer_div" onclick="myFunction(event)" style = "background-image:url('abstract-hd-wallpaper-24.jpg');width:800px;height:450px;">
<?php
$filetxt = 'data/data.txt';
if(file_exists($filetxt))
{
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
$length=sizeof($arr_data);
$i=0;
while ( $i< $length)
{
?>
<div class="store" id="<?php echo $arr_data[$i]['youname'];?>" data-y="<?php echo $arr_data[$i]['x'];?>" data-x="<?php echo $arr_data[$i]['y'];?>" style="top:<?php echo $arr_data[$i]['x'];?>px; left:<?php echo $arr_data[$i]['y'];?>px; position:absolute; width:100px; height:100px; border:3px solid gray" ><?php echo $arr_data[$i]['youname'];?></div>
<?php
$i++;
}
}
else echo 'The file '. $filetxt .' not exists';
?>
</div>
</center>
</div>
</div>
<div id="planetmap">
</div>
<div id='form_panel'>
<div class='row'>
<form id ="saveform">
<div class='label' id='label'>Title</div>
<div class='field' id='field'>
<input type='text' id='title' name='title' />
</div>
<input type='button' value='Add Tag' id='addTag'/><!-- <input type='button' value='Cancel' onclick='cancel()' id='cancel'/> -->
</form>
</div>
</div>
<div class = "overshow" id = "overshow" style="color:red;"></div>
<div id="footer" style="background-color:#ADFF85; clear:both; text-align:center;" >
<h3>Your Friends Here: </h3>
<div id="demo" >
<?php
$filetxt = 'data/data.txt';
if(file_exists($filetxt))
{
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
$length=sizeof($arr_data);
$i=0;
while ( $i< $length)
{
?>
<span class="tags" id="<?php echo $arr_data[$i]['youname'];?>" data-y="<?php echo $arr_data[$i]['x'];?>" data-x="<?php echo $arr_data[$i]['y'];?>" ><?php echo $arr_data[$i]['youname'];?><span class="del" id="<?php echo $arr_data[$i]['youname'];?>" style="color:red">X</span></span>
<?php
$i++;
}
}
else echo 'The file '. $filetxt .' not exists';
?>
</div>
</div>
</div>
</center>
<script>
var x_pos;
var y_pos;
function myFunction(e) // called when click on image to create span and textbox
{
$("#title").val("");
pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("pointer_div").offsetLeft;
pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("pointer_div").offsetTop;
x_pos = event.pageX;
y_pos = event.pageY;
x_pos = x_pos - 50;
y_pos = y_pos - 50;
var element = document.createElement('div');
element.id = "someID";
document.body.appendChild(element);
document.getElementById('someID').style.width='100px';
document.getElementById('someID').style.height='100px';
document.getElementById('someID').style.background='transparent';
document.getElementById('someID').style.border='thick solid #0000FF';
document.getElementById('someID').style.position = "absolute";
x = document.getElementById('someID').style.left=x_pos+'px';
y = document.getElementById('someID').style.top=y_pos+'px';
form(x_pos,y_pos);
}
</script>
<script>
var ids;
var idss;
var clas;
$(window).load(function(){
$("#form_panel").hide();
$(".store").hide();
var del_div = '<span class="del" id="del">DEL &nbsp</span>'
var close_div = '<span class="cls" id="cls"> CLOSE</span>'
$(".overshow").hide();
console.log("form panel");
$('#addTag').on('click',function (e) { //creates span dynamically,called when clicked on addtag button
var append_string = '<span class="tags" id="'+$('#title').val()+'" data-y="'+y_pos+'" data-x="'+x_pos+'">'+$('#title').val()+' <span class="del" id="'+$('#title').val()+'" style="color:red">X</span></span>'
$('#demo').append(append_string);
var store_div = '<div class="store" id="'+$('#title').val()+'" data-y="'+y_pos+'" data-x="'+x_pos+'" style="top:'+y_pos+'px; left:'+x_pos+'px; position:absolute; width:100px; height:100px; border:3px solid gray">'+$('#title').val()+'</div>'
$('#pointer_div').append(store_div);
$('.store').hide('slow');
console.log("store_div");
$("#form_panel").hide('slow');
$("#someID").hide('slow');
var text = $('#title').val();
var data_y = y_pos;
var data_x = x_pos;
console.log("ajax is ahead");
$.ajax({ // passing data to save in textfile
type: "POST", // post or get
url: 'save.php',
data: 'text='+text+'&x='+data_y+'&y='+data_x,
// dataType: "json",
success: function(e)
{
// alert(e);
}
});
});
jQuery(".tags").live('click',function(){ //to show a tagged pose
ids = $(this).attr('id');
idss=ids;
console.log(ids);
var x_cord = $(this).attr('data-x');
var y_cord = $(this).attr('data-y');
$('#overshow').show('fast'); //.delay(1000).hide('slow');
});
jQuery(".tags").live('mouseenter',function(){ //tag name mouseenter
var idss = $(this).attr('id');
ids=idss;
console.log(idss);
var x_cord = $(this).attr('data-x');
var y_cord = $(this).attr('data-y');
$("#overshow").css({top: y_cord, left: x_cord, width:'100px', height:'100px', position:'absolute',border:'3px solid gray'});
$('#overshow').show('slow'); //.delay(1000).hide('slow');
});
jQuery(".tags").live('mouseleave',function(){
$('#overshow').hide();
// $('#overshow').show('slow').delay(1000).hide('slow');
});
jQuery(".cls").live('click',function(){ //to close a overshow of tag
//alert("close");
$('.overshow').hide();
});
jQuery(".del").live('click',function(){ //to delete a tag
var idd=ids;
$('.overshow').hide();
$("#"+idss).remove();
$("#"+idss).remove();
$("#"+ids).remove();
$("#"+ids).remove();
$('.overshow').hide();
var data_y = y_pos;
var data_x = x_pos;
$.ajax({ // passing data to delete from textfile
type: "POST", // post or get
url: 'save.php',
data: 'text1='+ids+'&x1='+data_y+'&y1='+data_x,
// dataType: "json",
success: function(e)
{
// alert(e);
}
});
});
jQuery(".pointer_div").live('mouseenter',function(){ //image mouseenter
console.log("mouseenter on image");
$('.store').show();
});
jQuery(".pointer_div").live('mouseleave',function(){
// console.log("mouseleave");
$('.store').hide();
$('.overshow').hide();
});
})
function over(){
console.log("demo over");
}
function form(x_pos,y_pos){ // to create textbox, call from myFunction()
jQuery("#someID").show('slow');
var ele = document.getElementById('form_panel');
x_pos = x_pos - 25;
y_pos = y_pos - 80;
document.body.appendChild(form_panel);
document.getElementById('form_panel').style.width='180px';
document.getElementById('form_panel').style.height='70px';
document.getElementById('form_panel').style.background='#eee';
document.getElementById('form_panel').style.position = "absolute";
document.getElementById('form_panel').style.left=x_pos+'px';
document.getElementById('form_panel').style.top=y_pos+'px';
//console.log("form is showing in form()");
jQuery("#form_panel").show('slow');
}
function addTag(){
var text = document.getElementById('title').value; //value of text box
console.log(text);
var demoid = document.getElementById('demo'); //html of #demo
//console.log(demoid);
jQuery("#form_panel").hide('slow');
jQuery("#someID").hide('slow');
}
function cancel(){
$("#form_panel").hide('slow');
$("#someID").hide('slow');
}
</script>
</body>
</html>
The further code for saving tagged names in text file and get tagged names from that text file on refresh.
<?php
//refer : http://coursesweb.net/php-mysql/add-form-data-text-file-json-format_t
$filetxt = 'data/data.txt';
// check if all form data are submited, else output error message
if(isset($_POST['text'])) {
// if form fields are empty, outputs message, else, gets their data
if(empty($_POST['text'])) {
echo 'All fields are required';
}
else {
// gets and adds form data into an array
$formdata = array(
'youname'=> $_POST['text'],
'x'=> $_POST['x'],
'y'=> $_POST['y'],
);
// path and name of the file
$filetxt = 'data/data.txt';
$arr_data = array(); // to store all form data
// check if the file exists
if(file_exists($filetxt)) {
// gets json-data from file
$jsondata = file_get_contents($filetxt);
// converts json string into array
$arr_data = json_decode($jsondata, true);
echo $arr_data;
}
// appends the array with new form data
$arr_data[] = $formdata;
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
// saves the json string in "formdata.txt" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data/data.txt', $jsondata)) echo 'Data successfully saved';
else echo 'Unable to save data in "data/data.txt"';
}
}
else {
$filetxt = 'data/data.txt';
$arr_data = array(); // to store all form data
echo $text1 = $_POST['text1'];
// check if the file exists
if(file_exists($filetxt)) {
// gets json-data from file
$jsondata = file_get_contents($filetxt);
// converts json string into array
$arr_data = json_decode($jsondata, true);
foreach ( $arr_data as $k => $abc ) {
// print_r($abc['youname']);
if ( $abc['youname'] != $text1 ) {
$xyz[]=$abc;
}
}
print_r($xyz);
$jsondata = json_encode($xyz, JSON_PRETTY_PRINT);
if(file_put_contents('data/data.txt', $jsondata)) echo 'Data successfully saved';
else echo 'Unable to save data in "data/data.txt"';
}
}
?>

Error: JSON.parse: unexpected non-whitespace character after JSON data

I have a problem with Json pars, I have seen tons of users had this problem I saw them all but I couldn't understand where my error is in my code! Sorry if this is duplicate!
First file index.html:
This is in the head section of the file:
<script type="text/javascript">
function ajax_json_data(){
var databox = document.getElementById("databox");
var field1 = document.getElementById("field1").value;
var results = document.getElementById("results");
var x = new XMLHttpRequest();
x.open( "POST", "test.php", true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.onreadystatechange = function() {
if(x.readyState == 4 && x.status == 200){
databox.innerHTML = "";
var d = JSON.parse(x.responseText);
for(var o in d){
if(d[o].title){
results.innerHTML = "";
databox.innerHTML += '<p>'+d[o].title+'<br />';
databox.innerHTML += ''+d[o].cd+'</p>';
}
}
}
}
x.send("limit=4&field1="+field1);
results.innerHTML = "requesting...";
}
</script>
This is in the body section of the file:
<form id="form" method="post" onSubmit="return false;">
<textarea id="field1" name="field1" placeholder="Input some text here..."></textarea>
<input type="submit" id="submit" name="submit" value="Submit" onClick="ajax_json_data();">
</form>
<div id="results"></div>
<div id="databox"></div>
<script type="text/javascript">ajax_json_data();</script>
The second file test.php:
<?php header("Content-Type: application/json");
if (isset($_POST['field1']) && $_POST['field1'] != "") {
$field1 = $_POST['field1'];
require_once("db_conx.php");
$sqlString = "INSERT INTO test_ajax (title) VALUES ('$field1')";
$query = mysqli_query($db_conx, $sqlString) or die (mysqli_error());
}
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
require_once("db_conx.php");
$i = 0;
$jsonData = '{';
$sqlString = "SELECT * FROM test_ajax ORDER BY creationdate DESC LIMIT $limit";
$query = mysqli_query($db_conx, $sqlString);
while ($row = mysqli_fetch_array($query)) {
$i++;
$id = $row["id"];
$title = $row["title"];
$cd = $row["creationdate"];
$cd = strftime("%B %d, %Y", strtotime($cd));
$jsonData .= '"article'.$i.'":{"id":"'.$id.'","title":"'.$title.'","cd":"'.$cd.'"},';
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
}
?>
And mysqli table has an id, a title and a timestamp, I have tested the data in JSONLint and it's completely valid...Maybe some details that I give it's not necessary but nevermind... So it returns this error: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data ... var d = JSON.parse(x.responseText); Any help would be appreciated! Thanks in advance!
Found the problem..the problem was that my host provider send me some code together with my json response so the response from json was invalid..! Thank you for your feedback!

Categories