How to insert into MySQL HTML Form data? - php

I checked a lot of articles and I don't understand it how to insert data into a MySQL table. What is wrong? I guess that my Ajax request is already wrong.
I would be happy to get help!!!
I did not write programs since 20 years. My coding is for sure not good, but I need to get it running.
Any help would be very appreciated!
The code that follows does not INSERT INTO and does not UPDATE. Why?
Here is the source:
articles.php
<!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" dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<title>SoB - Administration</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/scroll.js"></script>
<script type="text/javascript" src="js/producttemplate.js"></script>
<script type="text/javascript" src="js/jquery.js" ></script>
<style type="text/css">.buttonarea: (\a)</style>
<script type="text/javascript">
<!--
var js_string;
document.getElementById("recordWrite").disabled = true;
var lastPreviousNext = "";
var date = new Date();
var mysqlDateTime;
var yyyy = date.getFullYear();
var mm = date.getMonth() + 1;
var dd = date.getDate();
var hh = date.getHours();
var min = date.getMinutes();
var ss = date.getSeconds();
mysqlDateTime = yyyy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + ss;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// No submit by onclick
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
elem = document.getElementById('buttonID');
function stop(e) {
e.preventDefault(); // browser - don't act!
e.stopPropagation(); // bubbling - stop
return false; // added for completeness
}
elem.addEventListener('click', stop, false);
// this handler will work
elem.addEventListener('click', function() { alert('I still work') }, false);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function jsRecordInsertWrite()
{
document.getElementById('formheadline').innerHTML = 'Article Database - I save the new item';
document.getElementById("recordWrite").disabled = true;
js_articles[0]=""; // set auto increment id to NULL
// ... the AJAX request is successful
var updatePage = function (response) {
alert("insert record successful");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("insert record failed");
};
// Create an object to describe the AJAX request
var ajaxOptions = {
url: 'writearticle.php',
dataType: 'json',
success: updatePage,
error: printError
};
// Initiate the request!
$.ajax(ajaxOptions);
}
// -->
</SCRIPT>
</head>
<body class="page page-id-11505 page-template-default" onload="jsRecordCurrent();">
<div id="page-wrap">
<?php
include('includes/header.html');
?>
<div id="container-main">
<div id="main-content">
<div class="post" id="post-11505">
<title>SoB - Administration</title>
<div class="entry">
<form id="form_articles" method="post" action="<?= $_SERVER['PHP_SELF'] ?>" name="form_articles">
<table border="0" cellpadding="0" cellspacing="5">
<tr>
<td align="right">
<span style="padding-right:20px">Item</span>
</td>
<td>
<input id="Item" name="Item" type="text" maxlength="100" size="25"/>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Item Category</span>
</td>
<td>
<input name="ItemCategory" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr id="buttonarea">
<td align="right" colspan="2">
<hr noshade="noshade" />
<input id="recordInsertWrite" type="button" name="recordInsertWrite" value=" Save New Record " onclick="jsRecordInsertWrite()" />
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
<div id="aside">
</div>
</div> <!-- End of main container -->
</div><!-- END Page Wrap -->
</body>
</html>
writearticle.php
<?php
$link = mysql_connect('test.test.com:3306', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
// Escape user inputs for security
$ID = mysql_real_escape_string($_POST['ID']);
$Item = mysql_real_escape_string($_POST['Item']);
$ItemCategory = mysql_real_escape_string($_POST['ItemCategory']);
if('$ID' == '')
{
$sql = "INSERT into articles values(NULL,'$Item','$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("error");</script>';
}
else
{
echo '<script type="text/javascript">alert("ok");</script>';
}
}
else
{
$sql = "UPDATE articles SET Item='$Item',ItemCategory='$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("update error");</script>';
}
else
{
echo '<script type="text/javascript">alert("update ok");</script>';
}
}
?>

Related

PHP-How to add an "Enter passcode" screen before user accesses website

