I can create, delete and display all but the update function will not work and does nothing. When I look the error in the console log it points to
jquery.min.js:2 PUT http://localhost:5000/shop/9 400 (BAD REQUEST)
send # jquery.min.js:2
ajax # jquery.min.js:2
updateServer # index.html:133
doUpdate # index.html:129
onclick # index.html:35
index.html:147
I cant see where I am going wrong. Am I missing something or is it within the update server code? This is the html code. A lot of the code for the update server is taken from other places within the html which works fine.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title> View Shopping List</title>
</head>
<body>
<h1>Shop</h1>
<div id="create-update" style="display:none">
<h2>create-edit</h2>
<table id="createUpdateForm">
<tr>
<td>ID</td>
<td><input type="hidden" name="ID" id="idInput"></td>
</tr>
<tr>
<td>Dept</td>
<td><input type="text" name="Dept"></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="Name"></td>
</tr>
<tr>
<td>Amount</td>
<td><input type="text" name="Amount"></td>
</tr>
<tr>
<td></td><td>
<button id="create-button" onclick="doCreate()">Create</button>
<button id="update-button" onclick="doUpdate()">update</button>
</td>
</tr>
</table>
</div>
<div id="display">
<h2>Shop</h2>
<button onClick="showCreate()">Create</button>
<table id="shopTable" class="table">
<tr>
<th>ID</th><th>Dept</th><th>Name</th><th>Amount</th><th></th><th></th>
</tr>
</table>
</div>
JS:
function showCreate() {
document.getElementById('display').style.display = "none"
document.getElementById('update-button').style.display = "none"
document.getElementById('create-button').style.display = "block"
document.getElementById('create-update').style.display = "block"
}
function showUpdate(thisElem) {
var rowElement = thisElem.parentNode.parentNode;
shop = readShopFromRow(rowElement)
populateForm(shop)
document.getElementById('display').style.display = "none"
document.getElementById('update-button').style.display = "block"
document.getElementById('create-button').style.display = "none"
document.getElementById('create-update').style.display = "block"
}
function readShopFromRow(rowElement) {
shop = {}
shop.ID = rowElement.getAttribute("ID");
shop.Dept = rowElement.cells[1].firstChild.textContent
shop.Name = rowElement.cells[2].firstChild.textContent
shop.Amount = rowElement.cells[3].firstChild.textContent
return shop
}
function populateForm(shop) {
var form = document.getElementById('createUpdateForm')
form.querySelector('input[name="ID"]').value = shop.ID
form.querySelector('input[name="ID"]').disabled = true
form.querySelector('input[name="Dept"]').value = shop.Dept
form.querySelector('input[name="Name"]').value = shop.Name
form.querySelector('input[name="Amount"]').value = shop.Amount
}
function clearForm() {
var form = document.getElementById('createUpdateForm')
form.querySelector('input[name="ID"]').value = ''
form.querySelector('input[name="ID"]').disabled = false
form.querySelector('input[name="Dept"]').value = ''
form.querySelector('input[name="Name"]').value = ''
form.querySelector('input[name="Amount"]').value = ''
}
function doCreate() {
console.log("in doCreate")
shop = getShopFromForm()
console.log(shop)
$.ajax({
url: "/shop",
data: JSON.stringify(shop),
method: "POST",
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result)
addShopToTable(shop)
showDisplay()
clearForm()
},
error: function(xhr, status, error) {
console.log("error" + error)
}
})
}
function doUpdate() {
shop = getShopFromForm()
updateServer(shop)
}
function updateServer(shop) {
$.ajax({
url: "/shop/" + shop.ID,
data: JSON.stringify(shop),
method: "PUT",
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result)
updateTableRow(shop)
showDisplay()
clearForm()
},
error: function(xhr, status, error) {
console.log("error" + error)
}
})
}
function doDelete(thisElem) {
var tableElement = document.getElementById('shopTable');
var rowElement = thisElem.parentNode.parentNode;
var index = rowElement.rowIndex;
ID = rowElement.getAttribute("id");
$.ajax({
url: "/shop/" + ID,
method: "DELETE",
dateType: "JSON",
success: function(result) {
tableElement.deleteRow(index);
},
error: function(xhr, status, error) {
console.log(error)
}
})
}
function updateTableRow(shop) {
rowElement = document.getElementById(shop.ID)
rowElement.cells[1].firstChild.textContent = shop.Dept
rowElement.cells[2].firstChild.textContent = shop.Name
rowElement.cells[3].firstChild.textContent = shop.Amount
//console.log("updating table")
}
function getShopFromForm() {
var form = document.getElementById('createUpdateForm')
var shop = {}
shop.ID = form.querySelector('input[name="ID"]').value
shop.Dept = form.querySelector('input[name="Dept"]').value
shop.Name = form.querySelector('input[name="Name"]').value
shop.Amount = form.querySelector('input[name="Amount"]').value
//console.log(shop)
return shop
}
function showDisplay() {
document.getElementById('display').style.display = "block"
document.getElementById('create-update').style.display = "none"
}
function populateTable() {
//ajax getAll
$.ajax({
url: 'http://127.0.0.1:5000/shop',
method: 'GET',
datatype: 'JSON',
success: function(results) {
for (shop of results) {
addShopToTable(shop)
}
},
error: function(xhr, status, error) {
console.log("error " + error + " code:" + status)
}
})
}
function addShopToTable(shop) {
//console.log("working so far")
tableElem = document.getElementById("shopTable")
rowElem = tableElem.insertRow(-1)
rowElem.setAttribute("ID", shop.ID)
cell1 = rowElem.insertCell(0)
cell1.innerHTML = shop.ID
cell2 = rowElem.insertCell(1)
cell2.innerHTML = shop.Dept
cell3 = rowElem.insertCell(2)
cell3.innerHTML = shop.Name
cell4 = rowElem.insertCell(3)
cell4.innerHTML = shop.Amount
cell5 = rowElem.insertCell(4)
cell5.innerHTML = '<button onclick="showUpdate(this)">Update</button>'
cell6 = rowElem.insertCell(5)
cell6.innerHTML = '<button onclick="doDelete(this)">delete</button>'
}
populateTable()
Server API
from flask import Flask, jsonify, request, abort, make_response, url_for, render_template, redirect #https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates Render template takes template and returns actual values
from flask_cors import CORS
from ShoppingDAO import ShoppingDAO
#from userinput import userinput
app = Flask(__name__,
static_url_path='',
static_folder='staticpages')
CORS (app)
#app.route('/')
def hello_world():
return 'Hello World'
# curl http://127.0.0.1:5000/
#app.route('/shop')
def getAllShop():
return jsonify(ShoppingDAO.getAllShop())
# curl http://127.0.0.1:5000/shop
# find By dept
#app.route('/shop/<string:Dept>', methods =['GET'])
def findShopByDept(Dept):
return jsonify(ShoppingDAO.findShopByDept(Dept))
# curl http://127.0.0.1:5000/shop/Spud
# find By ID
##app.route('/shop/<int:ID>')
#def findShopByID(ID):
# return jsonify(ShoppingDAO.findShopByID(ID))
# curl http://127.0.0.1:5000/shop/1
#app.route('/shop/<int:ID>', methods =['GET'])
def findShopByID(ID):
foundShop = ShoppingDAO.findShopByID(ID)
return jsonify(foundShop)
# Create
#app.route('/shop', methods=['POST'])
def createShop():
if not request.json:
abort(400)
if not 'ID' in request.json:
abort(400)
Shop={
"Dept": request.json['Dept'],
"Name":request.json['Name'],
"Amount":request.json['Amount']
}
values = (Shop['Dept'], Shop['Name'], Shop['Amount'])
newId = ShoppingDAO.createShop(values)
Shop['ID'] = newId
return jsonify(Shop)
# curl -X POST -d "{\"ID\":1, \"Dept\":\"Fresh\", \"Name\":\"Test\", \"Amount\": 5}" -H Content-Type:application/json http://127.0.0.1:5000/shop
#app.route('/shop/<int:ID>', methods=['PUT'])
def updateShop(ID):
foundShop = ShoppingDAO.findShopByID(ID)
if not foundShop:
abort(404)
if not request.json:
abort(400)
reqJson = request.json
if 'Amount' in reqJson and type(reqJson['Amount']) is not int:
abort(400)
if 'Dept' in reqJson:
foundShop['Dept'] = reqJson['Dept']
if 'Name' in reqJson:
foundShop['Name'] = reqJson['Name']
if 'Amount' in reqJson:
foundShop['Amount'] = reqJson['Amount']
values = (foundShop['Dept'],foundShop['Name'],foundShop['Amount'],foundShop['ID'])
ShoppingDAO.updateShop(values)
return jsonify(foundShop)
# curl -X PUT -d "{\"Dept\":\"Monday\", \"Name\":\"Mondy\", \"Amount\": 50}" -H Content-Type:application/json http://127.0.0.1:5000/shop/3
# Delete
#app.route('/shop/<int:ID>' , methods=['DELETE'])
def deleteShop(ID):
ShoppingDAO.deleteShop(ID)
return jsonify({"done":True})
# curl -X DELETE http://127.0.0.1:5000/shop/2
if __name__ == '__main__' :
app.run(debug= True)
The value property is a string, so the test type(reqJson['Amount']) is not int is succeeding and you're reporting an error.
Convert the amount to an integer when creating the JSON:
shop.Amount = parseInt(form.querySelector('input[name="Amount"]').value)
Related
I'm using DestroyAPIView with Javascript to delete the cart item in Django
While clicking on delete button it shows the following error on chrome console:
jquery.min.js:2 DELETE http://127.0.0.1:8000/showdata/2342; 404 (Not Found)
send # jquery.min.js:2
ajax # jquery.min.js:2
destoryCart # (index):46
onclick # (index):1
(index):55 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
and in vs code terminal showing:
Not Found: /showdata/2342;
and all my code goes here:
views.py
class CartDestroyAPIView(DestroyAPIView): # DeleteView
permission_classes = [IsAuthenticated] # Or anything else you want
authentication_classes = [SessionAuthentication] # Or anything else you want
serializer_class = productserializers
queryset = Cart.objects.all()
index.html
<script>
$(document).ready(function() {
$.ajax({
url: 'http://127.0.0.1:8000/showdata ',
dataType: 'JSON',
success: function(data){
for (var i = 0; i < data.length; i++)
{
var row =
$('<tr><td style="font-style:bold">'
+data[i].product.name+'</td><td style="font-style:bold">'
+data[i].product.price+'</td><td><a href='
+data[i].product.link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><button onclick="destoryCart('+data[i].product.id+')" type="button" class="btn btn-outline-danger">DELETE</button></td></tr>');
$("#tableProduct").append(row);
}
}
});
});
const destoryCart = (id) => {
let url = `http://127.0.0.1:8000/showdata/${id};`
$.ajax({
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRFToken', "{{ csrf_token }}");
},
url: url,
type: 'DELETE',
success: (data) => {
console.log("deleted!");
},
error: (err) => {
console.log(err);
}
});
};
</script>
urls.py
path('cart_destroy/<int:pk>', views.CartDestroyAPIView.as_view(), name ='cart_destroy'),
WHAT IS WRONG GOING WITH THIS CODE.
Change your URL in ajax call you have to put this URL in side your destoryCart()
let url = `http://127.0.0.1:8000/cart_destroy/${id};`
instead of this URL http://127.0.0.1:8000/showdata/${id};
UPDATE
get csrf_token like this i don't know if there is another way but as per official doc.
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
And you ajax call
const destoryCart = (id) => {
$.ajax({
type: 'POST',
url: "{% url 'cart_destroy' %}",
data: {
'product_id': id,
'csrfmiddlewaretoken': csrftoken,
},
success: function(success) {
console.log('success : '+success.responseText)
},
error: function(error) {
console.log('error : '+error.responseText)
},
});
}
and you have to update your URL also like this
path('cart_destroy/', views.CartDestroyView, name ='cart_destroy'),
add this in your views.py
def CartDestroyView(request):
if request.method == "POST":
product_id = request.POST['product_id']
Cart.objects.filter(id=product_id).delete()
return HttpResponse({'Success':"Deleted Successfully."})
I am trying to send the data from HTML form inside index.html to Java REST web service as a JSON data, using javascript and ajax. I tried whatever I found online so far, and still every time I get HTTP error 415.
I know the meaning of that error but can't figure out where I am wrong as I am not yet that much familiar with javascript.
Here is the code:
index.html
div style="text-align:center">
<form action="http://localhost/MyTaskTest/servicea" method="post"
id="test">
<fieldset>
<legend>Add to Your balance</legend>
<label for="amount">Money amount</label>
<input type="text" name="Amount" /> <br/>
<label for="currency">Select currency</label>
<select name="Currency">
<option value="eur">EUR</option>
</select>
<input type="submit" value="Add">
</fieldset>
</form>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
window.onload = function() {
var form = document.getElementById("test");
var output = document.getElementById("output");
form.onsubmit = function( e ) {
e.preventDefault();
var json = toJSONString( this );
console.log(json);
console.log("TEST");
$.ajax({
url: form.getAttribute( 'action' ),
headers: {
'Accept': 'application/json',
'Content-Type': "application/json; charset=utf-8"
},
type: 'POST',
data: json,
success: function(data) {
alert("data saved")
console.log("SUCCESS");
},
error: function() {
console.log("ERROR");
console.log(errorThrown);
}
})
};
}
})();
</script>
And here is the REST service:
#Path("/")
public class ServiceA {
#POST
#Path("/servicea")
//#Consumes(MediaType.APPLICATION_JSON)
public Response postRequest(String obj) {
String res = "hii";
return Response.status(200).entity(obj).build();
}
EDIT
I edited my code...now it is working. but why do I need to set argument to String instead of JSONObject and remove #Consumes? In console I get this data from the variable that I send in ajax: {"Amount":"213","Currency":"eur"} ... So I am sending JSON,but service only works if argument is String.
FINAL EDIT
I managed to fix the problem, I was missing dependency for jersey-json. Thanks :)
There are some errors in your code, try to debug it in chrome developer tools. I have made some changes and it is works
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
window.onload = function() {
var form = document.getElementById("test");
var output = document.getElementById("output");
form.onsubmit = function( e ) {
e.preventDefault();
var json = toJSONString( this );
console.log(json);
$.ajax({
url: form.getAttribute( 'action' ),
headers: {
'Accept': 'application/json',
'Content-Type': "application/json; charset=utf-8"
},
type: 'POST',
data: json,
success: function(data) {
alert("data saved")
},
error: function() {
console.log(errorThrown);
}
})
};
}
})();
try to add
dataType: "json",
contentType : "application/json"
to your $.ajax method
$.ajax({
url: $form.attr( 'action' ),
dataType: "json",
contentType : "application/json"
type: 'POST',
data: json,
success: function(data) {
alert("data saved")
},
error: function() {
console.log(errorThrown);
}
})
also You had ; in your url field in $.ajax method - so better to remove it ;)
Also its always better to check if service works corectly using for example PostMan so You are sure its not service side, I dont know what framework did You used, but You can also try to replace
public Response postRequest(JSONObject object) {
with
public Response postRequest(String object) {
to check if there is not a problem with mapping
I am using Jquery to implement autocomplete to my textbox, i have used Ajax call,but my ajax url is not working.
When i inspect it is showing this error -> POST http://localhost:51444/Searchoperation/searchvalues 404 (Not Found)
My HTML and Script code
<script>
$('#myInput').keyup(function (event)
{
var searchname = $('#myInput').val()
$('#myInput').autocomplete(
{
scroll: true,
selectFirst: false,
autoFocus: false,
source: function(request, response)
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Searchoperation/searchvalues",
data: "{'Searchname':'" + searchname + "'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
},
error: function (result) { }
});
},
select: function (event, ui) {
var vll = ui.item.val;
var sts = "no";
var url = 'search_app.aspx?prefix=' + searchname; // ur own conditions
$(location).attr('href', url);
}
})
})
</script>
<form autocomplete="off">
<div class="search-field" style="width:300px;">-->
<input id="myInput" type="text" name="myCountry" placeholder="SearchName" >
</div>
<input type="submit">
</form>
Code for fetching values from database
public List<string> searchvalues(string searchname)
{
try
{
List<string> result = new List<string>();
string connectionstring = #"Data Source=DESKTOP-LTV06QJ\SQLEXPRESS;Initial Catalog=Search;Integrated Security=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "connection_string";
conn.Open();
SqlCommand cmd = new SqlCommand("Sp_Search", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Emp_Name", searchname);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(string.Format("{0}/{1}", dr["Emp_id"], dr["Emp_Name"]));
}
conn.Close();
return result;
}
catch (Exception ex)
{
return null;
}
}
value entered in textbox is read but ajax call is not working.please help
try to use slash in the beginning of the path ("/Searchoperation/searchvalues"):
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Searchoperation/searchvalues",
data: "{'Searchname':'" + searchname + "'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
},
....
You are missing page extension(.ASPX). Replace the ajax attribute URL like below,
url: "Searchoperation.aspx/searchvalues"
Also, make sure you have added [WebMethod] before the searchvalues method.
I hope this will help.
Ajax sends data to controller. Method uses that data when button is clicked. My method has model.addatribute.Alert post null value. Why?
My Controller
#RequestMapping(value = "index", method = RequestMethod.POST)
#ResponseBody
public List<String> field(#RequestParam("tName") String name,
#RequestParam("dName") String dname, Model model) {
String tn = name;
String dn = dname;
List<String> coname = new ArrayList<>();
try {
Connection mycon2 = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "1996");
DatabaseMetaData metaData2 = mycon2.getMetaData();
ResultSet res4 = metaData2.getColumns(dn, null, tn, "%");
coname = new ArrayList<>();
while (res4.next()) {
String column_name = res4.getString("COLUMN_NAME");
coname.add(column_name);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return coname;
}
Index html
<div id="RightPanel" style="width: 200; height: 100%; float: right;">
<table class="table table-striped">
<input type='text' id='tablehead'/>
<tr>
<th>Column name</th>
</tr>
<tr th:each="name : ${cname}">
<td> th:text="${name}"</td>
</tr>
</table>
</div>
JavaScript in index html
<script th:inline="javascript">
function onclk(a, b) {
var search = {
"tName": a,
"dName": b
};
$.ajax({
type: "POST",
url: "http://localhost:8092/index",
data: search,
dataType: "json",
success: function (data) {
var modelAttributeValue = [[${coname}]];
alert(modelAttributeValue);
},
error: function () {
alert('got error');
}
});
}
</script>
Try this:
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
function onclk( a,b) {
var search = {
"tName" : a,
"dName" :b
}
$.ajax({
type: "POST",
url: "http://localhost:8092/index",
data: search,
dataType: "json",
success: function (data) {
var modelAttributeValue = [[${coname}]];
alert(modelAttributeValue); },
error: function(){
alert('got error');
}
});
/*]]>*/
</script>
I have used window.CSRF_TOKEN = "{{ csrf_token }}" inside script tag in restaurant_detail.html where my react page for posting review is rendered. I am getting an error, though. In my onSubmit function i have consoled to check if csrf token is passed or not and yes it is.
my axios code for posting review is
onSubmit(props){
console.log('csrf',CSRF_TOKEN);
axios({
method:'POST',
url:'/api/review/create/',
headers:{
'X-CSRF-Token':CSRF_TOKEN,
//'Access-Control-Allow-Origin':'*',
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data:{
review:props.review
}
})
.then(response => {
console.log('success');
})
.catch(error => {
throw("Error: ",error);
});
}
api/Views.py
class ReviewCreateAPIView(CreateAPIView):
queryset = Review.objects.all()
# permisssion_classes = [IsAuthenticated]
def get_serializer_class(self):
model_type = self.request.GET.get('type')
slug = self.request.GET.get('slug')
parent_id = self.request.GET.get('parent_id')
return create_review_serializer(model_type=model_type, slug=slug, parent_id=parent_id, reviewer=self.request.user)
serializers.py
def create_review_serializer(model_type='restaurant',slug=None, parent_id=None, reviewer=None):
class ReviewCreateSerializer(ModelSerializer):
class Meta:
model = Review
fields = ('id','review','created',)
def __init__(self, *args, **kwargs):
self.model_type = model_type
self.slug = slug
self.parent_obj = None
if parent_id:
parent_qs = Review.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
self.parent_obj = parent_qs.first()
return super(ReviewCreateSerializer, self).__init__(*args, **kwargs)
def validate(self, data):
model_type = self.model_type
model_qs = ContentType.objects.filter(model=model_type)
if not model_qs.exists() or model_qs.count() != 1:
raise ValidationError('This is not a valid content type')
SomeModel = model_qs.first().model_class()
obj_qs = SomeModel.objects.filter(slug=self.slug) # Restaurant.objects.filter(slug=self.slug)
if not obj_qs.exists() or obj_qs.count() != 1:
raise ValidationError('This is not a slug for this content type')
return data
def create(self, validated_data):
review = validated_data.get('review')
print('review',review)
if reviewer:
main_reviewer = reviewer
else:
main_reviewer = User.objects.all().first()
model_type = self.model_type
slug = self.slug
parent_obj = self.parent_obj
review = Review.objects.create_for_model_type(model_type, slug, review, main_reviewer, parent_obj=parent_obj)
return review
return ReviewCreateSerializer
urls.py
url(r'^create/$', ReviewCreateAPIView.as_view(), name="reviewcreateapiview"),
restaurant_detail.html
<div id="app"></div>
<script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>
How can i resolve this?
You have done a simple error. There is a typo. Do replace
'X-CSRF-Token'
to
'X-CSRFToken'
if you have code correctly, then it should post your data.
I'm not familiar with axios,but I solved a similar problem use the blow code with JQuery:
$.ajaxSetup({
data : {
csrfmiddlewaretoken : '{{ csrf_token }}'
},
});
you have to set the header in ajax call with cookie values.
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});