Google Map + Ajax + Mysql - php

I want to take variables location, location1, location2 and put them to my base in mysql. I have problem edit google script.
My target is to save 3 variables, when client want to find place.
I was looking for some advices or code in internet. I am a beginner, so sorry for basic code.
Link http://mikozniak.nazwa.pl/dzis/lok.php
Here is my code:
google.maps.event.addDomListener(window, 'load', intilize);
function intilize() {
var autocomplete = new google.maps.places.Autocomplete(document.getElementById("txtautocomplete"));
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
var location = place.formatted_address;
var location1 = place.geometry.location.lat();
var location2 = place.geometry.location.lng();
document.getElementById('lblresult').innerHTML = location
document.getElementById('lblresult1').innerHTML = location1
document.getElementById('lblresult2').innerHTML = location2
});
};
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 location = document.getElementById('lblresult').value;
var location1 = document.getElementById('lblresult1').value;
var location2 = document.getElementById('lblresult2').value;
queryString += "&location = " + location + "&location1 = " + location1 + "&location2 = " + location2;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
</script>
<span>Miejsce:</span><input type="text" id="txtautocomplete" style="width:200px" placeholder="wpisz miejsce"/>
<label id="lblresult"></label>
<label id="lblresult1"></label>
<label id="lblresult2"></label>
<div id = 'ajaxDiv'>Your result will display here</div>
<?php
$dbhost = "mikozniak.nazwa.pl";
$dbuser ="user";
$dbpass = "password";
$dbname = "name";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$loc = $_GET['location'];
$loc1 = $_GET['location1'];
$loc2 = $_GET['location2'];
// Escape User Input to help prevent SQL Injection
$loc = mysql_real_escape_string($loc);
$loc1 = mysql_real_escape_string($loc1);
$loc2 = mysql_real_escape_string($loc2);
//build query
$query = "INSERT INTO `miejsca`(`idm`, `dl`, `szr`) VALUES (NULL,$loc1,$loc2)";
//if(is_numeric($age))
// $query .= " AND age <= $age";
//if(is_numeric($wpm))
// $query .= " AND wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
/*
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)) {
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
*/
?>

You should use an Ajax request in your function intilize(). Link your request to your PHP script, pass your vars (location, location1 and location2) into the data parameter of the Ajax request, and handle them into your PHP script to save them in your database.
Something like that:
$.ajax({
url: '/script.php', // Your script
type: 'POST',
dataType: 'json',
data: { location: location, location1: location1, location2: location2 }
});
Then, in script.php, you will be able to access location, location1 and location2 by using $_POST["location"].

Related

Passing URL query string to PHP via AJAX

I am creating a site for users to look up their invoice numbers using their purchase order number and part number.
I have setup an HTML form which passes a query string to a PHP file which then queries a MySQL server, but I am getting an internal server error. The form is working correctly, it is generating the URL with the query strings attached.
Here is my code to generate the query string:
<html>
<body>
<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 partnumber = document.getElementById('partnumber').value;
var ponumber = document.getElementById('ponumber').value;
var queryString = "?partnumber=" + partnumber ;
queryString += "&ponumber=" + ponumber;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send();
}
//-->
</script>
<form name = 'myForm'>
Part Number: <input type = 'text' id = 'partnumber' /> <br />
PO Number: <input type = 'text' id = 'ponumber' />
<br />
<input type = 'button' onclick = 'ajaxFunction()' value = 'Find Invoice Number'/>
</form>
<div id = 'ajaxDiv'>Your result will display here</div>
</body>
</html>
And this is the ajax-example.php file
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$partnumber = $_GET['partnumber'];
$ponumber = $_GET['ponumber'];
// Escape User Input to help prevent SQL Injection
$partnumber = mysql_real_escape_string($partnumber);
$ponumber = mysql_real_escape_string($ponumber);
//build query
$query = "SELECT * FROM data WHERE partnumber = '$partnumber' and `po#` = '$ponumber'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Part Number</th>";
$display_string .= "<th>PO Number</th>";
$display_string .= "<th>Invoice Number</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)) {
$display_string .= "<tr>";
$display_string .= "<td>$row[partnumber]</td>";
$display_string .= "<td>$row[po#]</td>";
$display_string .= "<td>$row[invoicenumber]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

