0

On a Django website, I am trying to check a field input for database matches. I have search functions in my Django .py files, but since I can't run them after page load, I'm assuming a JavaScript POST request is the best option.

<input id="this_field" onblur="querySomething()">

There are numerous SO questions on JS POST [1, 2, 3, etc], however, I haven't been able to get any of them to work for me. Here's one of my many attempts to get something useful going:

function querySomething(){
    $.ajax({
       type: "POST",
       url: "/my/url/",
       data: {"check_this": "123-456789",},
       success: function() {
         alert('success');
       }
    });

Or,

function postSearch() {
    $.post("/my/url/",
    {
        "check_this": "123-456789",
    },
    function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    })
}

If I just treat the input like a search field and submit it (with JS or otherwise) it works fine. However, since I'm trying to provide results to help the user finish filling out the rest of the page, I need the results to be available on the same page as soon as the user focus leaves the field.

I don't know if my {% csrf_token %} token comes into play here. I'm not getting any errors or messages in the console or in my server logs.

// Edited version of code now reads:

function querySomething(){
    $.ajax({
        type: "POST",
        url: "/my/url/",
        headers: {
            "Content-Type": "application/json",
            "HTTP_GROUP_NAME": "groups_name",
        },
        data: {
            "check_this": $('#this_field').val(),
            "csrfmiddlewaretoken": "{{csrf_token}}",
        },
        success: function(data){
            console.log("success");
            console.log(data);
        },
        failure: function(data){
            console.log("failure");
            console.log(data);
        },
    });
    alert('marcusShep function ran.')
}
Community
  • 1
  • 1
whyeliah
  • 95
  • 1
  • 2
  • 9

1 Answers1

2

You are hard coding the post data with "check_this": "123-456789",.

You could use GET rather than POST because you're not creating an element. Yet you are retrieving a few.

Also, you haven't defined a failure function. This will help you with debugging quite a bit.

$.ajax({
    type: "GET",
    url: "/my/url/",
    data: {
        "check_this": $("#this_field").val(),
    },
    success: function (data) {
        console.log("success");
        console.log(data);
    },
    failure: function (data) {
        console.log("failure");
        console.log(data);
    },
});

Your view should then look something like:

from django.http import JsonResponse

def foo(request, *a, **kw):
    # Notice I didn't directly try to access request.GET["check_this"]
    search_value = request.GET.get("check_this", None)
    if search_value:
        data = dict()
        # Finding some data that you want.
        data["result"] = MyModel.objects.filter(name=str(search_value))
        # Using Django's beautiful JsonResponse class
        # to return your dict as JSON.
        return JsonResponse(data, verify=false)
Joe
  • 879
  • 3
  • 14
  • 37
marcusshep
  • 1,916
  • 2
  • 18
  • 31
  • Hard coded to limit possible mistakes pasting here. I changed `{% csrf_token %}` to `"{{csrf_token}}"` to fix `... unexpected <` error as the former drops a hidden ` – whyeliah Jun 17 '16 at 00:22
  • @whyeliah if you found this answer helpful you should consider accepting it. – marcusshep Jul 01 '16 at 19:04