Why cannot use both ajax and server sent event?

Ajax: every time there is a click, an ajax request is sent, and the console will display the text sent by server.

“server sent event”: it sends text to console in random time

if I use only ajax, I received data from server. But if I use both approaches, I did not receive data from server in response to the ajax request, but still receive message in response to “server sent event”. I did not even receive a fail message from ajax request. Can someone explain this?

Client

var evtSource = new EventSource("config/addRemoveEvent.php");
evtSource.onmessage = function(e) {
  //var newElement = document.createElement("li");
  console.log("listening: "+ e.data);
  //newElement.innerHTML = "message: " + e.data;
  //eventList.appendChild(newElement);
}   




    var data = {'action':'Initiate brief calendar', 'selectedMonth': month, 'selectedYear': year};
    var $request = $.ajax({
    type: "GET",
    dataType: "text",
    url: "config/addRemoveEvent.php",
    data: data,
    beforeSend: function(){
        console.log('start sending request');

    }
});

$request.fail(function(){
    console.log('fail');

}); 
$request.done(function(data){
    // change bg color of the cells that contain events;
    console.log(data);

});

Server

header("Content-Type: text/event-streamnn");
date_default_timezone_set("America/New_York");

while (1) {

  if (!$counter) {
    echo 'data: This is a message at time ' . $curDate . "nn";
    $counter = rand(1, 3);
  }

  ob_flush();
  flush();
  sleep($counter);
}

// return the date has event in a given month 
if($_GET['action'] == "Initiate brief calendar"){
    echo 'hello';}


Source: ajax

Leave a Reply