MySQL Like query not recognising anything but first word in database

Basically I am trying to use a $gen variable to match a user query to a string stored in a database describing a genre of music. My problem is that if the genre is Indie/Pop and the user selects Indie as a search query the event will display. If they select Pop the event does not display.
Here is how i am querying the database.
$sql="SELECT * FROM $tab WHERE genre LIKE '$gen%'AND dateForm = '$datepicker'";
Any help appreciated as ever
php script to get info
<?php
$con = mysqli_connect('localhost','root','','python');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax");
$gen = $_GET['gen'];
$gen = mysql_real_escape_string($gen);
$tab = $_GET['tab'];
$tab = mysql_real_escape_string($tab);
$datepicker = $_GET['datepicker'];
$sql="SELECT * FROM $tab WHERE genre LIKE '%$gen%' AND dateForm = '$datepicker'";
$result = mysqli_query($con,$sql);
echo "<table class='table table-hover'><thead>
<tr>
<th><h3>Artist</th>
<th><h3>Location</th>
<th><h3>Date</th>
<th><h3>Genre</th>
<th><h3>Preview</th>
</tr></thead>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td> <b>Venue: </b>" . $row['venue'] . "<p><b>Location: </b>" . $row['location'] . "</td>";
echo "<td>" . $row['datez'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "<td>" . '<iframe width="100%" height="100" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/' . $row['link'] . '&color=000000&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false"></iframe>' . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
The gen variable is made using AJAX
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 gen = document.getElementById('gen').value;
var datepicker = document.getElementById('datepicker').value;
var tab = document.getElementById('tab').value;
//var datepicker = document.getElementById('datepicker').value;
var queryString = "?gen=" + gen ;
queryString += "&datepicker=" + datepicker +"&tab=" + tab;
ajaxRequest.open("GET", "getuser.php" +
queryString, true);
ajaxRequest.send(null);
}
Okay, some security lessons in here. Bind the parameters $gen (with the wildcards added) and $datepicker in the prepared query. Since you can't bind column or table names, I'd run something like I did below with $tab and the allowed $tables array. This allows you to set a predefined list of tables that the query is allowed to run against and will throw an exception if the table provided is not in the list.
I don't like mysqli or procedural code so I don't use it much but I'm pretty sure everything is in order.
mysqli_select_db($con,"ajax");
// Add wildcards here
$gen = '%'.$_GET['gen'].'%';
$tab = $_GET['tab'];
$datepicker = $_GET['datepicker'];
// Check if $tab is in allowed tables (array $tables)
$tables = ['valid_table1', 'valid_table2', 'valid_table3'];
if (!in_array($tab, $tables)) {
throw new Exception('Hey, get outta here!');
}
$sql="SELECT * FROM $tab WHERE genre LIKE ? AND dateForm = ?";
// Prepare, bind, and execute
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt, 'ss', $gen, $datepicker);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result)) {
...
}
Try adding a % at the beginning of the search value
$sql="SELECT * FROM $tab WHERE genre LIKE '%$gen%'AND dateForm = '$datepicker'";

How to access current data and send data to another php file using ajax?

