Brian Brian - 3 months ago 18
Ajax Question

Pass a socket io connection to an ajax success function

I am trying to access a socket io connection within an ajax success function.

// Create socket connection
var socket = io.connect('http://localhost:81/');

// Ajax request gets auth token
$.ajax({
url: 'http://localhost:8000/foo',
xhrFields: {
withCredentials: true
},
success: function (result, textStatus, jqXHR) {
socket.on('connect', function () {
$('#rows').html(result);
socket.emit('message', result);
});
}
});


How do I do this? If I declare the connection within the success function it works fine

Answer

What you are showing looks confused. The connect event may have already happened before the ajax call completes so you would completely miss it.

If there is a legit reason to not want to insert the ajax results into the DOM until the socket has connected, then you can do it like this:

// Ajax request gets auth token
// start ajax call, save promise
var p = $.ajax({
    url: 'http://localhost:8000/foo',
    xhrFields: {
        withCredentials: true
    }
});

// Create socket connection
var socket = io.connect('http://localhost:81/');
socket.on('connect', function () {
    // when both socket is connected and ajax call is done, insert results into DOM
    p.then(function(results) {
        $('#rows').html(result);
        socket.emit(result);
    });
});