how template POST parameter to view? - ajax

Hi~ o( ̄▽ ̄)ブ ,I have a question about django template POST value to view.I have done this:
buttons:
for item in items
<input type="button" id="btn1" class="btn btn-info btn-xs" name="{{item.sn}}" value="parse" onclick="func1(this.name)"
<input type="button" id="btn2" class="btn btn-info btn-xs" name="{{item.name}}" value="report" onclick="func2(this.name)
A button passes a unique value to a view's function.
views:
if request.method == 'POST':
if btn1...?
function1...
if btn2...?
function2...
and now I want to get the corresponding parameter when i click a button. and they are used separately for two functions. I used ajax to post parameters.but I don't know how to make btn1's parameters for function1, and btn2's parameters for function2. As the '?' mark indicates.How to write the ajax code andthe view's '?' code
please and thanks!

Probably you need some like this
jQuery
function func1(param){
$.ajax({
dataType: "json",
url: '/your/url/here/',
data: {"button": "button1",
"param": param,
"csrfmiddlewaretoken": $("input[name=csrfmiddlewaretoken]").val()
},
type: "POST",
success: function(data){
console.log("Post OK");
}
});
}
python
if request.is_ajax():
button_name = request.POST.get('button', None)
button_param = request.POST.get('param', None)
if button_name == "button1":
func_form_button1(param)
elif button_name == "button2":
func_form_button2(param)

Related

Laravel Ajax update request is duplicating data

i am trying to update data using ajax, but my data is being duplicated,
due to ajax URL, i am not sure if i am passing correctly/
Ajax Code:
jQuery(document).ready(function($) {
$('#update-form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers/" + $('#update-id').attr("value"), //error is here
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
alert("updated");
},
});
});
});
view code:
i have table with list of teachers, and edit button for each teacher;
<button type="button" id="btn" value="{{ $teacher->id }}" class="btn btn-primary btn-block btn-sm edit-btn">Edit</button>
in form i have hidden field
<form method="post" id="update-form">
{{ method_field('PATCH') }}
<input type="hidden" id="update-id" value="{{$teacher->id}}" >
<div class="">
<label for="efirst">efirst</label>
<input type="text" class="form-control" name="efirst" id="update-efirst">
<textarea name="esecond" class="form-control" id="update-esecond" rows="6"></textarea>
</div>
<button type="submit" class="btn btn-success" id="update-submit">Update</button>
</form>
when i click on update, teacher ID's are being changed, one teacher id becomes another teacher id. is it correct way to pass teacher id from hidden field?
Write route name like below
At Web.php
Route::post("teacher/{id}/edit","YourController")->name("teacher.update");
At Blade File
$('#update-form').on('submit', function (e) {
e.preventDefault();
var id = $('#update-id').val(); // $('#update-id').attr("value") also ok
$.ajax({
method: "post",
url: "{{ route('teacher.update',id) }}",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
alert("updated");
},
});
});
Try this.
It will be work

CSRF Token missing or invalid. -> First form fails other CSRF Token work

