Passing django variable in ajax data - ajax

I would like ajax to post some variables which have been created in a view.
My problem is that it isn't written in the proper way and anything is sent to my post request when I am looking at the chrome inspecter.
This is my javascript function :
function submitDataTable() {
let table = $(document.getElementById('datatable')).DataTable()
let advisedPriceColumn = table.column('advised_price:name')
let advisedPriceData = advisedPriceColumn.data().toArray()
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' }
})
$.ajax({
url: 'submit/',
type: 'POST',
data: {
advisedPrice: advisedPriceData,
normal_price: '{{ normal_price|safe }}',
},
processData: false,
success: res => {
alert('Bien ouej mon vieux')
location.reload()
},
error: xhr => {
alert(xhr.responseText.split('\n')[1])
}
})
};
These are some of the variables of my view that I would like to pass in my JS function:
return render(request,'livedb_model/typeDetail.html',{
'property':property,
'roomtype':roomtype,
'invdf':invdf,
'price_advised_list':price_advised_list,
'price_list':price_list,
'occupancy_list':occupancy_list,
'c_occupancy_list':c_occupancy_list,
'normal_price_list':normal_price_list[:100],
'normal_price':normal_price,
'week_day_multi':week_day_multi,
'week_end_multi':week_end_multi,
'max_discount':max_discount,
'max_markup':max_markup,
'coccCategory':coccCategory,
'agressiveness':agressiveness
})
And this is a screenshot of the chrome inspector, where we can see that only an [object Object] is passing
Please can you help me on this?

You can't use django tags in .js file, what you can do is set data attributes in html like -
<input type="text" data="{{ normal_price|safe }}" id="id_normal_price" value="">
and then get it into your js like -
normal_price: $("#id_normal_price").attr("data")
you can set data values in any html tag.
Look at - https://www.w3schools.com/tags/att_global_data.asp

Related

Pass a nullable variable from twig to ajax js

