AJAX Call to python view from JavaScript not happening (Django) - javascript

Views.py (View function)
#csrf_exempt
def updateLogs(request):
print("Log AJAX call")
return HttpResponse("Hello")
javascript file
function updateConsoleLogOnPage(var1){
jobName = var1.value;
alert(jobName);
$.ajax({
type: "POST",
url: "my-logfetch",
data: { csrfmiddlewaretoken: '{{ csrf_token }}', text: jobName },
success: function callback(response){
alert(response);
}
});
}
URLs.py
from . import views
urlpatterns = [
url('my-ajax-test/', views.updateSUTInfo, name='ajax-test-view'),
url('my-logfetch/', views.updateLogs, name='my-logfetch-view'),
]
Calling Javascript function from HTML onchange event of SELECT.

Related

Django + Ajax: why does it redirect to a new URL and renders the response on browser?

Based on my understanding, ajax could be used to prevent the page from reloading/refreshing/redirecting after submitting a request to the server. However, my code will redirect to display the JSON response. I used e.preventDefault() and it didn't work. Is there anything that I am doing wrong?
My Django code looks like this:
views.py:
def projects(request):
if request.method == 'POST':
task_id = request.POST.get('task_id')
myUser = User.objects.get(pk=request.user.id)
myTask = Task.objects.get(pk = task_id)
myTask.claimed.add(myUser) #add the user to the task
return JsonResponse({'status': 'ok'})
projects = Project.objects.all()
tasks = Task.objects.all()
open_tasks = tasks.filter(status='Created')
proj_dict = {}
context = {
'projects' : projects,
'tasks' : tasks,
'open_tasks' : open_tasks,
}
return render(request, 'projects/projects.html', context)
My HTML:
<form action="{% url 'projects:' %}" method="POST" class='join-form' id='{{task.id}}'>
{% csrf_token %}
<input type="hidden" name="task_id" value={{task.id}}>
<button type="submit" class=" claim-font claim-button">
Join
</button>
</form>
Tha ajax call:
<script>
$(document).ready(function () {
$('#join-form').on('submit', function (e) {
e.preventDefault();
e.stopPropagation();
const url = $(this).attr('action');
console.log("here we are");
const task_id = $(this).attr('id');
$.ajax({
type: 'POST',
dataType: "json",
headers: { 'X-CSRFToken': csrftoken },
url: url,
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
task_id: task_id,
},
success: function (response) {
alert(data);
console.log("here we are");
},
error: function (response) {
console.log('error', response);
alert("shit")
}
})
return false;
});
});
</script>
Seems like ajax will make sure that my browser doesn't redirect/reload/refresh after the submit button is clicked, and only the server-side changes. However, my browser turns out to be displaying: {"status": "ok"}
Any insights are greatly appreciated!
I noticed that you have class attribute for your form. Change your JQuery selector from $('#join-form') to $('.join-form') for class attributes
<script>
$(document).ready(function () {
$('.join-form').submit(function(e) {
e.preventDefault();
// write your code here
});
});
</script>
You need to change button type from "submit" to "button"

How to make two or more AJAX calls in a single Django view

