pynovice
pynovice

Reputation: 7752

Ajax is giving back all the html instead of the variable in Django?

I have a Ajax and template like this:

<html>
<body>

<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            document.myForm.time.value = ajaxRequest.responseText;
        }
    }
    url = '/home'
    ajaxRequest.open("GET", url, false);
    ajaxRequest.send(null); 
}


//-->
</script>



<form name='myForm'>
{% csrf_token %}
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' id='time' value="" />
</form>
</body>
</html>

And I have simple views like this:

from django.shortcuts import render_to_response, HttpResponse
import simplejson
from django.template.context import RequestContext
import datetime

def home(request):
    if request.GET:
        a = datetime
        return HttpResponse(simplejson.dumps(a), mimetype='application/json')
        #return render_to_response('home.html', {'a':a}, context_instance=RequestContext(request))


    else:
        return render_to_response('home.html', context_instance=RequestContext(request))

Ajax is loading when I press enter but instead of the particular variable all the template is loading in the input box. What's wrong?

Upvotes: 0

Views: 128

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599610

This line:

if request.GET:

checks to see if there are any GET parameters. There aren't, because you're not sending any. The URL is just /home. You could use if request.method == 'GET', but I think you're checking for the wrong thing here: a normal request (not Ajax) will also be GET.

What you should do is send the HTTP_X_REQUESTED_WITH header as "XmlHttpRequest", then check request.is_ajax() in the view. Or, as recommended, use a library like jQuery - which sets that for you automatically.

Upvotes: 1

niconoe
niconoe

Reputation: 772

The proper way to detect request type is if request.method == 'GET', instead of if request.GET.

Upvotes: 0

Related Questions