I want ajax to send POST to json file of location information and text

Asked 2 years ago, Updated 2 years ago, 118 views

Currently, we are creating a web application function that sends data with location and text in Geolocation to json via ajax.I can't say that I'm confident in the communication part of the json data by ajax, and the current code is unresponsive.If you have any advice on how to obtain input data and send POST through ajax, please let me know.
The following code

<html>
<head>
<metacharset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css"/>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script>
window.addEventListener('DOMContentLoaded',
    function(){
    if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(
        function(pos){
        var bodyHeight=$('body').height();
            $("#gmap").css('height', bodyHeight-200);
            var latlng = {lat:pos.coords.latitude, lng:pos.coords.longitude};
    vargmap = new google.maps.Map(
      document.querySelector("#gmap"),
      {
        zoom:16,
        center: new google.maps.LatLng(latlng),
        mapTypeId—Google.maps.MapTypeId.ROADMAP
      }
    );
        var marker = new google.maps.Marker({position:latlng,map:gmap});

},

// Failed to retrieve location information
function(err){
        varmsgs = [
        err.message,
        'You are not allowed to retrieve location information.',
        'Failed to retrieve location information.',
        US>'Timeout while retrieving location information.'
    ];
    window.alert(msgs[err.code]);
},
    // Set Location Acquisition Behavior Options
    {
        timeout: 10000,
        maximumAge: 0,
        enableHighAccuracy —true
    }
);
    } else{
window.alert('Go to the Geolocation API-enabled browser.');
}
    }, false
);



// Place the position data argument into input
function getMarkerPos(){
document.getElementById('lat'.value=latitude);
document.getElementById('lng'.value=longitude);
};

    // Send data
$("button").click(function(){
var button = $(this);
button.attr("disabled", true);// disable button to prevent multiple transmissions

vardata = {
        title: $("#title").val(),
        lat —parseFloat($("#lat").val()) ,
        lng —parseFloat($("#lng").val()) ,
        comment: $("#comment").val()
        };
    // Communication execution
    $.ajax({
        type: "post",
        url: "/path/to/post",
        data —JSON.stringify (data),
        contentType: 'application/json',
        dataType: "json",
        success:function(json_data){
        if(!json_data[0]){
                alt("handling error" + json_data[1]);
            return;
        }
     location.reload();
        },
    error: function() {
        alert("Server error.Please try again");
        },
        complete:function(){
        button.attr("disabled", false);
        }
        });
    });

</script>
</head>
<body>
    <div data-role="page"id="submit">
        <div data-role="header">
            <h1>DEMO</h1>
    </div>

        <div class="ui-field-contain">
            <label for="text-title" > Title </label>
            <input type="text" name="title" id="title" value="/>
        </div>

        <div data-role="content" id="map_content">
            <divid="gmap"></div>
            </div>

        <!--- Longitude information to ajax -->
        <input type="hidden" name="lat" id="lat"/>
        <!--Latitude information to ajax -->
        <input type="hidden" name="lng" id="lng" />

        <div class="ui-field-contain">
            <label for="text-comment">Comments</label>
            <textareacols="40" rows="8" name=textarea id="comment">/textarea>
        </div>
        <div role="main" class="ui-content">
            <button class="ui-btn">Send</button>
        </div>

    <div data-role="footer">
        <div data-role="navbar" data-iconpos="bottom" class="navi_bar">
        <ul>
        <li class="ui-block-a"><a href="#" data-icon="home">Map</a></li>
        <li class="ui-block-b"><a href="#" data-icon="info" class="ui-btn-active ui-state-persist">output</a></li>
        </div>
    </div>
    </div>

    </body>

<style type="text/css">
    #gmap {
        width: 100%;
        height: 400px;
        border:4px solid #fff;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        }
</style>

javascript json ajax

2022-09-29 21:22

1 Answers

First of all, I bind click, but if I write directly globally, DOM is not ready, so I can't bind it.
DOMContentLoaded.
This should start running click events

first.

Also, is it meaningful that data is used as a JSON string when post to ajax?
If you do the following, you can pass the object as it is.
Also, if there is no communication error determination argument, it will be difficult to deal with the error.
I think you should put it on during the exam.

// Communication Execution
$.ajax({
    type: "post",
    url: "/path/to/post",
    data —data,
    dataType: "json",
    success:function(json_data){
        if(!json_data[0]){
            alt("handling error" + json_data[1]);
            return;
        }
        location.reload();
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log (XMLHttpRequest);
        console.log(textStatus);
        console.log (errorThrown);
        alert("Server error.Please try again");
    },
    complete:function(){
        button.attr("disabled", false);
    }
});

To isolate the problem, you should first investigate how far the code runs.
In this case,
1. Are click events running?
2. Is the communication working?
3. Are communication parameters correct?
should be able to investigate
Let's investigate by placing a console.


2022-09-29 21:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.