Django version 1.11.1
I have a form on my template, wanna use ajax to post it which can only change the form, my form code like:
<form action="" class="poster" id="posterForm">
{% csrf_token %}
<input type="file" accept="image/png,image/gif,image/jpeg" id="img_input" class="file_btn">
<input type="button" class="file_front_btn" value="选择图片" name="image">
<input type="text" name="title" id="title" class="title_area" placeholder="标题(不超过20字):">
<span class="img_root">已选图片:<span id="img_root" class="hidden">无</span></span>
<textarea name="content" id="content" name="content" class="content_area" placeholder="输入内容(不超过2000字):"></textarea>
<div id="title_error"></div>
<div id="content_error"></div>
<input type="button" class="submit" id="submitBtn" value="发布">
<div id="img_error"></div>
</form>
And my jQuery:
$(function(){
$('#submitBtn').on('click', function(){
$.ajax({
cache: false,
type: "POST",
url:"{% url 'community:poster' %}",
data:$('#posterForm').serialize(),
async: true,
success: function(data) {
if(data.status == 'success'){
$('#posterForm')[0].reset();
alert("发布成功")
}else if(data.status == 'fail'){
$('#img_error').html(data.msg)
}
},
});
});
})
And my views is:
class PosterView(View):
def post(self, request):
poster_form = PostForm(request.POST)
if poster_form.is_valid():
poster = poster_form.save(commit=True)
return HttpResponse("{'status':'success'}", content_type='application/json')
else:
return HttpResponse("{'status':'fail', 'msg':{0}}".format(poster_form.errors), content_type='application/json')
I use a ModelForm to commit the form, the forms is:
class PostForm(forms.ModelForm):
class Meta:
model = Posts
fields = ['image', 'title', 'content']
urls:
urlpatterns =[
url(r'^allpost/$', AllPosts.as_view(), name='allpost'),
url(r'^poster/$', PosterView.as_view(), name='poster'),
]
I can't see where the problem is, but when I click the submit button, nothing happened, no fail status.
Related
I'm trying to submit a form with ajax but I'm getting an error The POST method is not supported for this route. Supported methods: GET, HEAD. I have seen a lot of questions and answers on Stackoverflow and other sources but didn't get a solution, how can I fix this?
Blade file
<form method="POST" enctype="multipart/form-data">
<input type="hidden" value="{{csrf_token()}}" id="token"/>
<div class="form-group" >
<label for="title">Title</label>
<input type="text" name="title" >
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" name="description">
</div>
<button type='submit' id="btn" >submit
</form>
Javascript
<script>
$(document).ready(function(){
$("#btn").click(function(event){
event.preventDefault();
var url = '{{ route('review.store') }}';
var form = $('form')[0];
var formData = new FormData(form);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
data: formData,
type: 'POST',
cache: false,
contentType: false,
processData: false,
success:function(data){
if($.isEmptyObject(data.error)){
$("#msg").html("successfull");
$("#msg").fadeOut(3000);
}
}
});
});
});
</script>
Route
Route::post('review', 'ProductReviewController#store')->name('review.store');
You cannot use single quote ' inside '' in javascript. Enclosed your data in double quotes ""
Change
var url = '{{ route('review.store') }}';
to
var url = "{{ route('review.store') }}";
I want to submit a form to my Django back end using an AJAX post. I have multiple forms on the page but only want the one the user submits to be the one that sends.
The form is held in a modal:
<div class="modal-body">
<div class='content-section'>
<form method="POST" id="form{{ prod.id }}" class="showform" value="{{ prod.id }}" >
<input type="hidden" value="{{ prod.id }}" name="prodid">
{% csrf_token %}
<fieldset class='form-group'>
{{ form|crispy}}
</fieldset>
</form>
</div>
</div>
<div class="modal-footer">
<div class='form-group'>
<button class="btn btn-outline-info submit-form" value={{prod.id}} form="form{{ prod.id }}"
>Save
To Profile</button>
</div>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
When the submit button is pressed, it triggers the following AJAX :
$(document).on('click', '.submit-form', function () {
var thisButton = $(this)[0]
var prodID = $(this).val();
var form = $("form" + prodID);
$.ajax({
type: 'post',
headers:{
"X-CSRFToken": '{{ csrf_token }}'
},
url: '/ajax/validate_showadd/',
dataType: 'json',
contentType: 'json',
data: {
'form': form.serialize(),
"prodID":prodID,
},
success: function (data) {
console.log("sent")
},
error: function(data) {
console.log("error")
}
});
return false;
});
However, within Django whenever I try access any of these values it just returns 'None' and the QueryDict for the POST request is empty.
Thank you
I am pretty new to Ajax. i am trying to catch all the concepts.I am trying to submit a form through ajax. here's my code
views.py:
def ajax_test1(request):
if request.POST:
form = ModelForm(request.POST)
if form.is_valid():
form.save()
print request.POST.get('name')
x = request.POST.get('name')
if request.is_ajax():
response_dict = {}
response_dict.update({'server_response':x})
return HttpResponse(json.dumps(response_dict),content_type='application/json')
else:
return HttpResponse('not ok')
else:
form = ModelForm()
return render(request,'test1.html',{'form':form})
Jquery:
$(document).ready(function(){
$('#button').click(function{
var input_id = $('#id_name').val();
$.ajax({
type:'POST',
url:'/test1/',
datatype:'json',
data:{name:input_id},
success: function(json){
$('result').append(json.server_response);
},
headers:{'X-CSRFToken':csrf_token},
error: function(xhr,errmsg,err){
alert('Something worng');
}
});
});
});
Html:
<form action="" method="POST" accept-charset="utf-8">
{% csrf_token %}
{{ form }}
<p><input id="button" type="submit" value="Continue →"></p>
</form>
<div id="result">
</div>
<div id="result1">
</div>
The above code return 200 Response but data is not saving,and it return ServerResponse:Undefined
I have a small popbox window which users are supposed to use to send a message to another user. After clicking the send button I send the data to views.py in my flask application.
At that point I would like the popbox to close and nothing else. Instead what happens is that I get a print out on my site with
{
"data": null
}
my ajax command is
<script type='text/javascript'>
$(".send_recommend").click(function() {
var data = $("form").serialize();
$.ajax({
url: "/send_recommend",
type: "GET",
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
data: { send_dummy_id: document.getElementById("send_dummy_id").value, data: data },
});
});
</script>
and the flask part of this looks like
#app.route('/send_recommend', methods=['GET', 'POST'])
def send_recommend():
if request.method == 'GET':
ret_data = {"data": request.args.get('data')}
#do something here
return jsonify(ret_data)
The html looks like
<div class='popbox' style="display: inline">
<button class="btn btn-primary open" href="#" data-id="{{ data['arxiv_id'] }}" role="button"><span class="glyphicon glyphicon-share"></span>Recommend this paper</button>
<div class='collapse_popbox'>
<div class='box'>
<div class='arrow'></div>
<div class='arrow-border'></div>
<form action="/send_recommend" method="GET" style="padding:10px;" align="right">
<p>
{{ form.From(size=30, readonly=true) }}
</p>
<p>
{{ form.To(size=30, placeholder='To') }}
</p>
<p>
{{ form.message(rows=3, cols=29, placeholder='Message') }}
</p>
<button class="btn btn-primary send_recommend">Send</button>
<button class="btn btn-default close1">Dismiss</button>
<input id="send_dummy_id" name="send_dummy_id" value="" type=hidden>
</form>
</div>
</div>
</div>
Basically my question is how can I prevent ajax from any feedback on the website? I used ajax because I do not want to reload the website after the form is submitted. Maybe ajax is the wrong tool?
thanks
fl
Prevent the default behavior on the item clicked like so:
<script type='text/javascript'>
$(".send_recommend").click(function(evt) {
evt.stopPropagation();
evt.preventDefault();
var data = $("form").serialize();
$.ajax({
url: "/send_recommend",
type: "GET",
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
data: { send_dummy_id: document.getElementById("send_dummy_id").value, data: data },
});
});
</script>
$(".send_recommend").click(function(е) {
e.preventDefault();
...
});
or just end the function with return false;
Just remove the return jsonify(ret_data) line form your send_recommend() route.
#app.route('/send_recommend', methods=['GET', 'POST'])
def send_recommend():
if request.method == 'GET':
ret_data = {"data": request.args.get('data')}
#do something here
Because you are returning the JSON data back to your template.
I have multiple forms and I want all of them to be processed by a single jquery script, of course I have php functions that work correctly, I tried them separately.
This is my script:
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
My form looks like this
<form id="contacto" name="contacto" method="post" onsubmit="proceso_form('contacto', 'cargando')">
<input type="text" name="name"class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
I think my problem is that I can't put my script in the onsubmit, but honestly I have no idea.
Your html must look like
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form(this, 'cargando')">
...
</form>
And inside the function:
function proceso_form(form, id_div_error){
var $form = $(form);
var url = "my_url.php?form="+$form.attr('id'); //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
By passing this to the function you passing the whole form reference.
Hope it will help.
First, it should be:
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
The return keyword there is important.
Next, data: $(this).serialize(), //ID form should be:
data: $('#'+type_form).serialize(), //ID form
So, your script should look like this:
<script type="text/javascript" src="/path/to/jquery.min.js"></script>
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
<input type="text" name="name" class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
<div id="cargando"></div>
<script>
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $('#'+type_form).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
</script>