Issues with AJAX causing MYSQL to get NULL data inserted

My HTML code collects latitude and longitude coordinates and sends them to a PHP script using AJAX. However, the issue is that the AJAX request inserts NULL values into the database table. It seems to be inserting "0.000000" for both Latitude and Longitude fields even though they are defined as float(10,6) in the database following GPS coords best practices. As I am a new developer, any help would be greatly appreciated.

<!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.longitude);
    }

    // onError Callback receives a [PositionError](PositionError/positionError.html) 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>

The corresponding PHP script:

<?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";

        }
    }


?>

Answer №1

To update, use the following code to replace the xttp open and send functions:

    xttp.open("POST", "ConnectTest.php, true);
    xttp.send(latitude="+latitude+"&longitude="+longitude);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing complex analytical queries in Mysql in real-time: A comprehensive guide

Running a CRM application that heavily utilizes MySQL database means generating substantial amounts of data. Now, the goal is to create a reporting section for customers where admins can access real-time reports with filtering capabilities. The aim is to ...

Unable to access controller using jquery/ajax in CodeIgniter along with a bootstrap template

When loading a page into another, everything seems to be working fine except for the controller loading: The scripts and CSS are being loaded in the default page code, which might be causing the issue. The error message "Failed to load resource: the serve ...

Ensure to verify the presence of a null value within the ngFor iteration

I have a webpage where I am displaying information in buttons. These buttons show various objects from a list along with their corresponding fields (e.g. object.name, object.age, etc.). Sometimes, one of those fields is null. How can I check if a value is ...

Issue with Jquery similar to javascript createElement

I am attempting to replicate the code below using jQuery: var newElem = document.createElement("div"); newElem.innerHTML = "DynaColumn"; newElem.className = "ui-state-default ui-corner-all"; return newElem; This is the jQ ...

Working with an array of object in Vuex for form handling

Looking to make updates to a vuex store that includes an array of objects: Users have a combobox for making selections, which then updates a property of the object in the database. However, every time I choose an item from the autocomplete (combobox) I e ...

What is the Angular approach for configuring a form's encoding type to application/json?

I need to send form data using a POST request that triggers a download, making it impossible to use any Javascript requests. Therefore, calling a function with the $http service is not an option. Additionally, I require the corresponding backend route in ...

Preventing navigation without using the <Prompt> component in React Router DOM V6

I have recently discovered that in react-router-dom v5, it was possible to utilize the <Prompt> component to prompt the user before a page transition occurs, allowing them to prevent it. However, this feature has been removed in v6 with plans for a m ...

Checking the Value of the Second Child Element Using jQuery

I am struggling with a DIV structure that looks like this: <div class="metafield_table"> <div class="metafield"></div> <div class="metafield"></div> <div class="metafield"> ...

Is it possible to use jQuery to load a page via AJAX and define a callback function on the loaded page

Currently, I am using the $('#container').load method to manage loading all the subpages of my website. However, some of these sub-pages require additional functionality such as form validation. I would like each sub-page to be self-contained, m ...

Deleting a record by sending an HTTP request and then removing the corresponding object from an array in Vue.js

After successfully solving this particular issue with the help of @nils, I have encountered a new question that I hope someone can assist me with! My current situation involves having a list of records from which I can select and remove items with just on ...

Unsuccessful Ajax call in Rails application

I'm a bit perplexed as to why my Ajax call is failing. It was previously working fine and I can't identify any changes that might have caused it to stop. When I initiate the call, an error pops up in Firebug's console pointing to this sectio ...

Incorporating a YouTube channel into mobile websites

While it's relatively easy to embed single YouTube videos in mobile pages with the help of Google, I'm still struggling with embedding a whole channel. The issue seems to revolve around the screen width, and my attempts at using JavaScript have n ...

Best practices for passing search criteria to subsequent pages while implementing pagination in PHP

My website features a search block with various options for users to search. The search function is functioning correctly, but I am unsure how to pass the search parameters to other pages while using pagination in PHP. I am hesitant about creating a form ...

Optimizing Variable Destructuring Efficiency

Is there a difference in performance when assigning variables like const color = props.color; compared to destructuring like this const { color } = props; Furthermore, does destructuring within the parameters affect performance positively or negatively ...

Servlet malfunctioning while retrieving data from database

I am looking to develop a straightforward web application using Ajax in Java. I have a local database with a single table consisting of two columns: ID and Surname. The goal of my application is to show the user the correct surname based on their input (f ...

"Effortlessly move files with Filedrop HTML 5 and Jquery drag-and-drop feature

I am trying to implement a drag and drop file feature on my webpage, but for some reason, it's not working as expected. The drop zone is supposed to change its background color when I drag a file onto it, but that functionality doesn't seem to be ...

Setting up eslint for your new react project---Would you like any further

I am currently working on a TypeScript-based React application. To start off, I used the following command to create my React app with TypeScript template: npx create-react-app test-app --template typescript It's worth noting that eslint comes pre-co ...

Exploring the mechanics behind ES6 Map shims

From what I've gathered from the documentation (here and here), it seems that having a reference to the memory address is necessary for the operation to work: const foo = {}; const map = new Map(); map.set(foo,'123'); // This action requi ...

Converting Buffers to Binary with JavaScript Node.js

I've been working with Node.JS Buffers to send and receive packets, but I'm struggling to figure out how to convert these buffers into binary representation. I attempted the following code snippet, but it didn't yield the expected results co ...

Unbinding or undoing an 'onclick' event when another 'onclick' event is triggered

I am facing an issue where clicking on elements with 'onclick' functions works as expected, but when I click on a different element with another 'onclick' function, the first one remains active. What I actually want is for the previous ...