I am trying to store the Ajax request in the cookies so I can load it without the Ajax call if user refreshes the page.
So, this works: this.successLoad(response);
But this: this.successLoad(Ext.util.Cookies.get('JSON'));
doesn't work even if I set the cookie JSON to be equal the response I get from the Ajax request in success area. I tried to encode into cookie then decode the cookie but that didn't help eiter.
Long story short, I want to have a check if browser has a JSON cookie, if it does, simply send in JSON into the this.successLoad to load the page, if doesn't (it means user visiting first time) then create JSON cookie and load the page normally first time. JSON cookie is not setting up properly.
Ext.Ajax.request({
url: '/Authorization',
method: 'POST',
useDefaultXhrHeader: false,
withCredentials: true,
jsonData: {
activationCode: "",
},
scope: this,
success: function (response) {
this.getView().unmask();
// Cookie Creation Here
Ext.util.Cookies.clear('JSON');
Ext.util.Cookies.set('JSON', res);
this.successLoad(response);
}
Normally, cookies are plain text files and they can only be string. You can't store objects in cookies. Hence you need to encode the object using Ext.encode(response) as follows:
Ext.util.Cookies.set('JSON',Ext.encode(response));
Also while retrieving, you need to decode it as follows:
this.successLoad(Ext.decode(Ext.util.Cookies.get('JSON')));
Hope it helps!
If you don't want to use Extjs cookie library, then you can use the following utility functions :
getCookie:function(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
},
setCookie:function(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
if(window.location.protocol=="https:")
{
document.cookie = cname + "=" + cvalue + ";" + expires + ";secure;path=/";
}
else
{
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
},
Place the code in some singleton to access name.Where cname is name for your cookie(string). cvalue is value for your cookie (string) and extdays if number to days you expect your cookie to expire (integer).
Related
I am trying to intercept all requests, before send, from an Extjs App, POST and GET and then manipulate the URL and add a new Header, Authorization: Bearer XYZ123.
I've this code:
Ext.data.Connection.override({
request: function (options) {
var me = this;
this.cors = true;
this.useDefaultHeader = false;
this.useDefaultXhrHeader = false;
options.headers = { "Authorization": "Bearer VAROIS1iOiJKV1QiLCJh" };
var separator = options.url.indexOf('/') == 0 ? "" : "/";
options.url = UrlAPIPrefix + separator + options.url;
return me.callOverridden(arguments);
}
});
But when i try to use it, the Header Authorization is not sent in both cases, GET and POST. Parameters are not sent when using POST. I am able to see params if debugging the code into Extjs files, but can't see it on chrome Request Headers, see image.
If any one knows how to do it, in one place, i will be glad if you can help me.
That's because Ext.Ajax - the singleton of Ext.data.Connection - is used for most requests in the framework and overriding the latter does not affect the former. This overriding behavior was changed in extjs 5 and is intended by Sencha.
Use what you need of this instead:
Ext.Ajax.setWithCredentials(true);
Ext.Ajax.on({
beforerequest: function(conn, options) {
options.headers = options.headers || {};
options.headers['Authorization'] = 'Bearer VAROIS1iOiJKV1QiLCJh';
},
requestexception: function(conn, response, options) {
Ext.Error.raise('...');
}
});
And don't hardcode the token into your javascript!!!
Instead of overriding the class, i created a bootstrap class to set up the ajax interceptor. Called Bootstrap.init() in Application.launch() method.
Ext.define('MyApp.Bootstrap', {
singleton : true,
init: function() {
Ext.Ajax.on({
beforerequest: function(conn, opts){
if(opts.url && Ext.String.startsWith(opts.url, '/')) {
return;
}
if(opts.url && !Ext.String.startsWith(opts.url, MyApp.Config.SERVER_CONTEXT)) {
opts.url = MyApp.Config.SERVER_CONTEXT + opts.url;
}
var clientId = MyApp.getApplication().clientId;
opts.headers = Ext.apply({'X-Client-Id': clientId}, opts.headers);
Ext.log('Sending Request to : ', opts.url);
}
});
}
});
I am using firefox addons sdk.
I have created a plugin and I wanted to send request out of it. I came across following code on Mozilla developer site.
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
Here I cannot get any option to pass credentials along with request. As long as it is possible I want to avoid passing credentials along with url e.g. http://username:password#example.com, because many time special characters in password creates issue. So how to pass credentials with this request.
var { encode, decode } = require("sdk/base64");
// use encode() to base64 encode your credentials
var encodedCredentials = encode(email + ':' + password);
var testRequest = FRequest({
url: url,
headers: {
'Authorization': 'Basic ' + encodedCredentials
},
onComplete: function(response){
addOnPanel.port.emit('event', response.json)
}
}).get();
I had a problem getting ajax post data from django backend, I don't know how to pass the value, please help.
In html I have simply this:
<form id="get_vulns_from_family">
<label for="family_content">Enter a family name to display the NVTs</label>
<input id="family_content" />
<input type="submit" value="search" />
</form>
In javascript I wrote this:
$(function() {
$("#get_vulns_from_family").submit(function(event) {
var family_text = $("#family_content").val();
var family_data = {"family": family_text};
$.ajax({
url: "/template_conf/get_vulns_from_family",
type: "POST",
data: family_data,
success: function(response) {
console.log(response);
},
error: function(response) {
console.log("failed!");
}
});
// prevent default posting of form
event.preventDefault();
});
});
In Django method corresponding to url /template_conf/get_vulns_from_family, I tried this:
def get_vuln_from_family(request):
family = request.POST['family']
# some other operations to get value for variable "json_data"
return HttpResponse(simplejson.dumps(json_data))
But django said: MultiValueDictKeyError: "Key 'family' not found in <QueryDict: {}>", which means the POST dictionary is empty.
Am I using the wrong way to get post data? If so what should I do? Thanks.
your url "/template_conf/get_vulns_from_family" is missing a trailing slash. django will typically redirect this to "/template_conf/get_vulns_from_family/", dropping the POST data
If your CSRF enabled then simple ajax post do not work. you will have to add the csrf token and set it to the ajax request header.
For Ajax POST request, you have to pass the CSRF token in as POST data with every POST request. For this reason, you must get CSRF token first. Since you have enabled CSRF protection so you will get the token from csrftoken cookie. The CSRF token cookie is named csrftoken by default. Acquiring the token is very straight forward and it can be achieved using the below code snippet.
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]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
!(/^(\/\/|http:|https:).*/.test(url));
}
$(function() {
$("#person_form_id").submit(function(event){
event.preventDefault();
$.ajax({
type:$(this).attr('method'),
url:"",
data:$(this).serialize(),
success: function(){
$('#message').html("<h2 style='color:green;'>Person Form Submitted!</h2>")
},
error: function(){
$('#message').html("<h2 style='color:red;'>Can't submit form</h2>")
}
});
return false;
});
});
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
// Send the token to same-origin, relative URLs only.
// Send the token only if the method warrants CSRF protection
// Using the CSRFToken value acquired earlier
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
I have this piece of AJAX that validates the login credentials by sending the username and password via GET method. I want to update this code to use POST method, but I don't know where to start or what to change.
The reason I'm doing this is the data that will be sent to another page will be big and GET doesn't send it all.
This is the code I have:
function createObject()
{
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var usr;
var psw;
function login()
{
usr = encodeURI(document.getElementById('username').value);
psw = encodeURI(document.getElementById('password').value);
http.open('get', 'login.php?user='+usr+'&psw='+psw);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply()
{
if(http.readyState == 4)
{
var response = http.responseText;
if(response == 0)
{
alert('Login failed! Verify user and password');
}
else
{
alert('Welcome ' + usr);
document.forms["doSubmit"].elements["usr"].name = "usr";
document.forms["doSubmit"].elements["usr"].value = usr;
document.forms["doSubmit"].elements["pwd"].name = "pwd";
document.forms["doSubmit"].elements["pwd"].value = psw;
document.forms["doSubmit"].action = location.pathname + "user/";
document.forms["doSubmit"].submit();
}
}
}
This code uses GET and send the parameters in the URL and waits for the reply. I want to send the parameters via POST due to size.
The data that will be sent is for a <textarea name='taData' id='taData'></textarea>
Change the line of code as described below:
From:
http.open('get', 'login.php?user='+usr+'&psw='+psw);
To:
http.open('post', 'login.php');
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.send('user=' + usr + '&psw=' + psw + '&tboxName=' + yourTextBoxValue);
More on the topic:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849(v=vs.85).aspx
I have a problem with using Django CSRF with Ajax. I get a 403 Forbidden. I have done all the CSRF things that I normally do with a non-ajax request, but I still have this problem. I'm thinking this has something to do with the javascript snippet at https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax.
$(document).ajaxSend(function(event, 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;
}
function sameOrigin(url)
{
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method)
{
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
if (!safeMethod(settings.type) && sameOrigin(settings.url))
{
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
I'm not currently using this snippet, mostly because I don't understand a word of it and I don't know how to incorporate it into my jquery ajax call:
function submit_search()
{
$.ajax({
data: {query: document.search_form.query.value},
datatype: 'json',
success: function(data, textStatus, XMLHttpRequest)
{
if (data)
{
if (check_authentication(data))
{
$("#results").html("");
var results = data[0];
var length = data[1];
for (var index = 0; index < results.length; ++index)
{
var result = results[index];
$("#results").append("<p><a href='/entities/" + result["id"] + "'>" + result["name"] +
"</a><br />" + result["description"] + "</p>");
}
}
else
{
offer_login();
}
}
},
type: 'POST',
url: '/ajax/search',
});
}
Does anyone know how I should go about adding this snippet to my code?
Also tried:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken",
$("#csrfmiddlewaretoken").val());
}
}
});
but this also does not seem to work, although I'm not sure whether I should be doing something for the bit about #csrfmiddlewaretoken in my form
Thanks
All you need to do is paste the code block in such a way that the code in it runs. If you have a global JS file, you should be able to just add that JavaScript to the end of said file, and it will fix the problem.
well, couple steps required as stated in https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
To summarize the tedious django doc, you will need to:
1. install jquery.cookie plugins
2. make sure crsf_token is passing around
for example, in your template, the form must contain the following hidden field
<input type="hidden" name="csrfmiddlewaretoken" value="{{csrf_token}}"/>
In your ajax request, you should so similar things like
csrf_token = $.cookie('csrftoken');
$.ajax({
url: '/url/',
type: 'POST',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
},
data: $('.form').serialize(), //assume you are submit a form
}).done(function(response){
console.log(response)
});
one small tricks that you might be missing is, your landing page(non-ajax) will need #csrf_protect decorator to set up cookie, if you don't do that, the cookie won't exists and the method will fail. If you don't want to do #csrf_protect decorator, you can always refer back to the doc and specifically setup the cookie. Either way will work.
Hope this helps.