I have written a web application which uses lot's of $.post
calls with JQuery. Now I would like to send withCredentials: true
with it to keep a session alive, what looks like this in $.ajax
(and also works like this):
$.ajax({
type: 'post',
url: 'http://example.com/server/api.php',
crossDomain: true,
dataType: "json",
xhrFields: {
withCredentials: true
},
data: {
username : 'test',
password : 'test'
},
success: function (d) {
$('body').html(d.status);
}
});
This is because I would now like to upload the PHP files to my server and export the client side using Cordova. (withCredentials: true
is only included because of testing on my localhost server)
Can I pack this into the $.post
call or do I need to replace all calls? (I would write a new function which would look similar to $.post)
You can use jQuery.ajaxSetup() to set default options that each ajax request will use (including $.post
and $.get
)
$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
},
username: 'test',
password: 'test'
});
$.post('http://example.com/server/api.php', {
username: 'test',
password: 'test'
}, function (d) {
$('body').html(d.status);
}, 'json');
Also the warning regarding this API
Note: The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.
from jQuery documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With