So I have a chatting site in PHP, but the problem is that anyone can access any "chatroom". Is there a way to add an "Enter passcode" text box to the site before they are able to access the real thing? And if possible I would prefer not using those JavaScript pop-ups. And for the people who really want to help, I don't need any CSS.
My code:
index.php:
<?php
session_start();
if(isset($_GET['logout'])){
//Simple exit message
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: ../../index.php"); //Redirect the user
}
if(isset($_POST['enter'])){
if($_POST['name'] != ""){
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}
else{
echo '<span class="error">Please type in a name</span>';
}
}
function loginForm(){
echo
'<div id="loginform">
<p>Please enter your name to continue!</p>
<form action="index.php" method="post">
<label for="name">Name —</label>
<input type="text" name="name" id="name" />
<input type="submit" name="enter" id="enter" value="Enter" />
</form>
</div>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Chat</title>
<meta name="description" content=" Chat Application" />
<link rel="stylesheet" href="../../css/chat.css" />
</head>
<body>
<?php
if(!isset($_SESSION['name'])){
loginForm();
}
else {
?>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
</div>
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$contents = file_get_contents("log.html");
echo $contents;
}
?>
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function () {
$("#submitmsg").click(function () {
var clientmsg = $("#usermsg").val();
$.post("post.php", { text: clientmsg });
$("#usermsg").val("");
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function (html) {
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
}
});
}
setInterval (loadLog, 2500);
$("#exit").click(function () {
var exit = confirm("Are you sure you want to end the session?");
if (exit == true) {
window.location = "index.php?logout=true";
}
});
});
</script>
</body>
</html>
<?php
}
?>
post.php:
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
?>

Ajax search results with on click result to download file

MY INDEX PAGE
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Some name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h2 align="center">Search by name</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Enter model / search here" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
AND MY fetch.php PAGE
which is used to get data from the database tables and output results.
I also added if the result is > 50 it will ask to enter few more characters because if I don't add if result > 50 then my page took 20sec to display all data because my database table has 25000 entries.
<?php
$connect = mysqli_connect("localhost", "root", "PASSWORD", "DATABASE");
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM files
WHERE Name LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM files ORDER BY ID
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) < 500)
{
$output1 .= '
<div class="table-responsive">
<table class="table table bordered">
<div>
<th>Name</th>
<th>URL</th>
<th>Extension</th>
<th>Download</th>
</div>
';
while($row = mysqli_fetch_array($result))
{
$output2 .= '
<tr>
<td>'.$row["Name"].'</td>
<td>'.$row["URL"].'</td>
<td>'.$row["Extension"].'</td>
</tr>
';
}
if(mysqli_num_rows($result) > 0)
{
echo "$output1";
echo "$output2";
}
else
{
echo 'no results found';
}
}
else
{
echo 'Please enter few more charecters';
}
?>
I want href link for each of my results and on the click, it should download a file from ./"URL" column from a database table.
My database looks like this:
AND MY CURRENT PAGE IS http://mss1996.ddns.net:8008/files
I tried adding < a href=".$row["URL"]."> in outpur'array' but it destroys my page.
You should be able to easily add the URL field to form a valid URL if the contents of that field is indeed a valid URL. What I see missing form your code is http or https if it's an external link. If it's a relative link within the page then you're ok. Then add the </a> to close the link. So you'd form your table column like this:
echo '<td>' . $row["URL"] . '</td>';

How to convert this php normal code to codeigniter mvc

