I have a PHP script that does the insertion part as follows(I know, no PDO or mysqli, this is just for my personal testing):
<?php
$user = $_POST['user'];
$comments = $_POST['comment'];
$con = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db('localh',$con);
$query = mysql_query("INSERT INTO content (Title, Article)
VALUES('$user', '$comments')");
if(!$query){die(mysql_error());}
mysql_close($con);
?>
If I use this script in a form action it will work fine, the input values will be added to the database.
Here's the form:
<form>
<p>User: <input type="text" id="user" /></p>
<p>Comment:<input type="text" id="comment" /></p>
<input type="button" id="submit" onClick="insertData();" />
</form>
And the AJAX part, located between the head tags:
function insertData(){
var ajaxRequest = new XMLHttpRequest();
var usr = document.getElementById("user").value;
var cmnt = document.getElementById("comment").value;
ajaxRequest.open("POST", "insert.php", true);
ajaxRequest.send(usr, cmnt);
}
The result will be an empty row in the database. I don't know why that is, I'm clueless.
Actually, this is one of the only very specific cases where I actually recommend someone to use jQuery.
AJAX is probably the most ambiguously implemented feature. Each browser has its quirks regarding its implementation. jQuery can be used to iron out those cross-browser incompatibility.
jQuery $.ajax documentation page
You are not actually sending the keys of your variables to your script:
ajaxRequest.send(usr, cmnt);
so your $_POST array will not contain user nor comment.
Although a switch to jQuery is probably a good idea, you can send your variables like:
var vars = encodeURI("user="+usr+"&comment="+cmnt);
ajaxRequest.send(vars);
But you would have to test that as I normally use jQuery for my ajax requests.
Check if you recive in $_POST veriable user and comments data, just add in your php file something like that
print_r($_POST); exit();
if you will havent them at server side check your ajax
if allright check your mysql query:
Related
I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.
I have some problems loading input field from html using php. I am using jQuery Ajax $.post function to send my data from input filed to php file in order to do the query from the database.
I have fixed the code. Code below is working perfectly.
Here is the html from my main page
<input class="detail" maxlength="60" name="detail" placeholder="Type to search">
<button class="searchbtn" name="search">Search</button>
and this is the jQuery Ajax part
$(".searchbtn").click(function(e) {
makeAjaxRequest();
});
function makeAjaxRequest(){
var input = $(".detail").val();
$.post("search.php",{detail:input},function(data,status){
$('#resultTable tbody').html(data);
});
Then last part is the php file (search.php)
if (isset($_POST['detail'])) {
$data = $_POST['detail'];
$query = "SELECT * FROM products WHERE ".%data;
$result = $conn->query($query) or trigger_error($mysqli->error."[$sql]");
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
}
Now it worked perfectly. Thanks for the answer.
You are extracting $_POST['detail'] on your server side page, but while sending on client side, you are sending like this, $.post("search.php",input.
Data should be sent data as PlainObject or string. I mean, every POST data should have some index to get referenced on the other end.
Since you are extracting with index detail, add detail on following like:
$.post("search.php",{detail:input},function(data,status){
See : jQuery : $.post()
currently you're just sending a string with no key/value. You need to send a key/value pair as your data parameter, either as a string or an object (object is safer, as it'l get automatically urlencoded)
$.post("search.php",{detail:input},function(data,status){
You could try this.
function makeAjaxRequest(){
var input = $(".detail").val();
$.post("search.php",
{detail: input},
function(data,status){
$('#resultTable tbody').html(data);
});
}
The title may seem quite vague, sorry about that I don't really know how to phrase my question.
I'm trying to get a PHP variable to be assigned the value of a button class when the button is pressed. Sort of like this:
<input id="button-id" class="button-1" type="button" onclick="<?php $variable=class of button-id; // Assign the variable here ?>"
Obviously the syntax is wrong as I don't know how to do it, or whether it is possible.
The reason I need this is because I am doing a MySQL query which will rely on the $variable like so:
$query = "SELECT * FROM table WHERE name='{$variable}'";
This needs to be like this due to the what the query is being used for.
Thanks for any help.
In short: you can't do it that way.
What you probably want to do is use a hidden field to pass data to a PHP script by submitting a form. For example:
<form method="post" action="form.php">
<input type="hidden" name="variable" value="button-1" />
<input type="submit" class="button" />
</form>
Your form.php file would look something like this:
<?php
$user = 'example';
$pass = 'example';
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use a prepared statement!
$stmt = $dbh->prepare("SELECT * FROM table WHERE name = ?");
// the user input is automatically quoted, so no risk of SQL injection
if ($stmt->execute(array($_POST['variable']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
Of course, rather than printing the results of the query right there, you would probably want to store them in a variable for later use. Note that you could also incorporate the script on the same page as the form.
Hmm, try this: I used Jquery to pass the button class to an Ajax request that goes to the php file below.
EDIT: Be sure you are correctly parsing and filtering your data to prevent injection attacks. This simply shows you you can pass html classes to PHP.
HTML FILE
<html>
<head>
<script type="text/javascript">
// Assign your button an on click event using jquery
$('#button-id').click(function(){
//Store our current elements class value
var buttonclass = $(this).attr("class");
//Create an ajax request that goes to aphp file and will receive your class value
$.ajax({
url: 'ajaxfile.php?buttonclass='+buttonclass,
success:function(data){
alert(data);
}
});
});
</script>
</head>
<body>
<input id="button-id" class="button-1" type="button" />
</body>
</html>
PHP FILE
<?php
$pdo = new PDO("mysql:dbname=newdbnaem;host=1.1.1.1:1111", "owner", "passwordlulz");
$buttonclass = $_GET['buttonclass'];
$query = $pdo->prepare("SELECT * FROM table WHERE name = :name");
$query->execute(array(':name' => $buttonclass));
?>
Success
<?php exit(0);
?>
Hopefully that helps!
I'm creating a registration form.
The user enters the username and password, and presses submit, and the form is submitted using POST.
HTML :
<link href="Styles/RegisterStyles.css" rel="stylesheet" type="text/css" />
<form id="frmRegister" method="post" action="register.php">
<h1>Register</h1>
<table width="100%">
<tr>
<td width="16%"><label class="alignRight"> Username: </label></td>
<td width="84%"><input name="txtUsername" type="text" maxlength="40" /></td>
</tr>
<tr>
<td width="16%"><label class="alignRight"> Password: </label></td>
<td width="84%"><input name="txtPassword" type="text" maxlength="40" /></td>
</tr>
<tr>
<td width="16%"> </td>
<td width="84%"><input name="Submit" class="submitButton" type="submit" /></td>
</tr>
</table>
</form>
</html>
PHP:
$username = $_POST["txtUsername"];
$password = $_POST["txtPassword"];
//Code to connect to database
function doesUsernameExist($username)
{
//return true if username exists or false otherwise
}
Now, in PHP, I run a query to check if the username exists in the database.
If the username already exists, how can I notify the user without navigating to another page and causing the "username" and "password" fields to be reset to blank?
Some registration forms have a really neat Javascript that checks if the username exists each time you press a key on the keyboard. Any ideas on how this could be implemented? It's difficult ( and bad practice ) to connect to a database using JavaScript from what I can gather.
I use jQuery to do something like this.
in the html
<input type="text" name="username" onBlur="checkUsername(this)">
in the javascript something like this
function checkUsername(v){
$.post("phppage.php",{
valToBeChecked:v
},function(d){
if($.trim(d)==true){
// php page returned true
}else{
// php page returned false
}
});
}
do note this is only an example, I think I got the syntax right tho.
This will do an AJAX check on blur of the input without jQuery.
Edit: I want to clarify that I don't suggest this approach, and much prefer the use of jQuery (or other similar JS framework) for AJAX. However, I understand that not everyone has the luxury of specifying the technologies they use, and so here's the answer to your request! :)
<input id="txtUsername" name="txtUsername" />
<script type="text/javascript">
window.onload = function() {
document.getElementById('txtUsername').onblur = function(e) {
// Get the username entered
var el = e.target;
var username = el.value;
// Create an XHR
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// AJAX call to the server
request.open('GET', '/check_username.php?username=' + username, false);
xhr.onload = function(e) {
var json = eval(xhr.responseText);
if (json.exists) {
window.alert('That username exists already.');
}
}
xhr.send();
}
}
</script>
user_exists.php
$username = isset($_GET['username']) ? $_GET['username'] : '';
$username = mysqli_real_escape_string($username);
$sql = "SELECT COUNT(*) > 0 AS user_found
FROM users
WHERE username = '{$username}'";
$result = mysqli_query($sql);
$exists = false;
if ($row = mysqli_fetch_assoc($result)) {
$exists = $row['user_found'] ? true : false;
}
echo json_encode(array('exists' => $exists));
My solution to this would be to utilize AJAX.
On submission of your form, make an AJAX call to a page that will evaluate the data that has been input into the form, and return information regarding whether or not it was validated.
After you get back some information from that AJAX call, determine whether or not to submit the form again, but this time to a page that will absorb the data into the database.
It's one solution; and as an AJAX newbie I'd say there are probably better ones, but it might work for you.
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You don't want to pass a blank value, this is where you would put your username and password to deliver to FILE2.php. In your case, the line would look like this:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 1;
This would deliver a 1 to the success function in FILE1.php, and it would be stored in the variable called "data". Therefore, the alert(data) line in the success function would alert the number one.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file returns a response (whatever you choose to send) and that appears in the Success: section of your AJAX call.
The jQuery/AJAX is JavaScript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document.
I want to make a form submit without refreshing page in jquery.
But I have no idea why the data didn't insert into the database. Are there any problems in the code below?
Before that, I had referred to here, I hope I didn't write it wrong.
HTML
<form id="submit">
<fieldset><legend>Enter Information</legend> <label for="fname">Client First Name:</label>
<input id="vName" class="text" type="text" name="vName" size="20" />
<label for="lname">Client Last Name:</label>
<input id="vLat" class="text" type="text" name="vLat" size="20" />
<input id="vLng" class="text" type="text" name="vLng" size="20" />
<input id="Add" class="text" type="text" name="Add" size="20" />
<button class="button positive"> <img src="../images/icons/tick.png" alt="" /> Add Client </button></fieldset>
</form>
Javascript
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var vName = $('#vName').val();
var vLat = $('#vLat').val();
var vLng = $('#vLng').val();
var Add = $('#Add').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "vName="+ vName +"& vLat="+ vLat +"& vLng="+ vLng +"& Add="+ Add,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
dbtools.inc.php
<?php
function create_connection()
{
$link = mysql_connect("localhost", "root", "52082475");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
mysql_query("SET NAMES utf8");
}
function execute_sql($database, $sql, $link)
{
$db_selected = mysql_select_db($database, $link)
or die("Fail <br><br>" . mysql_error($link));
$result = mysql_query($sql, $link);
return $result;
}
?>
ajax.php
<?php
include ("dbtools.inc.php");
$link = create_connection();
// CLIENT INFORMATION
$vName = htmlspecialchars(trim($_POST['vName']));
$vLat = htmlspecialchars(trim($_POST['vLat']));
$vLng = htmlspecialchars(trim($_POST['vLng']));
$Add = htmlspecialchars(trim($_POST['Add']));
$sql = "INSERT INTO map_db (vName,vLat,vLng,add) VALUES ('$vName','$vLat','$vLng','$Add')";
$result = execute_sql("map",$sql,$link);
mysql_close($link);
header("location:add.html");
exit();
?>
For starters your PHP code is not safe (look up sql injection and prepared statements). Next make your PHP code echo/print something- the result of the query. For example, you may want to use JSON or XML to print the result of the query (good||bad). That way the ajax can use this in the success function to determine if the query was successful or not and can thus display an error or success message appropriately.
Also respond to errors in the ajax request (Reference here). For example:
ajax.({
url:..,
....
error: function() {
...
}
});
By interpreting the response from your PHP you should be able to determine what the cause of the error is (bad mysql connection, query, syntax, url, data, etc).
Goodluck.
i think there is a syntax error in data field of your ajax post method...
if you want to post entire form, then use...
var formData= $('form').serialize();
data: formData
or use below code to send individual parameters...
data: { 'vName' : vName, 'vLat' : vLat, 'vLng' : vLng}
i'm not familiar with php style of coding... but this works well with c# method signatures... change your code in php according to the posted data fields
NOTE: use preventDefault() in your submit method, for not to redirect/refresh your page
If you want to submit form data there is no need to use form tags instead use a button like this
<input type = 'image' src ='blah blah' id = 'submit'>
Also i see here you are using submit event instead use click event.
You should not close the connection in create_connection() I guess. That function exists to open a new one :)
Oh, and it seems that you want to return the $link from the same method too, even if you don't really need all that code (neither an explicit mysql_close() nor using the $link, unless you happen to connect to two or more different databases in the same script).
The server side code seems very weak and insecure. If it's a pet project it's ok, but if can become anything serious, you should watch out for sql injections and PHP vulnerabilities, or use a PHP framework which usually handles this for you