Trying to send value from javascript to python server

I have multiple input tags, my task is to collect the values ​​entered by the user and send them back to the server. I am using Django as my framework. I manage to send data to client side (javascript). To return data from javascript function to my python function, I used XMLHttpRequest. I added below code:

<html>
<head>
<style>label{ text-align:center; width:250px; color:blue; display:inline-block}</style> 
 <script type="text/javascript" src="'+url_read+'"></script>  
<script>
function submit_this()
{
var i,j;var arr=[];
for(i=0; i<Hello.length; i++)  
{
arr[i]=[];
for(j=0;j<Hello[i].length; j++) 
{
arr[i].push(document.getElementById(Hello[i][j]).value);
}
}
alert(document.getElementById(Hello[1][0]).value);  
xmlHttpReq =     new XMLHttpRequest();   
xmlHttpReq.open('POST', '/button_click',true);    
xmlHttpReq.send('w=' + encodeURI(arr));
}
</script>
</head>
<body>
<center>
<button id="submit_button" onclick="submit_this();" value="Submit">Submit</button>
</center>
</body>
</html>

      

The above code is stored in a string called html_string. Hello is a json object that is read from a file denoted by varible url_read. It was dumped with Python. The plan was to use HttpResponse to send the html_string and render the html page in reverse.

I understand that I need to do one POST function in one of the classes in views.py. But the inability to figure out how to approach this problem.

I need to somehow send a javascript data structure named arr back to the server. The main doubt is where can I put my code, where can I read the value sent by the javascript function. I want to navigate to a new page after clicking the submit button, and in Django every URL has a new function (in views.py) associated with it. Should I put it in this?

+3


source to share


1 answer


Here is an example where I am posting values ​​to a (Django) python server using JS and getting an html rendered template. I am using ul tag with id #Nearby to load html inside html. Success Ajax returns html from django view rendered via URL / getGopoints / 'endpoint

template.html

<div class="row">
    <div>
        <ul id="Nearby">

        </ul>
    </div>  
</div>

 <script>
 $(document).ready(function(){
          $('#dataTables-example1').DataTable({
                    responsive: true
            });
          getLocation();
    });
 function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } 
    }


function showPosition(position) {
        $.ajax({
                url : '/getGopoints/', // the endpoint
                type : 'GET', // http method
                data : { 'lat' : position.coords.latitude,
                         'lon' : position.coords.longitude,
                        'csrfmiddlewaretoken': '{{csrf_token}}'
                 }, // data sent with the post request

                // handle a successful response
                success : function(data) {
                  $('#Nearby').html(data);  
                },
                dataType: 'html'

        });
    }
</script>

      

urls.py



 url(r'^getGopoints/$',views.getGopoints, name='getGopoints'),

      

views.py

def getGopoints(request):
    lat = str(request.GET['lat'])
    lon = str(request.GET['lon'])
    pnt=fromstr('POINT(%s %s)' %(lon,lat))
    with_in_distance = 20
    go_points = GoPoint.objects.filter(point__distance_lte=(pnt, D(km=with_in_distance)))
    context = RequestContext(request,
        {'go_points':go_points,
        'with_in_distance':with_in_distance,
        })
    return render_to_response('nearby.html',
                             context_instance=context)

      

0


source







All Articles