I need help to convert this code to codeigniter MVC
i have 2 file php
index.php for viewer and cari_barang.php for model
i have problem with file controller, I dont know how to get value post with ajax.
this my PHP code index.php
<html>
<head>
<script type="text/javascript" src="jquery-1.11.2.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<script type="text/javascript">
$(document).ready(function() {
$("#barang").keyup(function() {
var kode = $('#barang').val();
$.ajax({
type : "POST",
data : "kode="+kode,
url : "cari_barang.php",
dataType: "json",
success: function(data){
$("#namabarang").val(data.namabarang);
$("#hargabeli").val(data.hargabeli);
}
});
});
});
</script>
</head>
<body>
<div class="demo" style="width: 450px;">
<div>
<p>Kode Barang : <input type="text" id="barang" value="0001"></p>
<p>Nama Barang : <input type="text" id="namabarang" size="50" disabled></p>
<p>Harga Beli : <input type="text" id="hargabeli" size="15" align="right" disabled></p>
</div>
</div>
</body>
</html>
this code for cari_barang.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("barang");
$kode = $_POST['kode'];
$sql = mysql_query("select * from tbbarang where kodebarang='$kode'");
$row = mysql_num_rows($sql);
if($row>0){
$r = mysql_fetch_array($sql);
$data['namabarang'] = $r['namabarang'];
$data['hargabeli'] = $r['hargabeli'];
echo json_encode($data);
}else{
$data['namabarang'] = '';
$data['hargabeli'] = '';
echo json_encode($data);
}
?>
thanks before
have a look on codeigniter website http://www.codeigniter.com/userguide3/ hope you will find your solution.
if you convert your above code to codeigniter then its only a view file of codeigniter.
thanks all for answer,my problem solved with this code
Model :
public function get($kode)
{
$this->db->where('kodebarang',$kode);
$query = $this->db->get('tbbarang');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data['namabarang'] = $row->namabarang;
$data['hargabeli'] = $row->hargabeli;
echo json_encode($data);
}
} else {
$data['namabarang'] = '';
$data['hargabeli'] = '';
echo json_encode($data);
}
}
Controller :
public function view()
{
$this->load->model('m_barang');
$kode = $this->input->post('kode');
//#$kode = $_POST['kode'];
$data = $this->m_barang->get($kode);
}
View :
<html>
<head>
<script type='text/javascript' src='<?php echo base_url("jquery-1.11.2.js");?>'></script>
<script type='text/javascript' src='<?php echo base_url("jquery.autocomplete.js");?>'></script>
<!-- <link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<link rel="stylesheet" href="main.css" type="text/css" /> -->
<script type="text/javascript">
$(document).ready(function() {
$("#barang").keyup(function() {
var kode = $('#barang').val();
$.ajax({
type : "POST",
data : "kode="+kode,
url : "<?=base_url('barang/view')?>",
dataType: "json",
success: function(data){
$("#namabarang").val(data.namabarang); //$r['namabarang']
$("#hargabeli").val(data.hargabeli); //$r['hargabeli']
}
});
});
});
</script>
</head>
<body>
<div class="demo" style="width: 450px;">
<div>
<p>Kode Barang : <input type="text" id="barang" value=""></p>
<p>Nama Barang : <input type="text" id="namabarang" size="50" disabled></p>
<p>Harga Beli : <input type="text" id="hargabeli" size="15" align="right" disabled></p>
</div>
</div>
<p class="footer" ><?php echo base_url();?></p>
<p class="footer" ><?php echo site_url();?></p>
<p class="footer" ><?php echo base_url('barang/view');?></p>
</body>
</html>

Javascript Error? Objects Null