I'm developing personal spending diary and I faced the problem.
For better UX I need to make process of adding new items without reloading page .
I make single ajax form but I need two .
I'm trying to solve this problem for 3 days .
Have anybody any suggestions ?
Here is my
forms.py
class AddIncome(forms.ModelForm):
class Meta:
model = Income
fields = ( 'title','value',)
class AddExpence(forms.ModelForm):
class Meta:
model = Expence
fields = ( 'title_exp','value_exp',)
Here is full
views.py
def dashboard(request):
if request.method == 'POST':
if request.is_ajax():
addincome = AddIncome(request.POST)
if addincome.is_valid():
addincome.cleaned_data
addincome.save()
latest = Income.objects.latest('id').id
income_object = model_to_dict(Income.objects.get(pk=latest))
return JsonResponse({'error': False, 'data': income_object})
else:
print(addincome.errors)
return JsonResponse({'error': True, 'data': addincome.errors})
else:
error = {
'message': 'Error, must be an Ajax call.'
}
return JsonResponse(error, content_type="application/json")
if request.method == 'POST':
if request.is_ajax():
addexpence = AddExpence(request.POST)
if addexpence.is_valid():
addexpence.cleaned_data
addexpence.save()
latest = Expence.objects.latest('id').id
expence_object = model_to_dict(Expence.objects.get(pk=latest))
return JsonResponse({'error': False, 'data': expence_object})
else:
print(addexpence.errors)
return JsonResponse({'error': True, 'data': addexpence.errors})
else:
error = {
'message': 'Error, must be an Ajax call.'
}
return JsonResponse(error, content_type="application/json")
else:
addincome = AddIncome()
addexpence = AddExpence()
income = Income.objects.order_by('-date').filter(is_published=True)
expence = Expence.objects.order_by('-date').filter(is_published=True)
data = {
'addincome_html': addincome,
'addexpence_html': addexpence,
'income':income,
'expence':expence
}
return render(request, template_name='main/dashboard.html', context=data)
Here is
Page forms
<form method="POST" name="create_incomefrm" id="create_incomefrm" action="{% url 'create_income_record' %}">
{% csrf_token %}
{{ addincome_html.as_p }
<button type="submit" id="popup-button-2" class="dashboard__popup-button"
name="createincomefrmbtn">Add <span>→</span></button>
</form>
<form method="POST" name="create_expencefrm" id="create_expencefrm" action="{% url 'create_expence_record' %}">
{% csrf_token %}
<div class="dashboard__popup-2" id="dashboardpopup-4">
{{ addexpence_html.as_p }}
<button id="popup-button-3" name="createexpencefrmbtn" class="dashboard__popup-button">Add<span>→</span></button>
</form>
Here is
ajax forms
$('#create_incomefrm').submit(function (e) {
e.preventDefault();
var formData = {
'title': $('#id_title').val(),
'value': $('#id_value').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
contentType: 'application/x-www-form-urlencoded',
encode: true,
};
$.ajax({
type: 'POST',
url: 'create/',
data: formData,
dataType: 'json',
}).done(function (data) {
//code
});
});
$('#create_expencefrm').submit(function (e) {
e.preventDefault();
var formData = {
'title_exp': $('#id_title_exp').val(),
'value_exp': $('#id_value_exp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
contentType: 'application/x-www-form-urlencoded',
encode: true,
};
$.ajax({
type: 'POST',
url: 'create_exp/',
data: formData,
dataType: 'json',
}).done(function (data) {
//code
});
});
Solution
Create a hidden input for both form having same name/id. e.g. HTML
<!--form-1-->
<input type='hidden' name='form_type' value='income'>
<!--form-2-->
<input type='hidden' name='form_type' value='expense'>
Update JavaScript accordingly.
And then on your view catch each form by -
# form-1
if request.method == 'POST' and request.POST['form_type'] == 'income':
# rest of your code
# form-2
if request.method == 'POST' and request.POST['form_type'] == 'expense':
# rest of your code

MethodNotAllowedHttpException when trying to post data to controller via ajax in laravel

I'm trying to send dynamically generated data to controller via ajax in laravel. When user select an option from the dropdown then along with selected option and other data should be sent to controller.
I've tried to send data to controller when an option from dropdown is selected. But every time i try this error,
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
and in the error
REQUEST_METHOD is GET
This is the where i call the ajax function
$(document).on('change', '.route-code-selector', function() {
var selectorID = $(this).attr('id');
addRoutePlanDetails(selectorID);
});
AJAX function
function addRoutePlanDetails(selectorID) {
var routePlanCode = document.getElementById("routeplanno").value;
var driver = $("#selectDriver").val().split('|');
var salesman = $("#selectSalesman").val().split('|');
var router_01 = $("#selectRouter01").val().split('|');
var router_02 = $("#selectRouter02").val().split('|');
var vehicle_no = document.getElementById("enterVehicleNo").value;
var route_code = document.getElementById(selectorID).value;
var date = document.getElementById("date").value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: 'addNewRoute',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
}
Route
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
Route::get ('route-plan', 'RoutePlanController#index');
Route::get ('excludePorterRes', 'RoutePlanController#excludePorterRes');
Route::get ('retreiveRouteData', 'RoutePlanController#retrieveRouteCodeData');
Route::get ('retreiveUserData', 'RoutePlanController#retreiveUserData');
Route::get ('retreiveNewRouteData', 'RoutePlanController#retreiveNewRouteData');
Route::post('addNewRoute', [
'uses' => 'RoutePlanController#insertNewRoute',
'as' => 'addNewRoute'
]);
});
controller
public function insertNewRoute(){
$routeplan = new Routeplan;
$user_email = auth()->user()->email;
$routeplan->RouteplanCode = Input::get('routePlanCode');
$routeplan->RouteCode = Input::get('route_code');
$routeplan->DriverID = Input::get('driver');
$routeplan->SalesmanID = Input::get('salesman');
$routeplan->Routercode1 = Input::get('router_01');
$routeplan->Routercode2 = Input::get('router_02');
$routeplan->VehicleNo = Input::get('vehicle_no');
$routeplan->Date = Input::get('date');
$routeplan->Createuser = $user_email;
$routeplan->Status = 'TEMP';
$routeplan->save();
}
when user select an option all the data should be stored in the db.
Try it once
url: '{{ route('addNewRoute') }}',
The issue is here:
url: 'addNewRoute',
here you are calling the route in a wrong manner, use it like:
url: '{{ url('admin/addNewRoute') }}',
you have to call the url() method so that it can create the right url format and don't forget the addNewRoute is grouped under admin, so you have to append that to while calling it.
If ajax method is runs in external javascript file, you should define a url variable in the blade (generally it layout blade.) that using as ajax request url on the ajax call method. (before .js file is loaded);
Example var url = '{{ route('addNewRoute') }}'
$.ajax({
url: url',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
If you using ajax in the blade, you can use directly route as ajax request url.
$.ajax({
url: "{{ route('addNewRoute') }}",
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
You forgot / in your routes.
Route::group(['prefix' => 'admin'], function () {
Add / in admin/
Route::group(['prefix' => 'admin/'], function () {
Then you can try this in your ajax
url: '{{ url('admin/addNewRoute') }}',
or
url: 'admin/addNewRoute',
Try if this will work.
You have used prefix for your routes. So all your route in group will be prefix/uri.
So in ajax call you should url: '{{ url('admin/addNewRoute') }}', and change method to type
$.ajax({
url: '{{ url('admin/addNewRoute') }}',
type: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
In ajax for specifying HTTP Verb use type not method.
if your script is in blade file then use route() to set url in ajax:
$.ajax({
url: '{{route('addNewRoute')}}',
method: 'POST',
dataType: 'json',
...
});
Try this:
Please use url: '{{ route('addNewRoute') }}' instead of url: 'addNewRoute'.
As many of you said.. I changed method to type.. And it still didn't work. But then i looked at laravel logs (storage/logs) and from the logs i found that some of my controller syntax are incorrect. And that's why it still gave me the 500 error. After I changed the syntax and do the corrections. It worked !! Anyways thanks for helping guys! If anyone is getting this error even if your ajax is correct take a look at laravel logs.. Hope this helps someone.

Django: Ajax not receiving data from server response

I am pretty new to Django and I am trying to figure out how to add content dynamically coming from a python script without reloading a page.
Currently, I have two functions in my views.py file. One handles uploading a file (home), and the other handles calling a python script and handling the file (handle). The reason I separated it like this is because I want to sequentially populate a HTML table as the python script works with the uploaded file.
However, my ajax function is not receiving any data from the handle function's http response and I am not sure why. Neither the success nor the error functions are being called. This is really strange because the print statement in the handle function in views.py prints successfully with data.
Views.py
i=0
uploaded_file = None
def home(request):
if (request.method == 'POST'):
file_form = UploadFileForm(request.POST, request.FILES)
if file_form.is_valid():
global uploaded_file
uploaded_file = request.FILES['file']
print(uploaded_file)
else:
file_form = UploadFileForm()
return render(request, 'personal/home.html', {'form': file_form})
def handle(request):
# TODO make ajax wait for a response from 'home'
# so I don't have to wait for 1 second
time.sleep(1)
data = {}
data['Name'] = fileName(uploaded_file)
if(request.is_ajax()):
print(data) # prints succesfully
return HttpResponse(json.dumps(data),
content_type="application/json")
home.html
<script type = "text/javascript" language = "javascript">
function post_tables(data) {
alert(data)
}
$(document).ready(function(post_tables) {
$("#upload").click(function(event){
$.ajax( {
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "get",
url:'/handler',
success: function(data) {
console.log("over here")
post_tables(data)
},
error: function(data) {
console.log("down here")
post_tables("error being thrown")
}
});
});
});
</script>
urls.py
urlpatterns = [
path(r'', views.home, name='home'),
path(r'handler', views.handle, name='handle'),
]
I explained the whole process ajax django to you. Perhaps your problem will be solved. good luck.
views.py
def handle(request):
if request.method == 'POST':
data = request.POST
field_example = data.get('field_example')
return JsonResponse(data)
else:
data = request.GET
field_example = data.get('field_example')
return JsonResponse(data)
home.html
<form id="upload">
{% csrf_token %}
<input type="text" name=field_example>
.
.
.
</form>
urls.py
urlpatterns = [
path(r'', views.home, name='home'),
path(r'handler/', views.handle, name='handle'),
]
js code in home.html:
$("#upload").submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "{% url 'handle' %}",
type: 'GET',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log("over here")
post_tables(data)
},
error: function (data) {
console.log("down here")
post_tables("error being thrown")
}
});
});

Django returning None after request.POST.get

I'm new to Django and AJAX and I'm trying to send the ID of a dropdown list to the Django View with an ajax POST. This ID is then used in a queryset filter to return with AJAX the row, based off the ID. I'm getting stuck with applying the filter to the query set, as it seems to be posting the ID and then a variable with None. When I print to console the variable sent in the POST I get the ID, followed by none, e.g.:
1748
None
My HTML is:
<select id="drugSet">
{% for dose in dose_set %}
<option id="{{ dose.pubmed_id }}">{{ dose.drug_name }}</option>
{% endfor %}
</select>
<span id="drugName"></span>
Javascript:
function NeedDrugInformation() {
var elementID = document.getElementById("drugSet");
var strUser = elementID.options[elementID.selectedIndex].id;
$.ajax({
type: "POST",
url: "drugsanddoses/",
dataType: "text",
async: true,
data: { csrfmiddlewaretoken: '{{ csrf_token }}', drugID: strUser },
});
$.ajax({
type: "GET",
url: "drugsanddoses",
dataType: "text",
async: true,
data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
success: function (json) {
$('#drugName').html(json.drugInfo);
// $('.ajaxProgress').hide();
}
})
}
views.py:
def drugsanddoses(request):
drugIdentifier = request.POST.get('drugID')
print(drugIdentifier)
drugInfo = RiskCalculator.objects.values('drug_name', 'l_dose', 'h_dose', 'risk', 'pubmed_id', 'updated')
response_data = {}
try:
response_data['drugInfo'] = str(drugInfo)
except:
response_data['result'] = 'No details found'
response_data['message'] = 'There is currently no information in the database for this drug.'
return HttpResponse(json.dumps(response_data), content_type="application/json")
You're making two Ajax requests; one a POST, where the ID is present, and one a GET, where the ID is absent so it prints None. I don't really understand why you're making two requests, but that is what you are doing.

Categories