I have the following ajax request:
$(document).ready(function () {
$.ajax({
url: '{{ admin.generateUrl('url') }}',
method: 'GET',
data: {
'id': {{ object.id }}
},
success: function (html) {
//
},
});
Data being optional as this request will be called in two different pages, create and /{id}/edit. How do I pass this to my data as the id of the object will not be always present?

Ajax call with flask-seasurf

I am developing a small app on localhost and using flask-seasurf to prevent csrf attacks. All my non-ajax forms work correctly with flask-seasurf. I have one form that triggers an ajax call to '/checkajax' on form submit; this worked until I started to use flask-seasurf but now I get a console error and the ajax doesn't work:
Warning in flask_seasurf: Forbidden (CSRF token missing or incorrect): /checkajax
The form triggering the ajax call has the standard hidden field containing the 'csrf_token()' function call of flask-seasurf embedded in the jinja page template:
<input id="csrf-token" type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
The ajax call structure is:
$("#submit").submit(function(event) {
event.preventDefault();
$.ajax({
url: "/checkajax",
data: {...},
type: "POST",
datatype: "text",
success: function(response){
...
},
error: function(response) {
...
}
});
});
I can see from the site cookie that there is an entry for '_csrf_token' generated by flask-seasurf. Can anyone give some insight as to why this ajax call is now not working?
The solution to my problem was to modify the header of the ajax call to include X-CSRFToken defined as the flask-seasurf token from my form:
var csrf_token = $("csrf-token").val()
$("#submit").submit(function(event) {
event.preventDefault();
$.ajax({
headers: {"X-CSRFToken", csrf_token},
url: "/checkajax",
data: {...},
type: "POST",
datatype: "text",
success: function(response){
...
},
error: function(response) {
...
}
});
});
Hope that helps someone else.

Ajax Post URL with button id, Django Server

I'm trying to delete an element in a list by clicking a button, each button got the pk of the element as id
$('.delete').on('click', function (event) {
var evaluacion_id = this.id;
$.confirm({
title: 'Desea Eliminar Evaluacion?',
content: 'De ser asi no podra Recuperar estos datos',
buttons: {
confirm: function (evaluacion_id) {
var url = "{% url 'delete-evaluacion' evaluacion_id %}"
$.ajax({
type:"POST",
url: url,
success: function(){
location.href="{% url 'evaluaciones-psicologo' informe.proceso.pk %}"
}
});
},
cancel: function () {
$.alert('Continue Evaluando');
},
}
})
});
if i do $.alert("Delete "+evaluacion_id); instead of the ajax function everything its ok and it shows me the correct id
But if I call it with ajax function, throws me this
Reverse for 'delete-evaluacion' with arguments '('',)' not found. 1 pattern(s) tried: ['INTRANET\\/delete-evaluacion/(?P<pk>\\d+)$']
And my urls.py
url(r'^procesos/EvaluacionesPsicologo/(?P<pk>\d+)$',views.evaluaciones_psicologo,name='evaluaciones-psicologo'),
url(r'^procesos/EvaluacionePsicologo/(?P<pk>\d+)$',views.evaluacion_psicologo,name='evaluacion-psicologo'),
url(r'^delete-evaluacion/(?P<pk>\d+)$', views.EliminarEvaluacion, name='delete-evaluacion'),
The problem is that the template tag {% url 'delete-evaluacion' evaluacion_id %} is evaluated when the template is rendered, not when the JavaScript is run. Django doesn't know the variable evaluacion_id, so it tries to reverse the URL with an empty string, which doesn't match the URL pattern.
The proper way to do this would be to get the URL pattern and transform it into the template URL format, but that would require diving deep into the internals of Django's URL resolving and is probably not worth the hassle. There is a library that does that for you: Django JS Reverse
A more pragmatic approach would be to reverse the URL with a dummy ID, which you then replace in JavaScript.
$('.delete').on('click', function (event) {
var evaluacion_id = this.id;
$.confirm({
title: 'Desea Eliminar Evaluacion?',
content: 'De ser asi no podra Recuperar estos datos',
buttons: {
confirm: function (evaluacion_id) {
var url = "{% url 'delete-evaluacion' 9999 %}".replace('9999', evaluacion_id);
$.ajax({
type:"POST",
url: url,
success: function(){
location.href="{% url 'evaluaciones-psicologo' informe.proceso.pk %}"
}
});
},
cancel: function () {
$.alert('Continue Evaluando');
},
}
})

PATCH AJAX Request in Laravel

Is it possible to make AJAX PATCH requests to laravel, or am I restricted to POST? Laravel uses PATCH in input hidden fields, however, I am not using form elements—just buttons that should partially update a record when clicked (via an AJAX request).
How would the route look like for this?
Routes file
Route::patch('questions/{id}', 'QuestionController#update')->before('admin');
I am not sure if laravel routes support PATCH.
Controller
public function update($id) {
if (Request::ajax() && Request::isMethod('patch')) {
//partially update record here
}
}
JS
$('div#question_preview <some button selector>').click(function (event) {
$.ajax({
url: 'questions/'+question_id,
type: 'PATCH',
data: {status: 'some status'}
});
});
I am just looking for clarity, thanks!
Yeah, it's possible try
In Your JavaScript
$('#div#question_preview <some button selector>').click(function() {
$.ajax({
url: 'questions/'+question_id,
type: 'PATCH',
data: {status: <SOME VALUE I WANT>, _method: "PATCH"},
success: function(res) {
}
});
});
In Your Route
Route::patch('questions/{id}', 'QuestionController#update')->before('admin');
In your QuestionController Controller's update method
dd(Request::method());
You will see the respond like
string(5) "PATCH"
Read more about Request Information on Laravel doc.
It's possible!
You should need to provide an extra parameter in the form request called as _method with a value PATCH.
JS
$('div#question_preview <some button selector>').click(function (event) {
$.ajax({
url: 'questions/'+question_id,
type: 'PATCH',
data: {status: 'some status',_method: 'PATCH'}
});
});
You can provide a hidden input in the view file with the value PATCH for better readability
HTML
<input type="hidden" name="_method" value="PATCH">
If you are using FormData, you need to send the request as POST. The Laravel application will automatically get it as a PATCH request because you included #method('PATCH'). So your route and method for that will get triggered.
JS with FormData
$('div#question_preview <some button selector>').click(function (event) {
let form_data= new FormData();
form_data.append('status','some status');
form_data.append('_method','PATCH');
$.ajax({
url: 'questions/'+question_id,
type: 'POST',
data: form_data
});
});

NotFoundHttpException: No route found for "POST / in SYmfony2

I have an ajax posted form causing me to want to pull my hair having tried various answers based on almost similar problems here to no avail.
I have the following route in my routing.yml file
_save_profile:
pattern: /register/save-profile/{data}
defaults: {_controller: MYBundle:Registration:saveProfile}
requirements:
_method: GET|POST
options:
expose: true
and use the following code to post my form
var postData = $('#form').serializeArray();
$.ajax(
{
url: Routing.generate('_save_profile',{
type: "POST",
data : postData,
}).done(function()
{
alert("Saved");
});
Any help will be much appreciated.
You don't need send form data through parameter {data} in route. If you want send form with ajax, so you need.
Change route:
_save_profile:
pattern: /register/save-profile/
defaults: {_controller: MYBundle:Registration:saveProfile}
Change js:
var postData = $('#form').serializeArray();
$.ajax({
url: Routing.generate('_save_profile'),
type: "POST",
data: postData,
dataType: "json",
success:
function(result) {
console.log(result);
},
error:
function() {
alert('Error')
}
});
note: I don't use FOSJsRoutingBundle bundle for js routing. I always render route on template in data attribute. For example.
html
<form type="POST" id="form" data-url="path('_save_profile')">
js
var url = $('#form').data('url');
References
How to implement a simple Registration Form
FOSJsRoutingBundle documentation

Resources