Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing variable from javascript to server (django)

I am trying to send the users current location variable (after the user clicks allow) from the browser to Django server using jQuery's post method. The current location is stored in the variable pos.

$(document).ready(function(){
    $.post("/location", pos)
});

In django, i've created a url /location in urls.py which captures the pos variable in views.py through request.POST(pos), which I use to carryout distance lookups.

I see that the variable is not being passed to the django server, Can someone please advise where I am going wrong ?

like image 906
kurrodu Avatar asked Sep 03 '13 17:09

kurrodu


1 Answers

I have assigned the JavaScript location variable(pos) in Google geolocation API to an input element (id= "location") in HTML form by using the below code

document.getElementById('location').value = pos

Below is my HTML form

<form id = "geolocation" action="/location" method="POST" >
            {% csrf_token %}
        <input type="text" id = "location" name="location" value="" />
        <input type="submit" />

</form>

Then within my google geolocation API, I auto submit the form by adding the below line of code

document.getElementById("geolocation").submit(); 

Finally within Django Views.py file, I use the 'POST' method to obtain the location from the client side within the function where I am using the variable

user_location = request.POST.get('location')

Here is a link to Google Geolocation API.

I've inserted excerpt from my code, just so that you may know where exactly I've used the above lines of JavaScript code in the Google Geolocation API.

var infowindow = new google.maps.InfoWindow({
    map: map,
    position: pos,
    content: 'Location found using HTML5.'
  });
  // the below line has been inserted to assign a JS variable to HTML input field called 'geolocation' 
document.getElementById('location').value = pos
map.setCenter(pos);
// the below line has been inserted to autosubmit the form.  
document.getElementById("geolocation").submit(); 
like image 188
kurrodu Avatar answered Oct 20 '22 09:10

kurrodu