Django 403 Forbidden Error - ajax

When I try the ajax in same page to html it works. Like this;
<html>
<head>
...
</head>
<body>
....
<script>
$.ajax({
url: /test/,
method: 'POST',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: { name: a, surname: b},
dataType: 'json',
success: function (data) {
getList(data);
}
});
</script>
</body>
</html>
When I try the call same javascript as external. It doesn't work. Why?
<html>
<head>
...
</head>
<body>
....
<script src="{% static 'js/test.js' %}"></script>
</body>
</html>

Define the {{ csrf_token }} as a global variable in your HTML page in script tag as a global variable as such:-
var generated_csrf_token = "{{ csrf_token }}";
And then in your .js file call it,
headers: {'X-CSRFToken': generated_csrf_token},
But make sure you put AJAX call within the document ready func in $(document).ready(function () {***here***}
This way you can access it with name generated_csrf_token in any js file.
Hope this helps :-)

Related

Ajax does not work when it is in a js page in laravel

Hi all I am having a problem when trying to split this code into a js file from the laravel page: php
In laravel page
$(".importer").click(function(e) {
// Stops the form from reloading
var parent = $('#parentdoc').val();
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
}
});
let fichiers_upload = new FormData();
let TotalFichiers = $('#fichiers-upload')[0].files.length; //Total Images
let images = $('#fichiers-upload')[0];
for (let i = 0; i < TotalFichiers; i++) {
fichiers_upload.append('images' + i, images.files[i]);
}
fichiers_upload.append('TotalFichiers', TotalFichiers);
fichiers_upload.append('idf', parent);
$.ajax({
url: "{{route('upload')}}",
type: 'POST',
contentType: false,
processData: false,
data: fichiers_upload,
success: function(result) {
$('#fichiers-upload').val("");
}
});
});
This works fine in the laravel page but if I create a js page to separate it from the laravel page
doing
<link rel="stylesheet" href="{{ asset('admin/import.js')}}">
I get this error
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "/home/vol1_3/epizy.com/epiz_27528825/htdocs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
line: 369
message: "CSRF token mismatch." ```
First, the tag is wrong. This is for linking CSS:
<link rel="stylesheet" href="{{ asset('admin/import.js')}}">
What you want is a script element:
<script type="text/javascript" src="{{ asset('admin/import.js')}}"></script>
(I'm honestly surprised that even worked for you at all.)
More to the point of the error though, the literal string "{{ csrf_token() }}" is not the CSRF token. This is a placeholder which the server-side framework will replace with an actual value when rendering the page. But it doesn't do this for .js resources.
One approach could be to add that value to the page itself, perhaps somewhere in the <head> element:
<script type="text/javascript">
const csrf_token = "{{ csrf_token() }}";
</script>
As long as it's added before any other .js files are loaded, the window-level constant csrf_token would then be available to any of the other JavaScript code. Which you'd use in your AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': csrf_token
}
});
Alternatively, if you want you can just put the call to $.ajaxSetup itself in the page, after loading jQuery but before any of your AJAX calls, and then it can directly make use of the CSRF token placeholder. Either way works, it's a matter of personal preference.
Use Script tag instead of link tag to include your JS file:
<script src="{{ asset('admin/import.js')}}"></script>
Link tag is used to attach CSS files.
Try changing the token name to _token
headers: {
'_token': "{{ csrf_token() }}"
}
change :
<link rel="stylesheet" href="{{ asset('admin/import.js')}}">
to :
<script src="{{ asset('admin/import.js')}}"></script>

How to call a controller function when someone click on a check box in laravel 8

is there any way to call a controller function when someone click on a check box. Like There are 4 check box with each has a category so when a user click on particular category then it will hit an API that process the filter request from the backend. I searched on Google but there is option to change it to
But that I don't want. Do I have to use jquery or else?
As in the comment section you can achive this via JQuery/Javascript. I have added a simple example with JQuery for your reference. What I achive here is first catch all check un check events and then via Ajax I send a request to the server. So that controller function will get called. You can test this via network tab when you check or uncheck a checkbox.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Check the Status of Checkboxes</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
//Add CSRF token to headers
$.ajaxSetup({
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$('input[type="checkbox"]').click(function(){
const val = $(this).val()
if($(this).prop("checked") == true){
alert(val+' Checked and sending data to server')
$.ajax({
type: "POST",
url: "file", // Route
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( "Data: " + msg );
});
}else{
alert($(this).val()+' unchecked');
$.ajax({
type: "POST",
url: "file",
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( 'Record removed' );
});
}
});
});
</script>
</head>
<body>
<input value="A" type="checkbox"> A
<input value="B" type="checkbox"> B
<input value="C" type="checkbox"> C
</body>
</html>

Setting up QUnit tests for AJAX calls

I am attempting to use Q-Unit Testing for my code. I would like to run some tests against my AJAX queries to ensure they are running ok and returning what they should.
Is there anyway I could get guidance on the two ajax calls below.
The first AJAX savePgID() essentially takes in 2 numbers and then goes to the pagaAJAX.php page where a simple MySQL INSERT query runs to insert those 2 numbers into the DB.
The second AJAX getModuleData() call again goes to a PHP script where a SELECT query runs, which GETS data from the database and the AJAX just pushes the content to certain divs.
My 2 AJAX calls inside of
script.js:
function savePgID(moduleID, pageID){
$.ajax({
url: "pageAJAX.php",
method: "POST",
data: {moduleID:moduleID, pageID:pageID},
dataType: 'json', //ajax to expect JSON data type
});
}
function getModuleData(moduleID, pageID){
console.log
console.log(moduleID);
console.log(pageID);
$.ajax({
url: "moduleAJAX.php",
method: "POST",
data: { moduleID:moduleID, pageID:pageID },
dataType: 'json', //ajax to expect JSON data type
success: function(data){
//console.log(data);
$('#result').html(data.result);
$('#modContent').html(data.modContent);
$('#modTitle').html(data.modTitle);
$('#modID').html(data.modID);
$('#pgID').html(data.pgID);
$('#modProgress').html("Page " + data.pgID); // For footer of modal overlay
}
});
}
my test.html page:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Q-Unit Tests</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.10.0.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-2.10.0.js" integrity="sha256-X1fQXHSYGxa4V2bqkEAQW0DQGSxJrKveasahr959o28=" crossorigin="anonymous"></script>
<script src="script.js"></script>
</body>
</html>

Displaying Data from JSON using AJAX call

Here is my json file(list.js)
{
"loginid":"Wafiqa",
"password":"123"
}
Here is my html file(ajaxTest.html)
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery-ui.js"></script>
</head>
<body>
<p>Username:</p>
<div id="uname"></div>
<p>Password:</p>
<div id="pword"></div>
<script>
$.ajax({
type:"GET",
datatype:"json",
async:false,
url:'ref/list.js',
success:function(data){
alert(data.loginid);
},
error:function(jqXHR,textStatus){
errorHandling(textStatus);
}
});
</script>
</body>
</html>
What I want to do is. I want to display the user id and password from the json file in div id="uname" and div id="pword". How can I do that?
success:function(data){
var jsonObj = JSON.parse(data);
$('div#uname').text(jsonObj.loginid);
$('div#pword').text(jsonObj.password);
},
For all beginners, here are the answer for your reference
Username:
Password:
<script>
$.ajax({
type:"GET",
datatype:"json",
async:false,
url:'ref/list.json',
success:function(data){
alert("Welcome "+data.password+data.loginid);
console.log(data.password);
$('#uname').html(data.loginid);
$('#pword').html(data.password);
}
});
</script>
</body>
</html>

Ajax button click that triggers a php file / link

I want a simple button that when I click, it shows the content from a file file.php ( this file when triggered it shows a random number) and if it's clicked several times refreshes the content from file.php.
You can try something like this:
PHP File: file.php
<?php
//your php code for random number...
?>
HTML File:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input type="button" id="clkMe" value="Load File" />
<div id="response"></div>
<script>
$(document).ready(function(){
$("#clkMe").click(function(){
var dataString={};
$.ajax({
url:"file.php",
type: 'POST',
cache:false,
data: dataString,
beforeSend: function() {},
timeout:10000,
error: function() { },
success: function(response) {
$("#response").html(response);
alert(response);
}
});
});
});
</script>
</body>
</html>
I hope this is what you are asking.
Happy Coding!!!

Resources