So I have a site with multiple buttons. These buttons are inside forms and use this { CSRF }. However the first button won't work.
This is a snippet of how the HTML looks like.
<form method="post" id="post-form">
{% csrf_token %}
<button type="submit" name="startVm" class="btn btn-default btn-block d-none d-md-block">StartVM</button>
</form>
<form method="post" id="post-form">
{% csrf_token %}
<button type="submit" name="stopVm" class="btn btn-default btn-block d-none d-md-block">StopVM</button>
</form>
And this is the Ajax function that I use.
$('#post-form').on('submit', function(e){
e.preventDefault();
console.log("form submitted!") // sanity check
post();
});
// AJAX for posting
function post() {
console.log("create post is working!") // sanity check
$.ajax({
url : '', // the endpoint
type : 'post', // http method
data : {},
csrfmiddlewaretoken: '{{ csrf_token }}',
contentType: 'application/x-www-form-urlencoded',
processData: true,
// handle a successful response
success : function() {
alert("Thank you for your comment!");
console.log("success"); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
So as I said. The button StartVM won't work and it returns a 403 error.(Forbidden (CSRF token missing or incorrect.): /)
The second one however works without a problem.
This is the code in the view.py
def post (self, request):
if request.method == 'POST' and 'startVm' in request.POST:
print("startVM button")
return HttpResponse("{}",
content_type='application/json', status=204)
if request.method == 'POST' and 'stopVm' in request.POST:
print("stopVM button");
return HttpResponse("{}",
content_type='application/json', status=204)
return HttpResponse("{}",
content_type='application/json')
I am returning status 204 because e.preventDefault() won't work and it refreshes the whole site if I click on a button.
Firstly, ids should be unique, but you have id="post-form" on two separate forms.
You could do class="post-form" instead, and change your JS to use .post-form.
Or, for the template in your question, you could have a single <form> tag that contains both buttons.
Next, you need to include the CSRF token inside the form data.
data : {'csrfmiddlewaretoken': '{{ csrf_token }}'},
Alternatively, you could follow the suggestion in the docs, and add an X-CSRFToken header for ajax requests, then you don't need to include the token in the post data.

ajax form in CodeIgniter - sending generated form

I want to open a modal and get the content (the formular) form the controller. These steps work fine.
Now I have the formular inside the modal. How I can submit these formular and process it with the same controller function?
At the Moment I do the Ajax-Call in this way
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and received
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#disconnect_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
This is the form which will be generate from the controller by the call above
echo' <div class="modal-body">
<div id="modul_disc_infos">
<span class="module-headlines-title">'._l("modul_name").': <span id="disc_modulname">'._l('module_'.$result->folder.'_titel').'</span></span>
<span class="module-headlines-subtitle">'._l("modul_disconnect_deadline").': <span id="disc_enddate">'.$enddate.'</span></span>
</div>
<div id="modul_disc_check">
<div class="alert alert-danger" role="alert">'._l("modul_disconnect_disclaimer").'</div>
<hr>
<input type="checkbox" name="check_disclaimer" value="1"> '._l("modul_disconnect_disclaimer_check").'
<input type="hidden" name="modid" value="'.$this->input->post('modid').'">
<input type="hidden" name="formstep" value="1">
'.$errormsg.'
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">'._l('close').'</button>
<button type="button" class="btn btn-danger" id="submit_disconnect" >'._l('modul_disconnect_now').'</button>
</div>';
By the way - is there a better way to parse the values of the formular instead one by one like in my code "var modid = $(this).attr('modid');"?
I've solved that in this way that i do 2 different ajax call, starts with a click or submit on the form or a specific button. One call generate the form, one call handle the form. For me it works and its a little bit flexibel to use the same functions for different jobs.
//Formular for disconnection
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$('#ajax_modal_title').html('<?php echo _l('modul_disconnect'); ?>');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and recieved
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#ajax_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
//Handle the disconnection
$("#ajax_form").on("submit", function (event) {
event.preventDefault();
subform=$('input[name="subform"]').val();
$.ajax({
url: "<?php echo base_url() ?>admin/module/"+subform+"_form",
type: "POST",
data: $('#ajax_form').serialize(),
success: function(result){
$('.modal-ajax-content').html(result);
},
error: function(error){
// Show error message
alert('error');
}
});
});

Django: Uploading files with AJAX: Form says that the file input field is empty (or CSRF token missing or incorrect)

I'm trying to add a very simple file upload modal form in my Django app.
But, when I click the submit button, the form shows me an error message: "this field is required".
Everything renders correctly:
My main page loads correctly
When I click in the "Agregar archivo adjunto" button ("add attachment"), the modal form shows correctly, and all the fields are rendered as I want them to.
The issue comes when I click on the "Adjuntar archivo" ("attach file") button in my modal field: The form throws an error, as if I was trying to upload a "null" file!
Now... I forgot to add cache: false, contentType: false, processData: false to the $.ajax() call, but, when I add them, I get the following error: Forbidden (CSRF token missing or incorrect.). So... I don't know how to proceed!
I've already wrote (successfully) a modal form which helps me add notes (related) to my lead object (using this reference), and I'm trying to reproduce exactly the same process for a file upload modal dialog... but it doesn't work :(
Any help will be really appreciated.
By the way: I'm testing this using Chrome (no IE will be used!)
Here is my code:
models.py
def lead_dir_path(instance, filename):
"""
Files will be saved to: MEDIA_ROOT/leads/<int:pk>/<filename>
where <int:pk> is lead's primary key, and <filename> is just that.
Filename will be set to an UUID value.
"""
ext = filename.split('.')[-1]
filename = '%s.%s' % (uuid.uuid4(), ext)
return 'leads/%s/%s' % (instance.lead.pk, filename)
class ArchivosAdjuntosLead(models.Model):
lead = models.ForeignKey(Lead, on_delete=models.CASCADE)
descripcion = models.CharField(max_length=100)
archivo = models.FileField(upload_to=lead_dir_path)
views.py
def agregar_adjunto_json(request, pk):
"""
Adds a file to lead with id=pk
"""
context = {}
data = {}
lead = get_object_or_404(Lead, pk=pk)
context['lead'] = lead
if request.method == 'POST':
form = AdjuntarArchivoLeadForm_v2(request.POST, request.FILES)
if form.is_valid():
form.save();
data['form_is_valid'] = True
else:
data['form_is_valid'] = False
else:
form = AdjuntarArchivoLeadForm_v2()
form.initial = {'lead': lead}
context['form'] = form
data['html_form'] = render_to_string(
template_folder + 'partial_templates/partial_adjuntar_archivo.html',
context,
request = request,
)
return JsonResponse(data)
forms.py
class AdjuntarArchivoLeadForm_v2(forms.ModelForm):
class Meta():
model = ArchivosAdjuntosLead
fields = ['lead', 'descripcion', 'archivo']
widgets = {
'lead': forms.TextInput(attrs={'class':'form-control', 'style':'display:none;'}),
'descripcion': forms.TextInput(attrs={'class':'form-control'}),
'archivo': forms.FileInput(attrs={'class':'form-control'}),
}
partial_adjuntar_archivo.html
I use this partial template to create a modal form:
<form method="POST" enctype="multipart/form-data"
action="{% url 'leads:agregar_adjunto_v2' pk=lead.pk %}"
id="js_adjuntar_archivo_form">
{% csrf_token %}
<div class="modal-header">
<h4 class="modal-title">Adjuntar archivo</h4>
</div>
<div class="modal-body">
{{ form.as_p }}
<div class="modal-footer">
<button type="submit" class="btn btn-primary col-4">Adjuntar archivo</button>
<button type="button" class="btn btn-secondary col-4" data-dismiss="modal">Cancelar</button>
</div>
</div>
</form>
my_lead_page.html
This is the page where I create the modal form:
{% extends "leads/base.html" %}
{% load static %}
{% block contenido %}
<!-- Lots and lots of info -->
<button type="button" class="btn btn-sm btn-primary col-2" id="btn_agregar_adjunto">
Agregar archivo adjunto
</button>
{% endblock %}
{% block other_scripts %}
<script type="text/javascript" src="{% static 'js/leads/archivos_adjuntos.js'%}"></script>
{% endblock %}
archivos_adjuntos.js
$(function() {
$("#btn_agregar_adjunto").click(function() {
$.ajax({
url: 'adjuntar_archivo/',
type: 'get',
dataType: 'json',
beforeSend: function() {
$("#modal-form").modal("show");
},
success: function(data) {
$("#modal-form .modal-content").html(data.html_form);
}
});
});
$("#modal-form").on("submit", "#js_adjuntar_archivo_form", function() {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data) {
if(data.form_is_valid) {
alert("Archivo adjuntado");
} else {
$("#modal-form .modal-content").html(data.html_form);
}
}
});
return false;
});
});
Instead of form.serialize() try sending it with js formData() it should work.
Here is an example:
$("#modal-form").on("submit", "#js_adjuntar_archivo_form", function() {
$that = this;
var form = new FormData($(this)[0]);
$.ajax({
url:$that.attr("action"),
type:$that.attr("method"),
data:form,
processData: false,
contentType: false,
// rest of the code'''
});
return false;
});

Joomla sending Data (special Image) with Ajax (Formdata)

Using Joomla:
My problem is when I submit the button, ajax send an empty data array back to my client. Debbuging in the console shows me that datas in the header but the preview and response values are empty.
Here is my code (I am using a modal form from bootstrap).
HTML in my default script:
<form action="<?php echo JRoute::_('index.php?option=com_addproduct&view=addproducts'); ?>" method="post" name="modalMessageForm" id="modalMessageForm" enctype="multipart/form-data">
<input type="file" id="message-image-upload" accept="image/*" style="display:none;" name="message-image-upload">
<textarea class="form-control message-textarea" id="message-textarea" placeholder="Nachricht..." name="new-message" rows="4"></textarea>
<button type="button" id="button-close-message" class="btn btn-default btn-block btn-message-close" style="display:none; margin-top:5px;"><?=JText::_( 'COM_ADDPRODUCT_MODAL_MESSAGES_CLOSE')?></button>
</form>
JQuery / Ajax:
$(document).on("submit", "#modalMessageForm", function(e)
{
var form = $('#modalMessageForm').get(0);
e.preventDefault();
var formData = new FormData(form);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
$.ajax({
crossDomain: true,
type: "POST",
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
data: formData,
dataType: "json",
processData: false
})
.done(function(data, textStatus, jqXHR){
console.log('Message: '+data.new-message+' PicName: '+data.img);
})
});
Here my controller.php:
public function sendMessages()
{
JResponse::setHeader('Content-Type', 'application/json', true);
$app = JFactory::getApplication();
$input = $app->input;
$new-message = $input->getString('new-message', '', 'RAW');
$img = $_FILES['message-image-upload']["name"];
$img = JFile::makeSafe($img);
$results=array(
'new-message' => 'new-message',
'img' => $img
);
echo json_encode($results);
$app->close();
}
I got the datas / variables in the console log.
it is:
new-message: null,
img: null
trying to set contentType: false will give me an 500 error.
Thank you very much
That´s the info from my network
enter image description here
I figure something out.
It´s the URL in my ajax command.
When I am using a normal url like
url: 'upload.php'
that will work and then I can set the
contentType: false,
But this is not safety enought.
I just want to use this url
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
But then I got the error message that the view is not found. That´s very strange.

Resources