##ajax function in the php file i need to send id,and two input field values to my updateReq.php file ##
function updateFunction(del,inp1,inp2){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?del=" + del;
queryString += "&inp1=" +inp1;
queryString += "$inp2=" +inp2;
ajaxRequest.open("GET", "updateReq.php" + queryString, true);
ajaxRequest.send(null);
}
in my file i use this part to access ajax function
The ajax function and the bleow code on the same php file
<?php
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<td><input type='text' id='inp1' name='inp1' value='$row[cname]' /></td>";
$display_string .= "<td><input type='number' id='inp2' name='inp2' value='$row[rank]'/></td>";
$display_string .= "<td><a href='#' onclick='deleteFunction($row[id])'>Delete?</a></td>";
$display_string .= "<td><a href='#' onclick='updateFunction( $row[id], $row[cname] ,$row[rank])'>Update?</a></td>";
$display_string .= "</tr>";
}
$display_string .= "</table>";
echo $display_string;
?>
This is my updateReq.php
<?php
// Retrieve data from Query String
include 'config.php';
$id = $_GET['del'];
$inp1 = $_GET['inp1'];
$inp2 = $_GET['inp2'];
// Escape User Input to help prevent SQL Injection
$id = mysql_real_escape_string($id);
$query=mysql_query("update rcategories set cname='$inp1' rank='$inp2' where id='$id'") or die("can not update");
?>
You have a bug in your code..
queryString += "$inp2=" +inp2; change it to queryString += "&inp2=" +inp2;
HTH
Please check your queryString you are using $ instead of &

Why wont this ajax script work on wamp localhost

I was trying out this ajax example on my local machine running windows 7 home premium, apache, php and mysql, but it wont return any results to the browser. After reading a few articles here, I downloaded firebug, and from the firebug console->All what I get is this:
GET http://localhost/dev/ajax/ajax-example.php?age=100&wpm=100&sex=m 200 OK 1.01s
Response
Query: SELECT * FROM ajax_example WHERE sex = 'm' AND age <= 100 AND wpm <= 100
<br /><table><tr><th>Name</th><th>Age</th><th>Sex</th><th>WPM</th>
</tr><tr>td>Frank</td><td>45</td><td>m</td><td>87</td></tr><tr><td>Regis</td>
<td>75</td><td>m</td><td>44</td></tr></table>
This thing above is what should be going to the broswer. The script seems to be working fine then, except the div wont refresh with new content.
Is this a broswer issue or windows/javascript issue. What do I need to do to get this working? Could you please help.
Here's the tutorial page I got all this from.
http://www.tutorialspoint.com/ajax/ajax_database.htm
This page is ajax.html
<html>
<body>
<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.value = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name="myForm">
Max Age: <input type="text" id="age" /> <br />
Max WPM: <input type="text" id="wpm" />
<br />
Sex: <select id="sex">
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type="button" onclick="ajaxFunction()" value="Query MySQL"/>
</form>
<div id="ajaxDiv">Your result will display here</div>
</body>
</html>
This page is ajax-example.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "norman";
$dbname = "test";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
ajaxDisplay.value = ajaxRequest.responseText; here is mistake, change it for example to ajaxDisplay.innerHTML = ajaxRequest.responseText;
and mb use jquery or other framework for such trivial task?
In the callback function
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
I dont think ajaxDisplay.value will work!
instead use
ajaxDisplay.innerHTML = ajaxRequest.responseText;

Inserting and retrieving data in MySQL using PHP through Ajax

I have a very simple form, containing a textbox and a submit button. When the user enters something into the form, then clicks submit, I would like to use PHP and Ajax (with jQuery) to insert the result of the form into a MySQL database. this result should be displayed on the same page in the form of a table which is updated after every insert.
Can anyone please help?
The code I have used that isn’t working:
ajax.html:
<html>
<body>
<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.value = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "&name=" +name+ "&age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" +
queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' id='name' /><br/>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()'
value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
ajax-example.php:
<?php
$dbhost = "localhost";
$dbuser = "demo";
$dbpass = "demo";
$dbname = "test_db";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($test_db) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "INSERT INTO form2 (name,age,sex,wpm) VALUES ('$name','$age','$sex','$wpm')";;
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
$result1=mysql_query("SELECT * FROM form2 WHERE name='$name'");
while($row = mysql_fetch_array($result1))
{
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
$display_string .= "</table>";
echo $display_string;
?>
$("button_id").click(function () {
$.ajax({
url:"where you should post the data",
type: "POST",
data: the string you should post,
success: function (result) {
//display your result in some DOM element
}
});
});
When you receive the data in the php script make query to the database and get your result
hope this would help
There are many tutorials available on internet for ajax with PHP and Jquery. You can go through any of these and get the desired result.
See an example here http://www.tutorialspoint.com/ajax/ajax_database.htm

Categories