Foro de elhacker.net

Programación => Desarrollo Web => Mensaje iniciado por: geshiro en 25 Abril 2017, 01:24 am



Título: long polling ajax no esta funcionando bien
Publicado por: geshiro en 25 Abril 2017, 01:24 am
lo hace este script es que cuando cambio algo en la base de datos automaticamente se refleja en el sitio solo que cuando agrego un elemento a la base de datos cada ves tengo que recargar la pagina como pudiera hacer para solucionar esto? otra cosa en mi timestamp en la consola de google chrome parece asi http://localhost/storelte/notify/pusher?timestamp=1493076211  pending pero al agregar el nuevo elemento no cambia el timestamp porq no lo hace automatico tengo que recargar para verlo no se que estoy haciendo mal en el ajax ,
Código
  1. $(function(doc, win, $) {
  2.    var has_focus = true;
  3.    var notification = win.Notification || win.mozNotification || win.webkitNotification;
  4.    var $badge = $("#notifications-badge");
  5.    var $list = $("#notifications-list");
  6.    var $button = $("#notifications-button");
  7.    URL_GET_NOTIFICATION = BASE_URL + 'notify/pusher';
  8.    URL_GET_NOTIFICATION_UPDATE = BASE_URL + 'notify/update';
  9.  
  10.    if ('undefined' === typeof notification) {
  11.        console.log('Web notification not supported');
  12.    } else {
  13.        notification.requestPermission(function(permission) {});
  14.    }
  15.  
  16.    function check_notifications(timestamp) {
  17.        $.ajax({
  18.            type: 'GET',
  19.            url: URL_GET_NOTIFICATION,
  20.            data: { timestamp : timestamp },
  21.            dataType: 'json',
  22.            async: true,
  23.            success: function (data) {
  24.                for (var i in data.notifications) {
  25.                    notify(data.notifications[i].message, data.notifications[i].type, data.notifications[i].timestamp);
  26.                }
  27.                check_notifications(data.timestamp);
  28.            }
  29.        });
  30.    }
  31.  
  32.     function notify(message, type, created_at) {
  33.        var type_txt = 'info';
  34.        var url = '#';
  35.        var icon = 'info-circle';
  36.  
  37.        if (type == 0) {
  38.            type_txt = 'success';
  39.            icon = 'check';
  40.        } else if (type == 1) {
  41.            type_txt = 'info';
  42.            icon = 'exclamation';
  43.        } else if (type == 2) {
  44.            type_txt = 'warning';
  45.            icon = 'exclamation-triangle';
  46.        } else if (type == 3 || type == 4) {
  47.            type_txt = 'danger';
  48.            icon = 'fire';
  49.        }
  50.  
  51.        $badge.show();
  52.        $badge.text(parseInt($badge.text()) + 1);
  53.  
  54.        $list.find(".item").eq(13).nextAll(".item").remove();
  55.        var item = '<li class="item text-' + type_txt + '"><a href="' + url + '"><span class="text-' + type_txt + '">' +
  56.            '<i class="fa fa-' + icon + ' fa-fw"></i> ' + message.substr(0, 22) + '</span>' +
  57.            '<span class="pull-right text-muted small" data-time="' + created_at + '">X</span></a></li>' +
  58.            '<li class="item divider"></li>';
  59.        $list.prepend(item);
  60.  
  61.        $('.dropdown.open .dropdown-toggle').dropdown('toggle');
  62.  
  63.        return true;
  64.    }
  65.  
  66.    $(win).on("blur", function () {
  67.        has_focus = false;
  68.    });
  69.  
  70.    $(win).on("focus", function () {
  71.        has_focus = true;
  72.    });
  73.  
  74.    $button.on("click", function () {
  75.        $badge.fadeOut(300, function () {
  76.            $badge.text(0);
  77.        });
  78.  
  79.        $list.find("span[data-time]").each(function (index) {
  80.            var $this = $(this);
  81.            $this.text(moment.unix($this.data('time')).fromNow());
  82.        });
  83.    });
  84.  
  85.    check_notifications();
  86. }(document, window, jQuery));
  87.  
  88. $('#notifications-button').on('click', function () {
  89.    $.ajax({
  90.        type: 'GET',
  91.        url: 'http://localhost/storelte/notify/update',
  92.        success: function(data){
  93.        }
  94.    });
  95. });


Título: Re: long polling ajax no esta funcionando bien
Publicado por: engel lex en 25 Abril 2017, 01:32 am
el ajax cada cuanto tiempo se llama?


Título: Re: long polling ajax no esta funcionando bien
Publicado por: geshiro en 25 Abril 2017, 01:36 am
lo dejo abierto en espera de un cambio en la base de datos y en google chrome me lo deja asi
 pusher?timestamp=1493077051   (pending)   xhr   jQuery-2.1.4.min.js:4   0 B   Pending


Título: Re: long polling ajax no esta funcionando bien
Publicado por: engel lex en 25 Abril 2017, 01:43 am
no veo el error, del todo, puedes colocar una captura de tu consola? para ver que peticiones hizo antes


Título: Re: long polling ajax no esta funcionando bien
Publicado por: geshiro en 25 Abril 2017, 01:50 am
asi se ve cuando queiro agregar un nuevo elemento queda igua si no recargo como arreglaria mi ajax https://drive.google.com/open?id=0B5jZAeoqf_UiVGJ5ZXk0UENucUE


Título: Re: long polling ajax no esta funcionando bien
Publicado por: engel lex en 25 Abril 2017, 01:57 am
el servidor te está dejando en visto XD

que back end tienes? un php normal?


