I use a jQuery plugin named Redactor, which can send ajax requests (link to the code). My site has an ajax authentication using header. So, I need to set header of all ajax requests, sending via redactor.
How can I modify just this request of the website without modifying the source file?
P.S. I don't need to modify XmlHttpRequest globally. I want to modify it just for this chunk of code.
You can use ajaxSetup() ( https://api.jquery.com/jquery.ajaxsetup/ ). You can define default values for all ajax request in jQuery. So you can force the header to requests sent by Redactor.
See this question : How can I add a custom HTTP header to ajax request with js or jQuery?
If you want to add a header (or set of headers) to every request then
use the beforeSend hook with $.ajaxSetup():
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your custom header
$.ajax({ url: 'foo/bar' });
// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
Related
How can I set a custom field in POST header on submit a form?
It cannot be done - AFAIK.
However you may use for example jquery (although you can do it with plain javascript) to serialize the form and send (using AJAX) while adding your custom header.
Look at the jquery serialize which changes an HTML FORM into form-url-encoded values ready for POST.
UPDATE
My suggestion is to include either
a hidden form element
a query string parameter
Set a cookie value on the page, and then read it back server side.
You won't be able to set a specific header, but the value will be accessible in the headers section and not the content body.
From FormData documention:
XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
With an XMLHttpRequest you can set the custom headers and then do the POST.
In fact a better way to do it to save a cookie on the client side. Then the cookie is automatically sent with every page header for that particular domain.
In node-js, you can set up and use cookies with cookie-parser.
an example:
res.cookie('token', "xyz....", { httpOnly: true });
Now you can access this :
app.get('/',function(req, res){
var token = req.cookies.token
});
Note that httpOnly:true ensures that the cookie is usually not accessible manually or through javascript and only browser can access it.
If you want to send some headers or security tokens with a form post, and not through ajax, in most situation this can be considered a secure way. Although make sure that the data is sent over secure protocol /ssl if you are storing some sensitive user related info which is usually the case.
Here is what I did in pub/jade
extends layout
block content
script(src="/jquery/dist/jquery.js")
script.
function doThePost() {
var jqXHR = $.ajax({
type:'post'
, url:<blabla>
, headers: {
'x-custom1': 'blabla'
, 'x-custom2': 'blabla'
, 'content-type': 'application/json'
}
, data: {
'id': 123456, blabla
}
})
.done(function(data, status, req) { console.log("done", data, status, req); })
.fail(function(req, status, err) { console.log("fail", req, status, err); });
}
h1= title
button(onclick='doThePost()') Click
You could use $.ajax to avoid the natural behaviour of <form method="POST">.
You could, for example, add an event to the submission button and treat the POST request as AJAX.
If you are using JQuery with Form plugin, you can use:
$('#myForm').ajaxSubmit({
headers: {
"foo": "bar"
}
});
Source: https://stackoverflow.com/a/31955515/9469069
To add into every ajax request, I have answered it here:
https://stackoverflow.com/a/58964440/1909708
To add into particular ajax requests, this' how I implemented:
var token_value = $("meta[name='_csrf']").attr("content");
var token_header = $("meta[name='_csrf_header']").attr("content");
$.ajax("some-endpoint.do", {
method: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader(token_header, token_value);
},
data: {form_field: $("#form_field").val()},
success: doSomethingFunction,
dataType: "json"
});
You must add the meta elements in the JSP, e.g.
<html>
<head>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<meta name="_csrf" content="${_csrf.token}"/>
To add to a form submission (synchronous) request, I have answered it here:
https://stackoverflow.com/a/58965526/1909708
I simply want to know if the request coming in is a standard page load or if the request has come from an ajax request.
Basically, I would like to use the same controller for both my ajax and my normal loading of a page.
Currently I am using:
console.info(req.get('Content-Type')); //undefined.
Here is the node code I am using
getFixtures: function (req, res) {
var passData = {}
console.info(req.get('Content-Type'));
passData.params = req.params;
leagues(app).getLeagues(passData)
.then(filterBarFixtures)
.then(function () {
res.render('games', {
title: 'Fixtures and Results',
passData: passData
})
});
}
app.get('/fixtures/', controllers.getFixtures);
2 way of loading the same controller
Open a browser and navigate to /fixtures
or
$.ajax({
method: "GET",
url: "/fixtures"
})
You would need to either set a header in the client request to look for in the server, or perhaps a search/query parameter
However, as you are using jQuery you don't need to worry
jQuery $.ajax uses XMLHttpRequest, which sets X-Requested-With=XMLHttpRequest request header
Additionally, if the request is for JSON (using $.ajax with appropriate settings or $.getJSON), jQuery usually sets Accept:application/json, text/javascript, etc
note, I've said "usually" to cover my butt in case in some strange browser this doesn't happen :p
Your comment regarding
beforeSend: function(request) { request.setRequestHeader("ajax",true); }
Is probably the safest option, as that header is guaranteed to be present, so that's the header to look for on the server side.
Is there anyway we can navigate (via <a/> click) to a URL with additional header in the request ? here's my code :
i have an <a href="#" id="aUsers"/> tag, and then i handle the onClick() event via JQuery :
$('#aUsers').click(function () {
var spAuthData = sessionStorage.getItem('sp-auth-data');
window.location.href = '/users.html?sp-auth-data' = spAuthData;
});
I want to put the spAuthData value in the authorization header, so i can have a clean URL
As far as I know, there is no way to manipulate HTTP headers with a plain url.
You can use headers parameter of jQuery AJAX request if it is suitable in your situation. For example, you can update the contents of some divs with AJAX HTML response.
$.ajax({
url: '/users.html',
headers: { 'Authorization': spAuthData }
}).done(function()
{
});
Otherwise, it looks like you need to make some server-side changes.
But why don't you use cookies or something like this?
Authorization is used only by unauthorized users during authorization. In my opinion, sending this header on every request from the browser manually sounds bad. The best approach is to send this header once during authorization, create a user session and store it in cookies (as an access-token, forms ticket or whatever else).
There are a lot of answers all around the web how to prevent jQuery AJAX requests from being cached. This is not what I'm trying to do.
I need the AJAX request to be returned from the cache based on condition in my code. That is, when the request is issued during page load, it is completely ok to return cached response (in fact that is the intention). But when the user clicks a button, I need the same request to be refreshed from the server.
I know that I can do this by setting cache: false option in jQuery, but this will just request the data with a different URL thus not refreshing the response in the cache and during the next page load the request with cache: true will return the obsolete data.
I tried adding a Cache-Control header to the request but that does not have effect at least in IE10.
$.ajax({
url: Configuration.ApiRootUri + "Notifications",
type: "GET",
headers: { 'Cache-Control': refreshCache ? 'no-cache' : 'private' },
success: function(data) {}
});
Is it possible at all to force the browser to refresh a cached resource from script?
(note: rewritten after discussion in the comments)
A solution would be to store the response from the server in the localstorage and load it at page load if it does exists.
This avoid completely the request made to the server at start and act like a cache, but in the browser.
Here's a pseudo-algo example :
function loadRequest(){
Call Ajax request
On success, store the result in the localstorage, call updateHtml(result);
}
function updateHtml(data) {
Update the specific html (list, view, etc) with the data
}
$('#mybutton').on ('click', loadRequest);
$(function() {
Check if the data in the localstorage exists
if exists, call updateHtml(localstorage.value);
else call loadRequest
});
That's it!
How can I set a custom field in POST header on submit a form?
It cannot be done - AFAIK.
However you may use for example jquery (although you can do it with plain javascript) to serialize the form and send (using AJAX) while adding your custom header.
Look at the jquery serialize which changes an HTML FORM into form-url-encoded values ready for POST.
UPDATE
My suggestion is to include either
a hidden form element
a query string parameter
Set a cookie value on the page, and then read it back server side.
You won't be able to set a specific header, but the value will be accessible in the headers section and not the content body.
From FormData documention:
XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
With an XMLHttpRequest you can set the custom headers and then do the POST.
In fact a better way to do it to save a cookie on the client side. Then the cookie is automatically sent with every page header for that particular domain.
In node-js, you can set up and use cookies with cookie-parser.
an example:
res.cookie('token', "xyz....", { httpOnly: true });
Now you can access this :
app.get('/',function(req, res){
var token = req.cookies.token
});
Note that httpOnly:true ensures that the cookie is usually not accessible manually or through javascript and only browser can access it.
If you want to send some headers or security tokens with a form post, and not through ajax, in most situation this can be considered a secure way. Although make sure that the data is sent over secure protocol /ssl if you are storing some sensitive user related info which is usually the case.
Here is what I did in pub/jade
extends layout
block content
script(src="/jquery/dist/jquery.js")
script.
function doThePost() {
var jqXHR = $.ajax({
type:'post'
, url:<blabla>
, headers: {
'x-custom1': 'blabla'
, 'x-custom2': 'blabla'
, 'content-type': 'application/json'
}
, data: {
'id': 123456, blabla
}
})
.done(function(data, status, req) { console.log("done", data, status, req); })
.fail(function(req, status, err) { console.log("fail", req, status, err); });
}
h1= title
button(onclick='doThePost()') Click
You could use $.ajax to avoid the natural behaviour of <form method="POST">.
You could, for example, add an event to the submission button and treat the POST request as AJAX.
If you are using JQuery with Form plugin, you can use:
$('#myForm').ajaxSubmit({
headers: {
"foo": "bar"
}
});
Source: https://stackoverflow.com/a/31955515/9469069
To add into every ajax request, I have answered it here:
https://stackoverflow.com/a/58964440/1909708
To add into particular ajax requests, this' how I implemented:
var token_value = $("meta[name='_csrf']").attr("content");
var token_header = $("meta[name='_csrf_header']").attr("content");
$.ajax("some-endpoint.do", {
method: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader(token_header, token_value);
},
data: {form_field: $("#form_field").val()},
success: doSomethingFunction,
dataType: "json"
});
You must add the meta elements in the JSP, e.g.
<html>
<head>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<meta name="_csrf" content="${_csrf.token}"/>
To add to a form submission (synchronous) request, I have answered it here:
https://stackoverflow.com/a/58965526/1909708