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.')
}