16

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)

7
  • and the question is ??
    – iJade
    Sep 24, 2014 at 10:06
  • 1
    Duplicate: stackoverflow.com/questions/16689496/… Sep 24, 2014 at 10:07
  • @ZeeTee linking to a question that has no marked correct answer is mean :P
    – MoshMage
    Sep 24, 2014 at 10:15
  • Look at the first answer, it clearly shows the answer. Sep 24, 2014 at 10:22
  • @ZeeTee This is not a duplicate as for I want session credentials and the other thread wants basic authentication Sep 24, 2014 at 10:27

1 Answer 1

24

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

3
  • I already tried this, now it works though because I placed it at the end of the file and not at the beginning Sep 24, 2014 at 10:36
  • what about access to https requests, that require keys to access? Mar 7, 2022 at 11:25
  • @RicardoMota do you mean with a client certificate? I don't think there's a way to do that yet
    – Spokey
    Mar 23, 2022 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.