My HTML script gathers the latitude & longitude and sends them to another PHP script via ajax, which inserts those values into mysql, problem is that AJAX inserts NULL values into the table. It's inserting values of "0.000000" for both Latitude & Longitude, lat & long are type float(10,6) in the DB as stated by the internet for best practice with gps coords. I'm obvious new developer please help -- HTML Script
<!DOCTYPE html>
<html>
<head>
<title>AJAX DATABASE</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8">
/*/ Wait for Cordova to load
/*/
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// Cordova is ready
//
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = {enableHighAccuracy:true, timeout: 3000, maximumAge:0};
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var latitude = document.getElementById("lat");
latitude.innerHTML = position.coords.latitude;
var longitude = document.getElementById("longitude");
latitude.innerHTML = position.coords.latitude;
insertDB(position.coords.latitude,position.coords.latitude);
}
// onError Callback receives a [PositionError](PositionError/positionError.html) object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Options: throw an error if no update is received every 30 seconds.
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });
// Sends latitude & longitude value to php script and alerts on success
function insertDB(latitude, longitude){
var xttp = new XMLHttpRequest();
xttp.onreadystatechange = function(){
if(this.readyState == 4){
document.getElementById('longitude').innerHTML =
this.responseText;
alert("state changed by ajax")
}
}
xttp.open("GET", "ConnectTest.php?
latitude="+latitude+"&longitude="+longitude, true);
xttp.send();
}
</script>
</head>
<body>
<p id="lat"></p><br>
<p id="longitude"></p>
</body>
</html>
and the PHP --
<?php
//POST VARIABLES
$one = $_GET['latitude'];
$two = $_GET['longitude'];
//ESTABLISH CONNECTION
$servername = "localhost:3306";
$user = "client";
$pass = "sonic_client";
$db_name = "sonicstrains";
$server = mysqli_connect($servername, $user, $pass, $db_name);
$sql = "SELECT * FROM 'users' WHERE 'latitude' = ".$two;
$result = mysqli_query($server, $sql);
if(!isset($_GET['latitude'])){
echo "Nothing is set";
}
if(!$server){
die("Connetion error".mysqli_connect_error());
}else{
if (!$result){
$insert = "INSERT INTO users (latitude, longitude) VALUES ('$one', '$two')";
mysqli_query($server, $insert);
echo "Coordinates Inserted";
}
}
?>
Replace the xttp open and send functions with below:
xttp.open("POST", "ConnectTest.php, true);
xttp.send(latitude="+latitude+"&longitude="+longitude);
Related
I am new to jQuery and PHP. This might be a trivial question or not.
Normally jQuery handles form input, post it to PHP, and then let PHP passes it to a database.
In my case, I have the current user's geographic location and I compare the user's geographic location against the destination's geographic location in JavaScript. If those two locations are close which means the user is arrived at the destination, record in the database by inserting the destination's Identifier (let's just say Id =1 to keep it simple) for the current user under the Place_Id filed in database. The table in the database only has two columns (userId and placeId).
I wonder how to achieve by jQuery and PHP.
Here is the JavaScript code for geographic locations comparison.
I need help on the function postIt() to initiate PHP using jQuery and the associate PHP.
<script type="text/javascript" ,
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
var lat;
var long;
window.onload=function(){
getLocation();
}
function getLocation() {
if (navigator.geolocation) {
watchId = navigator.geolocation.watchPosition(showPosition, locationError,
{maximumAge:0, timeout:10000, enableHighAccuracy:true});
}
else {
alert("Browser doesn't support Geolocation. Visit http://caniuse.com to
discover browser support for the Geolocation API.");
}
}
function locationError(error) {} // error function here
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
lat = position.coords.latitude;
long = position.coords.longitude;
comparePosition();
}
function comparePosition()
{
var userCurrentLat = lat;
var userCurrentLong = long;
var Dest1_Lat = 38.00; //this is just for demo
var Dest1_Long = -72.00; //this is just for demo
if (userCurrentLat == Dest1_Lat
&& userCurrentLong == Dest1_Long)//just a simplified way of comparison
{
postIt();
}}
function postIt()
{ $.post ('insertDest1.php', {current_user_id, //pseudo jQuery code here
destinationId(1)}, callback function() ) //where I need help
}
</script>
PHP (insertDest1.php)
<?php
include ('mysqli_connect.php');
$query = "INSERT INTO user (userId,placeId) VALUES
('current_user_id' , '1')";
$result = #mysqli_query ($dbc, $query); // Run the query.
if ($result) { // If it ran OK.
// Print a message.
echo '<h1 id="mainhead">Success!</h1>';
}
else { // If it did not run OK.
echo '<h1 id="mainhead">Error</h1>';
}
?>
Use $.ajax for more configuration options:
function postIt()
{
$.ajax({
url: 'insertDest1.php',
type: 'POST',
data:{
userId: 'current_user_id', // replace with actual user id
placeId: 'the_place_id' // replace with actual place id
},
success: function(serverResponse) {
// handle output from server here ('Success!' or 'Error' from PHP script)
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// handle any network/server errors here
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}
});
}
Setup PHP file to handle POST data from AJAX
<?php
include ('mysqli_connect.php');
# Always sanitize input from $_POST variable to prevent SQL injection
$userId = $dbc->escape_string($_POST['userId']); // current_user_id
$placeId = $dbc->escape_string($_POST['placeId']); // the_place_id
$query = "INSERT INTO user (userId, placeId) VALUES ('".$userId."' , '".$placeId."')";
$result = #mysqli_query ($dbc, $query); // Run the query.
if ($result) { // If it ran OK.
// Print a message.
echo '<h1 id="mainhead">Success!</h1>';
}
else { // If it did not run OK.
// Print error.
echo '<h1 id="mainhead">Error</h1>';
}
?>
Hi I try to get the geolocation of the user using cordova. The longitude and latitude should be get in php and cookies should be created with these values. But when I start the application on my device a blank white screen become show. How can I get the javascript variables with php right?
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
//
function onSuccess(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
window.location.href = "http://".$_SERVER['HTTP_HOST']."/loc/www/login.php?latitude=" + latitude;
window.location.href = "http://".$_SERVER['HTTP_HOST']."/loc/www/login.php?longitude=" + longitude;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
<?php
$latitude = $_GET["latitude"];
$longitude = $_GET["longitude"];
$t = time() + 60 * 60 * 24 * 1000;
setcookie("latitude", $latitude, $t);
setcookie("longitude", $longitude, $t);
?>
You have PHP variable combined with javascript, please fix to this:
window.location.href = "http://<?php echo $_SERVER['HTTP_HOST'] ?>/loc/www/login.php?latitude=" + latitude;
You change the location previously and then you try to change again, this will not work:
window.location.href = "http://<?php echo $_SERVER['HTTP_HOST'] ?>/loc/www/login.php?longitude=" + longitude;
Why you don't try to create a API to be consumed by your cordova App, send the location to the webservice when cordova is ready?, you could send both values, latitude and longitude to the server and locally keep those values.
I am working on a php/mysql application, I am trying to collect javascript errors to the database using window.onerror, where inside that function I make an ajax request to a php script that will log the errors into the database. However, when I tested it there are supposed to be 13 errors logged, but only one get inserted into the database. All the 13 ajax requests return 200 OK, is this happening because ajax is just simply too fast for the mysql query to process anything. I tried using set timeout on the send request but it doesnt seem to work.
Here is my code:
window.onerror = function(msg, url, line)
{
function createXHR()
{
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
return null;
}
function sendRequest(url, payload)
{
var xhr = createXHR();
if (xhr)
{
xhr.open("POST",url,true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
};
xhr.send(payload);
}
}
function encodeValue(val)
{
var encodedVal;
if (!encodeURIComponent)
{
encodedVal = escape(val);
/* fix the omissions */
encodedVal = encodedVal.replace(/#/g, '%40');
encodedVal = encodedVal.replace(/\//g, '%2F');
encodedVal = encodedVal.replace(/\+/g, '%2B');
}
else
{
encodedVal = encodeURIComponent(val);
/* fix the omissions */
encodedVal = encodedVal.replace(/~/g, '%7E');
encodedVal = encodedVal.replace(/!/g, '%21');
encodedVal = encodedVal.replace(/\(/g, '%28');
encodedVal = encodedVal.replace(/\)/g, '%29');
encodedVal = encodedVal.replace(/'/g, '%27');
}
/* clean up the spaces and return */
return encodedVal.replace(/\%20/g,'+');
}
if (window.XMLHttpRequest) {
var master = "llesmana#ucsd.edu";
var payload = "msg=" + encodeValue(msg) + '&url=' + encodeValue(url) + "&line=" + encodeValue(line) + "&master=" + encodeValue(master);
var url_req = "http://104.131.199.129:83/php/log_error.php";
sendRequest(url_req, payload);
return true;
}
return false;
}
PHP:
<?php
/**
* Created by PhpStorm.
* User: xxvii27
* Date: 9/2/14
* Time: 12:30 PM
*/
/* Helper functions */
function gpc($name)
{
if (isset($_GET[$name]))
return $_GET[$name];
else if (isset($_POST[$name]))
return $_POST[$name];
else if (isset($_COOKIE[$name]))
return $_COOKIE[$name];
else
return "";
}
//Database Connection
function connectDB (){
define('DB_HOST', 'localhost');
define('DB_NAME', 'userinfo');
define('DB_USER','root');
define('DB_PASSWORD','ohanajumba');
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD, DB_NAME) or die("Failed to connect to MySQL: " . mysql_error() );
return $con;
}
function logError($occured, $name, $line, $master, $url, $db){
$command="INSERT INTO errors (id, occured, name, url, line, master) VALUES (NULL, '$occured', '$name', '$url','$line', '$master')";
mysqli_query($db, $command) or die(mysql_error());
}
$db = connectDB();
$message = htmlentities(substr(urldecode(gpc("msg")),0,1024));
$url = htmlentities(substr(urldecode(gpc("url")),0,1024));
$line = htmlentities(substr(urldecode(gpc("line")),0,1024));
$master = htmlentities(substr(urldecode(gpc("master")),0,1024));
$date = date('Y-m-d G:i:s', time());
logError($date, $message, $line, $master, $url, $db);
mysqli_close($db);
Also, I have checked all the sent data through the request and all of them have been received properly by the script, any help would be appreciated.
I solved it , apparently I forgot to use mysqli_real_escape_string().
When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped. Is there a way that I should be passing a reference?
the console output is as follows
[12:29:06.839] GET getterms.php?query=DFA [HTTP/1.1 200 OK 99ms]
[12:29:06.888] SyntaxError: JSON.parse: unexpected character # search.php:21
[12:33:24.316] console.log(req.responsetext)
[12:33:24.318] ReferenceError: req is not defined
Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse(req.responseText);
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Scope problem! Remove var in front of req to make it global and it should work
So I am trying to make a simple autocomplete form but keep getting a error when I try to test the program.
When I try to test the program my console spits out [11:25:26.267] SyntaxError: JSON.parse: unexpected character # /search.php:22 which is this line. I am pretty sure my syntax is fine but I could be mistaken. Any and all help would be most gratefully appreciated. Thank you to anyone who takes the time to read and/or answer even if you cannot help!
for (var i = 0; i < response.length; i++)
My Full code is as follows.
Edit: Now with page that echos the json. When I do console.log(req.responsetext) i get [11:38:04.967] ReferenceError: req is not defined. But i define req as a new xml request on window load so I am kind of stumped.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Auto Complete</title>
</head>
<body>
<script>
window.onload = function () {
var req = new XMLHttpRequest(); //the HTTP request which will invoke the query
var input = document.getElementById('search'); //where to grab the search from
var output = document.getElementById('results'); //where to display the sugestions
input.oninput = getSuggestions;
function getSuggestions() {
req.onreadystatechange = function () {
output.innerHTML = ""; //CLEAR the previous results!! only once the server can process new ones though
if (this.readyState == 4 && input.value != "") {
var response = JSON.parse('(' + req.responseText + ')');
for (var i = 0; i < response.length; i++)
addSuggestion(response[i].terms);
}
}
req.open('GET', 'getterms.php?query=' + input.value, true); //GET request to getterms.php?=
req.send(null);
}
addSuggestion = function (suggestion) {
var div = document.createElement('div');
var p = document.createElement('p');
div.classList.add('suggestion'); //suggestion[x]...
p.textContent = suggestion;
div.appendChild(p);
output.appendChild(div);
div.onclick = function() {
input.value = p.innerHTML; //set the search box
getSuggestions(); //GET new suggesions
}
}
}
</script>
<input type='text' id='search' name='search' autofocus='autofocus'>
<div id='results'></div>
</body>
</html>
edit this is my php page that echos the json.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
if (!isset($_GET['query']) || empty($_GET['query']))
header('HTTP/1.0 400 Bad Request', true, 400);
else {
$db = new PDO(
my database
);
$search_query = $db->prepare("
SELECT * FROM `words` WHERE `word` LIKE :keywords LIMIT 5
");
$params = array(
':keywords' => $_GET['query'] . '%',
);
$search_query->execute($params);
$results = $search_query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
?>
Get rid of the ( and ) in the JSON.parse!
JSON.parse('(' + req.responseText + ')')
should be
JSON.parse( req.responseText );
hopefully the responseText is valid JSON