0

I want to display a form with a script I adapted from this question. The script is in a file I wrote called queries.js, and its purpose is to print the content of a php form called "dbMinAlert.php" in a div like this <div id="recentExits" name="recentExits"></div> located in my project's index, I tried invoking getNewData(); in my index.php file using this tag <body onLoad="getNewData()"> but it doesn't seem to do anything at all.

var data_array = '';  // this is a global variable

function getNewData() {
    $.ajax({
        url: "dbMinAlert.php",
    })
    .done(function(res) {
        data_array = res;  // the global variable is updated here and accessible elsewhere
        getNewDataSuccess();
    })
    .fail(function() {
        // handle errors here
    })
    .always(function() {
        // we've completed the call and updated the global variable, so set a timeout to make the call again
        setTimeout(getNewData, 2000);
    });
}

function getNewDataSuccess() {
    //console.log(data_array); 
    document.getElementById("recentExits").innerHTML=data_array;
}
getNewData();`

---This php code works and it actually does what I expect it to do. The real problem is the javascript, for all I care the next php form could print a "Hello world" message, but I want it displayed inside the div I placed in my index, without having to post a thing to dbMinAlert.php.

define("HOST", "localhost");
define("DBUSER", "root");
define("PASS", "password");
define("DB", "mydb");

// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);

$query = mysql_query("
    SELECT *
    FROM outputs, products
    WHERE products.idProduct=outputs.idProduct
    ORDER BY Date DESC, Time DESC limit 5
");

echo '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
    $date = date_create($data['Date']);
    $time = date_create($data['Time']);
    echo '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';
}
echo '</ul>';
Community
  • 1
  • 1
Alvaro Alday
  • 343
  • 3
  • 19

3 Answers3

0

You have to execute the function for the first time.

getNewData();

0

It could be the way you are returning the result from php. Instead of doing multiple echo, could you first assign your result in single php variable and finally do single echo.

$result = '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
$result = $result + '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';}

$result = $result + '</ul>';
echo  $result;
Tranquillity
  • 237
  • 2
  • 9
  • No, it's not like that, in my experience using ajax the form is printed as a whole inside the
    tags, that's how it's been like with all the ajax functions I have used regardless of how I printed the content inside my php file, that method always worked correctly for me.
    – Alvaro Alday Feb 29 '16 at 16:22
0

I found a solution in this question and my code ended up Like this. I just had to invoke the function in my index by typing <body onload="return getOutput();">

JavaScript

        //Min-Max Alerts
    // handles the click event for link 1, sends the query
    function getOutput() {
      getRequest(
          'dbMinAlert.php', // URL for the PHP file
           drawOutput,  // handle successful request
           drawError    // handle error
      );
      return false;
    }  
    // handles drawing an error message
    function drawError() {
        var container = document.getElementById('recentExits');
        container.innerHTML = 'Bummer: there was an error!';
    }
    // handles the response, adds the html
    function drawOutput(responseText) {
        var container = document.getElementById('recentExits');
        container.innerHTML = responseText;
    }
    // helper function for cross-browser request object
    function getRequest(url, success, error) {
        var req = false;
        try{
            // most browsers
            req = new XMLHttpRequest();
        } catch (e){
            // IE
            try{
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                // try an older version
                try{
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    return false;
                }
            }
        }
        if (!req) return false;
        if (typeof success != 'function') success = function () {};
        if (typeof error!= 'function') error = function () {};
        req.onreadystatechange = function(){
            if(req.readyState == 4) {
                return req.status === 200 ? 
                    success(req.responseText) : error(req.status);
            }
        }
        req.open("GET", url, true);
        req.send(null);
        return req;
    }
Community
  • 1
  • 1
Alvaro Alday
  • 343
  • 3
  • 19