Вопрос:

How to update the client side javascript based on something on the server?

javascript php mysql

121 просмотра

1 ответ

40 Репутация автора

I've researched this, but it's hard to find something when you don't know the best way to do it or even how to begin. I don't have any code obviously, so i'll describe my issue and hopefully someone can point me to the correct way to solve this :

ok let's say I have a page with a javascript function called "myfunction1" that fires off every x seconds by using setinterval in js. What I want it to do is, (using AJAX perhaps?) when "myfunction1" is called, call a php script that will check something in the database. If a certain condition is TRUE, I want a specific function to be called in javascript on the client side. If FALSE, I want it to call a different function.

My intuition makes me think the way to do it is to have the ajax call the php checking script, then echo the proper javascript code based on if true or false. But how would I go about doing that? I know how to use ajax to change the .innerhtml of a tag, but can you use it in this way to rewrite inside a script tag?? My head's spinning, hope I made some sense and one of you can point me the right way

Автор: Rocks Источник Размещён: 24.04.2017 04:34

Ответы (1)


1 плюс

10473 Репутация автора

Решение

AJAX would probably be the simplest solution and can be used to evaluate returning script or you can manually validate/display the response from the XmlHttpRequest that the server processed.

For example when using jQuery.ajax You can change the dataType option to script. Otherwise you can manually program the validation in the success callback, like below, using JSON.

javascript (jQuery)

jQuery(function($) {
   'use strict';
   var element = $('#myElement');
   var ajax = null;
   var ajaxTimeout = 0;

   function myFunction1() {
       if (null !== ajax) {
          //prevent overlapping ajax requests
          ajax.abort();
          ajax = null;
       }
       ajax = $.ajax({
         url: '/response.php',
         method: 'post',
         dataType: 'json',
         success: function(data) {
            //parse the server side response
            if (data.result === true) {
               trueFunction(data);
            } else {
               falseFunction(data);
            }
            ajax = null;
         }
      });
   }

   //custom functions for true or false and setInterval.
   function trueFunction(data) {
      element.html('Success: ' + data.value);
   }

   function falseFunction(data) {
      element.html('Failed: ' + data.value);
   }

   ajaxTimeout = window.setInterval(myFunction1, 1000);
});

response.php

<?php 

header('Content-Type: application/json');
$date = new \DateTime;
echo json_encode((object) [
    'value' => 'Hello World ' . $date->format('Y-m-d h:i:s a'), 
    'result' => true
]);
exit;
Автор: fyrye Размещён: 24.04.2017 05:19
Вопросы из категории :
32x32