403 forbidden error during send JSON data with ajax - 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.

Related

jquery ajax without refersh data get laravel

my blade
jQuery('.tbody').trigger('click').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ route('artist_genre_page_ajax') }}",
dataType: 'json',
cache: false,
method: 'GET',
success: function(result){
$.each(result.genre,function(key,iteam){
$('tbody').append(
'<tr>\
<td>'+ iteam.id +'</td>\
<td>'+ iteam.genre_name +'</td>\
<td><div class="table-actions d-flex align-items-center gap-3 fs-6"><i class="bi bi-pencil-fill"></i><i class="bi bi-trash-fill"></i></div></td>\
</tr>'
);
});
console.log(result.genre);
}});
});
here i am save data using Ajax and i wont o without refresh page show data on same page how to fix this

Ajax not posting Select Option

I'm trying to get the value of the option in my template below called exampleid. I've followed several examples I found online, but nothing seems to work. My template below has the ajax and jquery to get the value but when I try to print it returns None. I've exhausted my resources and my professor doesn't seem to know, he's "looking into it".
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title ="accesslevelid" class="form-control" id="accesslevelid" onchange="accesslevelid" title="">
<option value="7"> Option 1</option>
<option value="5"> Option 2</option>
<option value = "3"> Option 3</option>
</select>
<script>
$(document).ready(function () {
$('#accesslevelid').on('change', function () {
var accesslevelid = $(this).val();
$.ajax({ url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
alert(result);
},
});
});
});
</script>
my view attempting to retrieve the value of the post.
exampleidpost = request.POST.get('accesslevelid', False)
print (exampleidpost)
My desired result is for the POST to return a 7,5, or 3.
You should add csrf token to you ajax request,
Try this way.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<select title="accesslevelid" class="form-control" id="accesslevelid" >
<option value="1"> Option1</option>
<option value="2"> Option2</option>
<option value="3"> Option3</option>
</select>
<script>
$(document).ready(function () {
$('#accesslevelid').on('change', function () {
var accesslevelid= $(this).val();
$.ajax({
url: "{% url 'submitted' %}",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {
accesslevelid: accesslevelid
},
type: 'POST',
success: function (result) {
alert(result);
},
});
});
});
</script>
And you no longer need a form.

Form validation in codeigniter when ajax used to form submit

Form submit is not happened in this scenario..
$.ajax({
type: "POST",
async: false,
url: base_url+"register/registration_val",
data: "register_first_name="+first_name,
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
In your view you can add this:
<script type="text/javascript">
var base_url = "<?php print base_url(); ?>";
</script>
Plus try to alert and see the value of final url in ajax i.e alert(url);
Try adding a id to the firstname input
<script type="text/javascript">
$(document).on('submit','#form-reg',function(){ // #form-reg is id on form open tag
$.ajax({
url: "<?php echo base_url('register/registration_val');?>",
type: 'POST',
data: {
firstname: $('#firstname').val(),
},
dataType: 'html', // I perfer to use json
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
}
});
});
</script>
I would use dataType: json much easier that way to get data from controller
You used data: "register_first_name="+first_name, it's not correct. Correction is data: {register_first_name:first_name},
base_url like this var base_url = <?php echo base_url(); ?>
So, Bellow final code :
<script type="text/javascript">
jQuery(document).ready(function ($) {
var base_url = <?php echo base_url(); ?>
$.ajax({
url: base_url+"register/registration_val", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {register_first_name:first_name}, // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
}).done(function (data) {
$('#inferiz').html(data);
}).fail(function (data) {
console.log('failed');
});
}(jQuery));
</script>
Please verify your view part that whether you provided id same as in ajax function.
view part:
<form id="form-reg">
<input name="firstname" id="firstname" type="text" required placeholder="Enter firstname " >
<span id="name_validation" class="text-danger"></span>
<button name="submit" id="submit_button" onClick="myFunction();" >submit</button>
</form>
Then correct the base url path which has to be given inside php tag.
function myFunction() {
$.ajax({
url: "<?php echo base_url();?>register/registration_val",
type: "POST",
data:'firstname='+$("#firstname").val(),
success: function(msg)
{
alert('done..!');
}
});
}

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>

Issues posting comment with ajax through django

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;
});
});

Resources