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>';
}
?>
Related
I have an HMTL form with 3 fields on it, Firstname, Lastname and image upload file. When submit is pressed it calls the following JS script.
//main function to be called on submit
function processData() {
var firstName = document.querySelector('#first-name'),
lastName = document.querySelector('#last-name'),
imageUser = document.querySelector('#image-user');
var formSubmitData = {
'firstName': firstName.value,
'lastName': lastName.value,
'imageUser': imageUser.value
};
var dataString = JSON.stringify(formSubmitData);
if (navigator.onLine) {
sendDataToServer(dataString);
} else {
saveDataLocally(dataString);
}
firstName.value = '';
lastName.value = '';
imageUser.value = '';
}
//called on submit if device is online from processData()
function sendDataToServer(dataString) {
var myRequest = new XMLHttpRequest();
//new code added so data is sent to server
//displays popup message - data sent to server
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
console.log('Sent to server: ' + dataString + '');
window.localStorage.removeItem(dataString);
} else if (myRequest.readyState == 4 && myRequest.status != 200) {
console.log('Server request could not be completed');
saveDataLocally(dataString);
}
}
myRequest.open("POST", "write_test.php", true);
//Send the proper header information along with the request
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequest.send(dataString);
alert('Sent: ' + dataString + ''); //remove this line as only for example
}
As you will see it sends a POST request to the php page. The "datastring" is encoded as JSON.
I use the following PHP code to send the data to the SQL server, but all it does is create a blank record with no data but it does create a new record.
<?php
//TRYING NEW CODE TO EXTRACT DATA FROM dataString
$json = json_decode(file_get_contents("php://input"), true);
$data = json_decode($json, true);
echo '<pre>' . print_r($data, true) . '</pre>';
// INSERT into your contact table.
$sql="INSERT INTO contacts (firstName, lastName)VALUES('$firstName','$lastName')";
How do I get it to create records in SQL with data that has been submitted from the form??
I have no final solution as I don't have the form code. Hope you are ready to learn.
I'm worried about user image - don't send any image for testing, but a string (like path) or nothing, please.
js - change for double quotes:
var formSubmitData = {
"firstName" : firstName.value,
"lastName" : lastName.value,
"imageUser" : imageUser.value
};
php - leave only this
<?php
$data = json_decode(file_get_contents("php://input")); // test only version
print_r($data); // test only version
/*
and close the rest as a comment - SQL is fine, don't worry
$data = json_decode(file_get_contents("php://input",true)); // final ver
echo print_r($data, true); // final ver
...
*/
If you receive the right output, delete the trial version and good luck.
If not - go back to var formSubmitData to the values on the right - they are so naked ... without any quotes
And of course, take care of security (injection) and order, set the required at the inputs - you don't need empty submits
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);
I am using JQuery Ajax (and I am sure that things have changed since the last time I used it) but I am having trouble pulling the information from the PHP variable. Basically I am getting the IP address and logging how long it took that IP to load the page fully and then display it.
Here is my code...
getIP.php
<?php
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip = $_SERVER['REMOTE_ADDR'];
}
echo json_encode(array('ip' => $ip));
?>
Event listener that calls it
var IPAddresses = [];
//Anonymous functions - used for quality control and logging
(function() { //Used to test how long it took for a user to connect - uses a php script with it
window.addEventListener("load", function() {
$.ajax({
url: '../php/getIP.php',
type: 'POST',
success: function(result)
{
setTimeout(function alertUser(){IPAddresses.push(result.ip);}, 40);
}
});
}, false);
})();
(function() {
window.addEventListener("load", function() {
setTimeout(function() {
for (var i = 0; i < IPAddresses.length; i++)
{
var timing = performance.timing;
console.log(IPAddresses[i] + " " + timing.loadEventEnd - timing.responseEnd);
}
}, 0);
}, false);
})();
EDIT
Now I don't get errors but it does not seem to print the IP address or push it into the array at all. I am basically trying to get it to [ip] [loadtime] It gives a NaN error
Your output is a string:
echo $ip; //Just to check if it worked - it shows the IP
^---e.g. 127.0.0.1
and then you try to treat it as an array:
setTimeout(function alertUser(){alert(result['ip']);}, 40);
^^^^^^
Since it's not an array, this won't work. try just alert(result).
try to use "json_encode"
echo json_encode(array('ip' => $ip));
and in ajax
success: function(result)
{
setTimeout(function alertUser(){alert(result.ip);}, 40);
}
I want to transfer some coordinates to php (server-side) from javascript (client-side) via Ajax, and after processing (filter, etc) I want to retrieve the result to javascript, for use. The pass to php working, but I don't know how get and use the processed result from php. Any help is highly appreciated.
The php part script is:
$dbconn = pg_connect ("host=localhost port=5432 user=postgres password=xxxxxxx dbname=yyyyyyyy") or die('can not connect!'.pg_last_error());
//The nearest point of Start point
$ss='';
if (isset($_POST['kuldes_st'])){
$kuldes=$_POST['kuldes_st'];
$latk=$_POST['lat_st'];
$lngk=$_POST['lng_st'];
$query = "SELECT ST_X(the_geom), ST_Y(the_geom) FROM tbl_mypoints ORDER BY ST_Distance(the_geom, ST_GeomFromText('POINT($latk $lngk)', 4326)) LIMIT 1";
//$result = pg_query($query) or die('The query failed: ' . pg_last_error());
$result = pg_query($dbconn,$query);
if (!$result) {
die('The query failed: ' . pg_last_error());
}
else {
while ($line =pg_fetch_row($result))
{
$latitude=$line[0];
$longitude =$line[1];
$ss .= "L.latLng(".$latitude.", ".$longitude.")";
}
}
echo json_encode($ss);
}
Javascript code:
map.on('click', function(e) {
var container = L.DomUtil.create('div'),
startBtn = createButton('Start from this location', container),
destBtn = createButton('Go to this location', container);
nearestBtn = createButton('Find and go to nearest parking', container);
//Start
L.DomEvent.on(startBtn, 'click', function() {
control.spliceWaypoints(0, 1, e.latlng);
var lats=e.latlng.lat;
var lngs=e.latlng.lng;
$.ajax({
url : 'index.php',
type : 'POST',
async : true,
data : { 'kuldes_st':1,
'lat_st': lats,
'lng_st': lngs
},
success: function(data,response) {
if (response == 'success') {
alert("Post working fine");
alert(response);
console.log(data);
} else {
alert("Post don't working");
console.log(data);
}
}
});
map.closePopup();
});
I think the main problem is how to use return value.
in index.php file , you can return value without html tags. for example, if you wants to return array of number, just use code like this:
echo implode($array,",");
the data that return by ajax function is some things like this:
1,2,4,2
you can split this string to a javascript array with code like this:
var result = data.split(",");
after it, you can use the array result every where you want in jquery code.
My PHP is a bit rusty but I think the issue is that you are returning a string that is not JSON but trying to pack it up like JSON.
I think you want something more like
$ss = array();
while ($line =pg_fetch_row($result))
{
$latlng = array();
$latlng["lat"] = $line[0];
$latlng["lng"] = $line[1];
array_push($ss,$latlng);
}
echo json_encode($ss)
Forgive my PHP if it's wrong, but hopefullly from this you get the idea. At this point, the thing the server will return should look like real JSON like (
[
{"lat":46.5,"lng":24.5},
{"lat":46.5,"lng":24.5},
...
]
Then in the javascript, you can just deal with it like an array.
var latitudeOfTheFirstEntry = data[0].lat;
var longitudeOfTheSecondEntry = data[1].lng;
Do you know what L.latLng is supposed to be providing. This solution I've outlined is not using that and if that is needed, there maybe more work to figure out where that is supposed to happen.
Hope this helps
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.