Issues posting comment with ajax through django - ajax

I am relatively new to this, but I'm working through things. I want to get solid understanding of how things work.
That being said, I have been attempting to get Django to post comments with an ajax hook.
I thought I was close to accomplishing this but, nothing so far. I was able to write a view that would save a posted comment then redirect me to my main page. I want to be able to use ajax so that the comment would post in a facebook style.
def add_comment(request, pk):
if request.method == 'POST' and request.is_ajax():
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=True)
comment.save()
json = simplejson.dumps(comment, ensure_ascii=False)
return HttpResponse(json, mimetype='application/json')
return render_to_response(simplejson.dumps('{{ post.id }}', {'comment': comment,}), context_instance=RequestContext(request), mimetype='application/json')
This view is pretty rough right now. I don't have any calls to json but, read this might be the way to go.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
$(document).click(function()
{
$('#comment_form').submit(function()
{
var dataString = $('#comment_form').serialize();
$.ajax({
type: 'POST',
url: '{{ post.id }}',
data: dataString,
success: function(data){
$('{{ post.id }}').html(data);
},
});
return false;
});
});
</script>
<form action="" method="POST" id="comment_form">{% csrf_token %}
<div id="cform">
Name: {{ form.author }}
<p>{{ form.body|linebreaks }}</p>
</div>
<div id="submit"><input type="submit" value="Submit"></div>
</form>

Thanks for the response, next time I will definitely leave a more detailed post. My problem was in the jquery script. I was trying to pass dataString as form data to the view, when it was a DOM object not the actual form data. Here's the final working script.
$(document).ready(function() {
$('#comment_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url art.views.post %}',
data: $('#comment_form').serialize(),
dataType: 'json',
success: function() {
location.reload();
$('#comment_form').get(0).reset();
},
});
return false;
});
});

Related

Print automatically on form close

I have a button that prints something and it works well.
I would like to print automatically when the form is closed.
At the moment the form sends an email to my customers with order details (it works very well) but now I would like to print automatically without requiring the user to push a button.
Please help me. I am a beginner here.
Relevant code:
<a
href="#!"
target="_blank"
id="save-and-print"
type="submit"
title="Speichern & Drucken">
<i class="fa fa-print"></i>
</a>
<script type="text/javascript" src="/js/summernote.js?v=0.72"></script>
<script>
$( function() {
$('#save-and-print').on('click', function (e) {
e.preventDefault();
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
});
$.ajax({
type: "PATCH",
url: '/myOrders/replacement/' + '{{ $data->id }}',
data: $("form").serialize(),
dataType: 'json',
success: function (data) {
window.location.reload();
location.href = '{{ route('print', [$data->id, 'option' => 'advance']) }}';
},
error: function (data) {
$('body').pgNotification({
style: 'flip',
message: 'Error',
position: 'top-right',
type: 'danger',
timeout: 4000
})
},
});
</script>
If you want the same action to take place on the submit event of your form as what happens when your id="save-and-print" button is being pressed, you could do something like this:
function printSomething(event) {
var url = 'myOrders/replacement/' + '{{ $data->id }}';
}
const form = document.getElementById('form');
form.addEventListener('submit', printSomething);

ID received from post - send via ajax

I would like to read the post id from html and send it via AJAX to the controller. How can I get the post ID ($post->id) and transfer it via AJAX? Or is there a better solution to save the post seen by the user?
#foreach ($posts as $post)
<div id="post_container_{{$post->id}}" class="row waypoint">
</div>
#endforeach
This is my AJAX code:
$('.waypoint').waypoint(function() {
$.ajax({
url: '/posts/view',
type: "post",
data:
success: function(request){
console.log(request);
},
error: function(response){
console.log(response);
},
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}, {
offset: '100%'
});
Get the id from the focused waypoint.
let waypoint_id = this.getAttribute('id'); // something like 'post_container_1'
Get only the string after the _
let post_id = waypoint_id.split("_").pop(); // something like '1'
in ajax() function
data: {
post_id: post_id
}
You could add a data-id attribute like so:
#foreach ($posts as $post)
<div id="post_container_{{$post->id}}" data-id="{{$post->id}}" class="row waypoint">
</div>
#endforeach
And then access it using the attr()
$('.waypoint').waypoint(function() {
let post_id = $(this).attr('data-id'); //this specifies the particular post row in focus.
$.ajax({
url: '/posts/view',
type: "post",
data: {post_id: post_id}
//and so on.
});
}, {
offset: '100%'
});

token mismatching ajax in Laravel

$('#id').change(function(){
var a = $('#id_one').val();
var token = '<?php echo csrf_token(); ?>';
$.ajax({
url: "url",
type: 'POST',
data: {'id':a,'_token':token},
success: function(data)
{
// some code
}
});
})
This is my code.
Getting token mismatch error..!!
I have tried both of the following..
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<script type="text/javascript">
var _globalObj = {{ json_encode(array('_token'=> csrf_token())) }}
Can any one help ??
You can utilize your token from the blade template, just declare your session token in the blade file of your view under the script tag like this:
<script> var token = '{{ Session::token() }}'; </script>
and call the token in ajax, in your code it will be something like this:
$('#id').change(function(){
var a = $('#id_one').val();
$.ajax({
url: "url",
type: 'POST',
data: {'id':a,'_token':token},
success: function(data)
{
// some code
}
});
})
Possibly because the token field name should be _token and not token
Also If this javascript code in a separate javascript file then php function will not work.
Also if the data you are trying to send is of a form then you can do this
$('#id').change(function(){
var data = $("#form").serialize() ;
$.ajax({
url: "url",
type: 'POST',
data: data,
success: function(data)
{
// some code
}
});
})
where your form looks like
<form id="form">
<input type='hidden' value='{{ csrf_token() }}' name='_token'>
<input type="text" name='id'>
</form>
$.ajax({
url: someurl,
type: 'POST',
data : formData,
headers: {
"x-csrf-token": $("#token").data('id')
}
});
}
and in your html
<div id="token" data-id="{!! csrf_token() !!}"></div>

403 forbidden error during send JSON data with ajax

these are code snippet for sending json data with ajax.
you can show same code in the last postings.
I'm just follow the code.
But I got 403 error
jsonpost.html
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/test/jsontest/',
data: {
'fruit': selected,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(result) {
document.write(result)
}
});
});
});
</script>
</head>
<body>
<form>
{% csrf_token %}
{{ data }}
<br>
Select your favorite fruit:
<select id="mySelect">
<option value="apple" selected >Select fruit</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
</body>
</html>
urls.py
urlpatterns = patterns('',
url(r'^jsontest/$', views.JsonRead.as_view(), name='userTest'),
)
views.py
class JsonRead(View):
def get(self,request):
return render(request, 'MW_Etc/jsonpost.html')
def post(self,request):
print(request.body)
data = request.body
return HttpResponse(json.dumps(data))
After change the fruit value, I got the error.
How can I resolve this?
Any others good ways is good as well.
If you are using post method you have to send csrf token in the form,same has to be done in the case of ajax
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/test/jsontest/',
data: {
'fruit': selected,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function(result) {
document.write(result)
}
});
});
});
try like this,this worked for me.