I made an upload page and php script for it that is an AJAX script but i'm getting some errors in Firebug and my upload percentage isn't being returned, so far i am only able to do one upload in firefox and the script won't even work in chrome.
here is my code:
<?php
session_start();
include ('../Connect/Connect.php');
$User = $_SESSION['User'];
if(isset($User))
{
}
else
{
header("location:../");
}
$Connect -> close();
?>
<!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>
<link rel="stylesheet" href="../StyleSheets/StyleSheet.css" />
<link rel="stylesheet" href="../JQueryUI/css/black-tie/jquery-ui-1.10.1.custom.min.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TeraShare</title>
<script type="text/javascript" src="../JQuery/JQuery.js"></script>
<script type="text/javascript" src="../JQueryUI/js/jquery-ui-1.10.1.custom.min.js"></script>
<script type="text/javascript" src="../Scripts/JavaScript.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var UploadB = $('#Submit');
UploadB.click(function(event)
{
event.preventDefault();
event.stopPropagation();
var Data = new FormData();
var Files = document.getElementById('Files');
for(var I = 0; I < Files.files.length; ++I)
{
var FilesName = Files.files[I].name;
Data.append('File[]', Files.files[I]);
}
var Request = XMLHttpRequest();
Request.upload.addEventListener('progress', function(event)
{
if(event.lengthComputable)
{
var Percent = event.loaded / event.total;
Progress = document.getElementById('#Progress');
while(Progress.hasChildNodes())
{
Progress.removeChild(Progress.firstChild);
}
Progress.appendChild(document.createTextNode(Math.round(Percent * 100) + '%'));
}
});
Request.upload.addEventListener('load', function(event)
{
Progress.style.display = 'none';
});
Request.upload.addEventListener('error', function(event)
{
alert('Upload Failed.');
});
Request.open('POST', 'Upload.php');
Request.setRequestHeader('Cache-Control', 'no-cache');
Progress.style.display = 'block';
Request.send(Data);
});
});
</script>
</head>
<body>
<div id="Wrapper">
<div id="Menu">
<div id="Logo"><img src="../Pictures/Logo.png" /></div>
<div id="Buttons">
<div class="Button" title="LogOut">LogOut</div>
<div class="Button" id="Upload" title="Upload">Upload</div>
<div class="Button" id="CFolder" title="Upload">Create Folder</div>
<div class="Button" id="Store" title="Store">Store</div>
<div class="Button" title="Menu"><?php echo $User; ?> <span class="Triangle"></span></div>
</div>
</div>
<div id="Content">
<div id="Fix">
<div id="UForm">
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="Files" name="File[]" multiple="multiple" />
<input type="submit" name="Submit" class="AB" id="Submit" value="Upload!" />
<div id="Progress"></div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
php script:
<?php
session_start();
include('../Connect/Connect.php');
$User = $_SESSION['User'];
$Token = $_POST['Token'];
$Files = $_FILES['File'];
if(isset($User))
{
if(!empty($Files))
{
for($X = 0; $X < count($Files['name']); $X++)
{
$Name = $Files['name'][$X];
$TMP = $Files['tmp_name'][$X];
move_uploaded_file($TMP, '../Users/HARAJLI98/' . $Name);
}
}
}
else
{
header("location:../");
}
$Connect->close();
?>
Document.getElementById needs the physical string of the ID, you don't need to specify that it's an ID.
You are mixing up javascript and jQuery. In jQuery, $.("#Progress") would work because the $ function doesn't know whether you are looking or an ID or a class.
This:
Progress = document.getElementById('#Progress');
should be this:
Progress = document.getElementById('Progress');
or this:
Progress = $("#Progress");

I want a map with values inserted from the user and that values on a database

