Getting a CSRF 403. The console.log statements below confirm that I'm grabbing the token. I'm submitting the request to the same domain on my local server.
internal.csrfToken = $.cookie('csrftoken');
internal.csrfSafeMethod = function(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
console.log("ajaxSetup");
console.log(internal.csrfToken);
if (!internal.csrfSafeMethod(settings.type)) {
console.log("Settings type");
xhr.setRequestHeader("X-CSRFToken", internal.csrftoken);
}
}
});
external.submitPayment = function (app_id, charge_now_amount, stripe_plan_id) {
// Submit a payment to the server and handle any errors.
$.ajax({
url: URLS.postPayment,
type: 'POST',
data: {
'app_id': STRIPE_CONFIG.app.id,
'amount': charge_now_amount,
'stripe_plan_id': stripe_plan_id
},
dataType: 'json',
success: function(response) {
alert("Success!");
},
error: function(jqXHR, textStatus, errorThrown ) {
alert("Error!");
}
});
};
not sure if this will help you. I had a similar problem. And fixed it by making a beforeSend functions that's add the X-CSRFToken
$.ajax({
url: url,
data: JSON.stringify({'name': value }),
type: 'POST',
dataType: 'json',
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader('X-CSRFToken', $('input[name=csrfmiddlewaretoken]').val());
},
success: function(response) {
alert("Success!");
}
})
Related
is it possible to reload a Django template after an ajax call?
This is my code.
script.js
$('.test').click(function(){
var platform = $('#testModal').attr('test-attr');
$.ajax(
{
type:"POST",
url:"test",
headers: {
'X-CSRFToken': TOKEN
},
dataType: "json",
cache : false,
processData : false,
contentType : false,
data: string,
success: function(data) {
location.reload();
}
});
});
view.py
return render(request, "user_interface/index.html", {'my_var': 'abc', 'my_var_2': 'cde'})
I tried to use return HttpResponse(json.dump({'res': 'Ok', 'err': None}), content_type = "application/json") but when i reload the page it fails.
If I try to do this, I get this error:
Uncaught TypeError: Illegal invocation
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
},
success: function(data) {
console.log(data);
}
});
});
And if I try to do this, I get this error:
403: Forbidden
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
processData: false,
contentType: false,
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]'),
},
success: function(data) {
console.log(data);
}
});
});
# This is my views.py
def search(request):
return JsonResponse(data={
'test': 'test'
})
What could be the problem?
Your help is greatly appreciated. Thank you
I am so sorry that I bothered everyone.
$(document).on('input', '#search-inp', (e) => {
$.ajax({
type: 'POST',
url: '/search/',
dataType: 'json',
data: {
input: $('#search-inp').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
console.log(data);
}
});
});
I had done this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]')
But should do this: csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
So I have a snippet of code that will update a field value if the field has content, although if the field that I'm trying to update is null than the value won't update. Am I doing something wrong?
siteURL = _spPageContextInfo.webAbsoluteUrl;
var apiPath = _spPageContextInfo.webAbsoluteUrl +"/_api/lists/getbytitle('Training%20Copy')/items/getbyid(9)";
$.ajax({
url: apiPath,
type: "POST",
headers: {
Accept: "application/json;odata=verbose"
},
data: JSON.stringify
({
__metadata:
{
type: "SP.Data.Training_x0020_CopyItem"
},
Admin_x0020_Function: "Have content"
}),
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
async: false, success: function(data) {
console.log("Item updated successfully");
}, eror: function(data) {
console.log("An error occurred. Please try again.");
}
})
There are two headers parameters in your ajax request, it is not clear whether it will affect.
My test code for your reference:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
Update()
function Update(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Doc')/items(9)",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose",
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
data: JSON.stringify({__metadata:{'type':'SP.Data.DocItem'},test:'test'}),
/*where Title is column name and add your desired new data*/
success: function(data) {
console.log(data);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
})
</script>
I'm new with ember and I wanted to know if it was possible to push some information that I've got back from my server into the store in ember.
I've tried this :
$.ajax({
url: host,
type: 'POST',
data: data,
accepts: 'application/json',
success: function(data) {
login.reset();
console.log("DEBUG: Login Succeed");
model: function() {
this.store.push() {
id: data.session.user.id,
username: data.session.user.username
}
}
login.transitionTo('home');
},
error: function() {
login.reset();
login.set('loginFailed', true);
console.log("DEBUG: Login Failed");
}
});
But obviously I'm wrong, and I don't really know how to do it :/
thanks for your help !!
EDIT:
Here is the new working code. I just forgot a small thing... such as the name of the model..
$.ajax({
url: host,
type: 'POST',
data: data,
accepts: 'application/json',
success: function(data) {
login.reset();
console.log("DEBUG: Login Succeed");
login.store.push('user', {
id: data.session.user.id,
username: data.session.user.username,
firstname: data.session.user.firstname,
lastname: data.session.user.lastname,
email: data.session.user.email,
domainid: data.session.user.domain,
role: data.session.user.role,
status: data.session.user.status
});
login.transitionTo('home');
},
error: function() {
login.reset();
login.set('loginFailed', true);
console.log("DEBUG: Login Failed");
}
});
Hi i am new to sencha touch2. i have to consume external web service. i have written code as below in console it is giving error like this Uncaught TypeError: Cannot call method 'request' of undefined. what is the problem, please provide the solution. Thank you
Ext.util.JSONP.request({
url: 'http://localhost/SLS.BRND.Services/Service1.asmx/Helloworld',
params: {
method: 'Helloworld',
format: 'json',
callback: 'callback'
},
success: function(response) {
alert('Working!')
console.log(response);
},
failure: function(response) {
alert('Not working!')
console.log(response);
}
});
Add this:
requires: ['Ext.data.JsonP'],
Try using Ext.data.jsonP.request
Ext.data.JsonP.request({
url: 'http://localhost/SLS.BRND.Services/Service1.asmx/Helloworld',
params: {
method: 'Helloworld',
format: 'json',
callback: 'callback'
},
success: function(response) {
alert('Working!')
console.log(response);
},
failure: function(response) {
alert('Not working!')
console.log(response);
}
});
DEMO
Hope this helps
Try -
Ext.data.JsonP.request({
url: 'http://A-Valid-Domain/SLS.BRND.Services/Service1.asmx/Helloworld',
params: {
method: 'Helloworld',
format: 'json',
callback: 'callback'
},
success: function(response) {
alert('Working!')
console.log(response);
},
failure: function(response) {
alert('Not working!')
console.log(response);
}
});