Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery $.post cross domain and credentials

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)

like image 268
Deproblemify Avatar asked Sep 24 '14 10:09

Deproblemify


1 Answers

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

like image 200
Spokey Avatar answered Sep 23 '22 13:09

Spokey