Título: Re: long polling ajax no esta funcionando bien
Publicado por: geshiro en 25 Abril 2017, 01:59 am
en backend tengo php con codeigniter, lo que pasa es que cuando inserto una notificacion desde mysql deberia ser vista en la web sin recargar ese es el problema q no lo esta haciendo porq tengo q recargar

Código
  1. public function pusher(){
  2. $data = $this->session->userdata('log');
  3. $user_id = $data['id'];
  4. header('Content-Type: application/json');
  5. while (true) {
  6. $firstCall = false;
  7. if ($this->input->get('timestamp')) {
  8. $last_ajax_call = $this->input->get('timestamp');
  9. }else{
  10. $last_ajax_call = time();
  11.             $firstCall = true;
  12. }
  13.  
  14. $notificationsCount = $this->notification->checkForNotifications($user_id, $last_ajax_call);
  15. $newData = (int) $notificationsCount > 0 ? true : false;
  16. $notifications = [];
  17. if ($newData) {
  18. $dataSet = $this->notification->getNotifications($user_id, $last_ajax_call);
  19. foreach ($dataSet as $value) {
  20. $notifications[] = $value;
  21. $finalNotificationTime = $value['timestamp'];
  22. }
  23.  
  24. $result = array('notifications' => $notifications, 'timestamp' => $finalNotificationTime);
  25. $json = json_encode($result);
  26. echo $json;
  27. break;
  28. }else{
  29. if ($firstCall) {
  30. $dataSet = $this->notification->getUnreadNotifications($user_id);
  31. foreach ($dataSet as $value) {
  32. $notifications[] = $value;
  33. }
  34.  
  35. $result = array('notifications' => $notifications, 'timestamp' => $last_ajax_call);
  36. $json = json_encode($result);
  37. echo $json;
  38. break;
  39. }
  40.  
  41. sleep( 1 );
  42.            session_write_close();
  43.            continue;
  44. }
  45. }
  46. exit();
  47. }


Título: Re: long polling ajax no esta funcionando bien
Publicado por: engel lex en 25 Abril 2017, 02:17 am
set_time_limit(0)
while(true)
exit()
sleep(1)

que es eso geshiro!? eso solo se usa casi que para debug... (excepto time limit que se usa para largas data frame, y aquí no es el caso)

lo unico que te altó fue error_reporting(0)

no se para que tienes ese while ahí, para mi está pegado en ese while, cuantas veces se va a repetir ese get si nunca debería repetirse, si se manda data se mando y adiós! no es socket, es htttp


Título: Re: long polling ajax no esta funcionando bien
Publicado por: geshiro en 25 Abril 2017, 02:27 am
set_time_limit(0) Limitamos  el tiempo máximo de ejecución  para que el sleep solo de 1s
while(true) un ciclo infinito que en ves que estar pidiendo request cada 3s o 5s lo hize infinito con un estado de pending
exit() terminamos el ciclo infinito
sleep(1) delays de 1s

es lo mas cerca que pude hacer al websocket ya que short polling me iba a hacer request cada 3s o 5s para que lo hize long polling cuando se haga una alteracion a la base de datos , con un efecto similar al websocket pero es http

Código
  1. {"notifications":[{"user_id":"1","notification_id":"105","timestamp":"1493078569","id":"105","product_id":"4232","message":"1","type":"1","created_at":"1493078569","status":null}],"timestamp":1493080187}

y este json es lo que me regresa el ciclo


Título: Re: long polling ajax no esta funcionando bien
Publicado por: engel lex en 25 Abril 2017, 02:37 am
eeehm no... es http... ahí no hay socket... cada conexión cierra estado, cada script tiene su propia data estatica...

por eso se pega... a demás... aunque fuera socket, no estás dando salida a los datos... echo solo pasa la data a el buffer... y si te pones a vaciar buffer vas a crear caos...


Título: Re: long polling ajax no esta funcionando bien
Publicado por: geshiro en 25 Abril 2017, 02:39 am
asi es es similar al websocket no es un socket , solo como arreglaria el ajax para que no tenga que recargar para cuando inserto algo a la base de datos porque si me muestra l a notificacion pero tengo que recargar esa parte como la solucionaria?


Título: Re: long polling ajax no esta funcionando bien
Publicado por: geshiro en 25 Abril 2017, 02:42 am
entonces en el ajax como arreglaria para que no tenga q recargar cada ves q se inserta algo en la db el settimeout()


Título: Re: long polling ajax no esta funcionando bien
Publicado por: engel lex en 25 Abril 2017, 02:44 am
no intentas hacer socket XD llamas cada vez a tu php... el php hace echo y naturalmente termina XD

en resumen quita el while (deja el contenido de sus cochetes) y el exit()


a demás por la forma de funcionar php, si eso pudieras hacerlo, con unas 1000 personas llenas 4gb de ram o tal vez 8 XD


Título: Re: long polling ajax no esta funcionando bien
Publicado por: geshiro en 25 Abril 2017, 02:49 am
emm como es algo pequeño solo notificaciones de client - server y como maximo tendre 2 conexiones haci que no hay problema pero solo ocupo que no tenga que recargar la notificacion para q aparezca


Título: Re: long polling ajax no esta funcionando bien
Publicado por: engel lex en 25 Abril 2017, 02:53 am
solo elimina la linea 6, 43, 47 y 48

tu jscript está bien (excepto por el timeout que como no tienes podría hacerte un DoS, pero como espera la respuesta y son solo 2 no hay problema), el problema es php que te deja en visto, es decir, el acepta el paquete y te dice que ya te va a responder, pero como el script nunca termina... -> (http://cdn3.ticbeat.com/src/uploads/2016/09/twitter-incopora-doble-check-azul-810x501.png)