Below there is my code of "home.php". I want insert some values associated to an address, put them (find and put also the latitude and longitude of the address inserted from the user) in a database and in the map with a marker.
The problem is that when codeaddress() execute, it stops exactly before geocoder.geocode({'address': address},function(results, status) {..} and I'm not able to have the latitude and logitude to put in my database, and in the map there isn't the marker.
If I remove the line <form action="home.php" method="post" width="300px" height="300px"> (and of course the part of insertinDb() because now I haven't any $_POST value) codeaddress() works, and I have the marker and latitude and longitude values.
If I remove the call to codeaddress(), insertinDB() works (of course without insert lat and lng values).
Where am I wrong?Please ask me if something is not clear in the question.
<!DOCTYPE html>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<HTML>
<HEAD>
<script type="text/javascript" src="jquery.js"></script>
<META NAME="GENERATOR" Content="AlterVista - Editor HTML">
<title>LowPricePetrol</title>
<link rel="stylesheet" type="text/css" href="homeformat.css"/>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/PRIVATEKEY=true">
</script>
<script type="text/javascript">
var geocoder;
var map;
var lat_;
var lng_;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(41.92, 12.93);
var mapOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function codeAddress() {
var contentString = '<div id="content">'+
'<h2 id="firstHeading" class="firstHeading">' + document.getElementById("nome").value + '</h2>'+
'<div id="bodyContent"><u>Indirizzo</u>: ' + document.getElementById("indirizzo").value + ' ' + document.getElementById("civico").value +'<br><u>Citta</u>: '+ document.getElementById("citta").value
+ '<br><u>Paese</u>: ' + document.getElementById("paese").value + '<br><u>Prezzo Benzina</u>: ' + document.getElementById("prezzoB").value + ' (euro/litro)</div>' +
'<u>Prezzo Diesel</u>: ' + document.getElementById("prezzoD").value +
' (euro/litro)</div>'+
'</div>';
var image = '/img/'+ document.getElementById("nome").value +'.png';
var infowindow = new google.maps.InfoWindow({content: contentString});
var ind2_map = document.getElementById("indirizzo").value;
var civ_map = document.getElementById("civico").value;
var cit2_map = document.getElementById("citta").value;
var pae2_map = document.getElementById("paese").value;
var address = ind2_map + " " + civ_map + ", " + cit2_map + ", "+ pae2_map ;
alert(address);
geocoder.geocode({'address': address},function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
alert(results[0].geometry.location);
lat_ =results[0].geometry.location.lat();
alert(lat_);
lng_ =results[0].geometry.location.lng();
alert(lng_);
document.getElementById('lat').value = lat_;
document.getElementById('lng').value = lng_;
var marker = new google.maps.Marker({
map: map,
icon:image,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', function() {infowindow.open(map,marker);});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
<?php
function insertInDb() {
$database = mysql_connect( CONNECTION DB);
if (!$database) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("NAME DB", $database);
$sql="INSERT INTO Dati(NomeLuogo, Indirizzo, Citta, Paese, PrezzoB, PrezzoD, Lat, Lng)
VALUES
('$_POST[nome]','$_POST[indirizzo]','$_POST[citta]','$_POST[paese]','$_POST[prezzoB]', '$_POST[prezzoD]', '$_POST[lat]', '$_POST[lng]')";
if (!mysql_query($sql,$database)) {
die('Error: ' . mysql_error());
}
mysql_close($database);
}
?>
<script type="text/javascript">
function check_form(){
var check_n = document.getElementById("nome").value;
var check_i = document.getElementById("indirizzo").value;
var check_civ = document.getElementById("civico").value;
var check_cit = document.getElementById("citta").value;
var check_pa = document.getElementById("paese").value;
var check_prb = document.getElementById("prezzoB").value;
var check_prd = document.getElementById("prezzoD").value;
if(check_n == "" || check_i == "" || check_cit == "" || check_pa == "" || (check_prb == "" && check_prd == "") )
alert("Tutti i campi con asterisco sono obbligatori (almeno un prezzo va inserito)");
else{
codeAddress();
}
}
</script>
</HEAD>
<BODY onload="initialize();">
<div class="titlebox" style="center">
<img src="/img/Logo.png" alt="LowPricePetrol_Logo" width="700" height="150" align=%u201Dcenter%u201D />
</div>
<?php
if(isset($_POST["nome"]))
insertInDb();
?>
<div class="insertbox" style="center">
<br/>
<form action="home.php" method="post" width="300px" height="300px">
AGGIUNGI LA TUA SEGNALAZIONE
<br/>
<label for="nome">Seleziona il gestore:</label><br/>
<select id="nome" name="nome">
<option value="" selected="selected">-- seleziona --</option>
<option value="Eni" id="Eni">Eni</option>
<option value="Esso" id="Esso">Esso</option>
<option value="Ip" id="Ip">Ip</option>
<option value="Q8" id="Q8">Q8</option>
<option value="Tamoil" id="Tamoil">Tamoil</option>
<option value="Total" id="Total">Total</option>
</select><br/>
Indirizzo: <br/>
<input type="text" name="indirizzo" id="indirizzo"/> <br/>
Civico: <br/>
<input type="text" size="4" name="civico" id="civico"/> <br/>
Città: <br/>
<input type="text" name="citta" id="citta"/> <br/>
Paese: <br/>
<input type="text" name="paese" id="paese"/> <br/>
Prezzo benzina (euro/litro): <br/>
<input type="text" name="prezzoB" size="5" id="prezzoB"/> <br/>
Prezzo diesel (euro/litro): <br/>
<input type="text" name="prezzoD" size="5" id="prezzoD"/> <br/>
<input type="text" id="lat" name="lat"></input>
<input type="text" id="lng" name="lng"></input>
<br/>
<input type="submit" name="invia" onclick="check_form()"/>
</form>
</div>
<div class="mapbox" id="map_canvas" style="width:700px; height:350px" ></div>
</BODY>
</HTML>
Geocoding is async function. You getting redirected to home page before it gets result. You should submit form after data is received.
To achieve this goal you can change
<input type="submit" name="invia" onclick="check_form()"/>`
to
<input type="button" name="invia" onclick="check_form()"/>
and
<form action="home.php" method="post" width="300px" height="300px">
to
<form action="home.php" method="post" width="300px" height="300px" name='sform'>
and add document.sform.submit to the end of your if (status == google.maps.GeocoderStatus.OK) { part of code.

Categories