ajax request to controller to update view in laravel

I can't find a working solution for this problem:
I want to update a part of my view without reloading it,
I have a form that collects the data to be passed to the controller,
the controller needs to get the data from the DB and spit out a JSON
to the view so that it can be filled with such data.
I tried to adapt this http://tutsnare.com/post-data-using-ajax-in-laravel-5/ but it's not working at all. The data collected is not reaching the controller.
My uderstanding is the javascript part in the view should listen to the click event and send a GET request to the controller, the controller checks if the data is sent through AJAX, gets the data from DB then returns the response in JSON form, the view is then updated.
Please, does anyone have a working example or can explain?
Simple working example using JQuery:
In you routes.php file:
Route::post('/postform', function () {
// here you should do whatever you need to do with posted data
return response()->json(['msg' => 'Success!','test' => Input::get('test')]);
});
and in your blade view file:
<form method="POST" action="{{ url('postform') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="text" name="test" value="" />
<input type="submit" value="Send" />
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$(document).ready(function()
{
var form = $('form');
form.submit(function(e){
e.preventDefault();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: form.serialize(),
success: function(data)
{
console.log(data);
if(data.msg){
alert( data.msg + ' You said: ' + data.test);
}
}
})
});
});
});
</script>
As you can see, most of the logic is done in JavaScript which has nothing to do with Laravel. So if that is not understandable for you, I'd recommend to look for jQuery ajax tutorials or rtfm :)
I have experienced submitting a modal form without reloading the entire page. I let the user add option to the dropdown and then repopulate the items on that dropdown without reloading the entire page after and item is added.
you can have custom route to your controller that handles the process and can be called by javascript and will return json
Route::get('/profiles/create/waterSource',function(){
$data = WaterSource::orderBy('description')->get();
return Response::json($data);
});
then the javascript
<script>
$(document).on('submit', '.myForm-waterSource', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
$.get('{{ url('profiles') }}/create/waterSource', function(data) {
console.log(data);
$.each(data, function(index,subCatObj){
if (!$('#waterSource option[value="'+subCatObj.id+'"]').length) {
$('#waterSource').append('<option value="'+subCatObj.id+'">'+subCatObj.description+'</option>');
}
});
$('#myModal-waterSource').modal('hide');
$('#modal-waterSource').val('');
});
}
});
e.preventDefault();
});
</script>
You can view the full tutorial at Creating new Dropdown Option Without Reloading the Page in Laravel 5

Resources