1

I am implementing a custom error reporting form for an application to allow users to report errors into the issue tracker (YouTrack) directly from the application.

function createIssue() {

    $.ajax({
        url: "http://example.myjetbrains.com/youtrack/rest/user/login",
        dataType: "json",
        type: "POST",
        data: {
            login: $("#username").val(),
            password: $("#password").val()
        }
    });

    $.ajax({
        url: "http://example.myjetbrains.com/youtrack/rest/issue",
        dataType: "json",
        type: "POST",
        data: {
            project: 'PROJECT_NAME',
            summary: $("#summary").val(),
            description: $("#description").val()
        },
        xhrFields: {
            withCredentials: true
        }
    }).done(function(data) {
        $("#result").show();
        $("#summary").val('');
        $("#description").val('');
    });
}

The first ajax request which is to log the user into the external system is something I only want to happen if the user is not already logged in. Since the cookie is set for the remote domain when a login session exists how I can first check whether I need to try and log the user in first?

If I attempt the first request when the user already has a session I get an error from the service which is why I want to perform this check first.

ProNotion
  • 3,662
  • 3
  • 21
  • 30
  • The session cookie doesn't contain any of the session information, it's just an ID that the server uses to look up the session data. So you'll need to perform an AJAX call to ask the server if the user is logged in. – Barmar Dec 14 '13 at 08:35
  • 2
    BTW, you should perform the second AJAX call in the `.done` function of the first one. Otherwise, you'll send the `issue` request before the `login` request completes. – Barmar Dec 14 '13 at 08:37
  • Why don't you just change the login script so it doesn't return an error if the user is already logged in, it just keeps them logged in. – Barmar Dec 14 '13 at 08:38
  • @Barmar Moving the AJAX call to the .done function was a good call and that worked well. I need to check the API to see if I can verify the login status so I don't even show the login fields unless they are required. Since you've answered my question in the comments I can't mark it as a solution, I can only vote it up! – ProNotion Dec 16 '13 at 09:23
  • I didn't think my comment was an answer. Moving the AJAX call only helps in the case when the user is not already logged in. If they're already logged in, the login script will report an error, and you need some way to prevent that, which requires either a new API or a change to the login script. – Barmar Dec 16 '13 at 18:06
  • Possible duplicate of [jQuery check if Cookie exists, if not create it](http://stackoverflow.com/questions/6362688/jquery-check-if-cookie-exists-if-not-create-it) – Paul Sweatte Nov 22 '15 at 05:50

0 Answers0