0

Completely new to /. Every tutorial seems to be outdated in one way or another. Spent about 30 hours already trying to come up with a simple insert/retrieve script. Please help! Once i see the code working its alot easier for me to fiddle with it understand the documentation.

Im getting the following error.

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

My index.php relevant data, the error is on the xmlhttp.open line.

disp_data();
function disp_data(){

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "update.php?status=disp",false);

This is my update.php relevant code. On the tutorial, it is supposed to load my data upon refresh, but its blank. I'm not sure why the tutorial sets it to false, when the documentation ive read at w3schools seems I should make it true, but neither work.

$status = $_GET["status"];

if ($status == "disp") {
  $link = mysqli_connect("localhost", "root", "");
  mysqli_select_db($link, "checkbox");

$res = mysqli_query($link, "SELECT * FROM table1");

my full index.php

<div id ="disp_data"></div>

<script src="jquery-3.2.1.min.js"></script>
<script type ="text/javascript">

(function() {
  var newXHR = null;

  function sendXHR(type, url, data, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
    newXHR.send(data);

    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response); // Callback function to process the response.
      }
    };
  }

  sendXHR("GET", "update.php?status=disp", null, function(response) {
    document.getElementById("disp_data").innerHTML=newXHR.responseText;
  });

})();

</script>

</body>

my full update.php file

$status = $_GET["status"];
if($status=="disp")
{
$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"checkbox");
$res = mysqli_query($link,"SELECT * FROM table1");

echo "<table>";
while($row = mysqli_fetch_array($res))
{
echo "<tr>";
echo "<td>";   echo $row["id"]; echo "</td>";
echo "<td>";  echo $row["name"];  echo "</td>";
echo "<td>";  echo $row["city"];  echo "</td>";

echo "</tr>";
}
echo "</table>";
}
born2gamble
  • 197
  • 7
  • 17

3 Answers3

2

You should use true in the async parameter.

Something like this: xmlhttp.open("GET", "update.php?status=disp", true);.

See XMLHttpRequest.open().

You could use this helper function to make XMLHttpRequest.

Works in all browsers, incluiding IE6.

var newXHR = null;

function sendXHR(type, url, data, callback) {
  newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
  newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
  newXHR.send(data);
  newXHR.onreadystatechange = function() {
    if (this.status === 200 && this.readyState === 4) {
      callback(this.response); // Callback function to process the response.
    }
  };
}

Usage:

sendXHR("GET", "update.php?status=disp", null, function(response) {
  console.log(response);
});

You could retrieve data by using this demo:

(function() {



  var newXHR = null;

  function sendXHR(type, url, data, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
    newXHR.send(data);
    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response); // Callback function to process the response.
      }
    };
  }


  // Example 1: Get data.
  var btnRequest = document.getElementById("btnRequest");
  btnRequest.onclick = function() {
    sendXHR("GET", "https://gist.githubusercontent.com/dannyjhonston/22851f9c21733973b2705b0b65443f90/raw/30cf99ceeb470a7ab6d2ffb51a78f1bb57f41ca3/data.txt", null, function(response) {
      document.getElementById("myDiv").innerHTML = response; // response contains the data from the server.
    });
  };


  // Example 2. Cancel a long request.
  var btnCancelRequest = document.getElementById("btnCancelRequest");
  btnCancelRequest.onclick = function() {
    newXHR.abort(); // You can use the newXHR variable to abort a XMLHttpRequest that is taking long time to response, with the .abort() method.
  };





})();
#myDiv {
  border: solid 1px #ccc;
  border-radius: 5px;
  margin: 20px;
  padding: 5px;
}
<button id="btnRequest" type="button">Request data</button>
<button id="btnCancelRequest" type="button">Cancel request</button>
<div id="myDiv">The new content will print here.</div>

It's good to know this:

XMLHttpRequest.response property returns the response's body. It can be of the type ArrayBuffer, Blob, Document, JavaScript object, or a DOMString, depending of the value of XMLHttpRequest.responseType property. Value of response is null if the request is not complete or was not successful. However, if the value of responseType was set to "text" or the empty string, response can contain the partial text response while the request is still in the loading state.

XMLHttpRequest.responseText property returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent. The responseText property will have the partial response as it arrives even before the request is complete. If responseType is set to anything other than the empty string or "text", accessing responseText will throw InvalidStateError exception.


Your code must be like this:

$status = $_GET["status"];
if($status=="disp")
{
    $link = mysqli_connect("localhost", "root", "");
    mysqli_select_db($link,"checkbox");
    $res = mysqli_query($link,"SELECT * FROM table1");

    $html = "<table>"; // Declare a variable to concat the html content.
    while($row = mysqli_fetch_array($res))
    {
        $html += "<tr><td>";
        $html += $row["id"];
        $html += "</td><td>";
        $html += $row["name"];
        $html += "</td><td>";
        $html += $row["city"];
        $html += "</td></tr>";
    }
    $html += "</table>";
    echo $html; // Prints the $html variable.
}

In you code you need to remove:

<script src="jquery-3.2.1.min.js"></script>

It's not necessary if you gonna use native .

0

try this way

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "update.php?status=disp",false);
xmlhttp.send();

use xmlhttp .send(); method for send a request to athore page

To avoid this warning, do not use false in perameter:

async: false
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
0

XMLHttpRequest? try the "new" Fetch API. See: Browser Support for Fetch.

Ok, it is not supported in IE. In my defense, IE 11 is the only version of IE in support, and if they have IE 11, they probably have Edge.

This is a very simple example:

fetch("example.com")
.then(
    function(response)
    {
        response.text()
        .then(
            function(result)
            {
                console.log(result);
            }
        );
    }
);

Of couse, you would change "example.com" to your url.

The following is a more elaborate example, showcasing different options such as headers, request methods, redirections, control credentials (do you want to send cookies and http auth?) and catch exceptions. I recommend to read the MDN article on Using Fetch for more details.

Note: you can pass GET parameters in the url as expected. For a POST request you have to add the member body to the initialization of the Request object.

var headers = new Headers();
headers.append('X-Requested-With', 'XMLHttpRequest'); // #lies
var request = new Request(
    "example.com",
    {
        method: "GET",
        headers: headers,
        mode: 'cors',
        credentials: 'same-origin',
        cache: 'default',
        redirect: 'follow'}
);
fetch(request)
.then(
    function(response)
    {
        // response status
        console.log('ok: ' + response.ok);
        console.log('status: ' + response.status); //e.g: 200
        // response headers
        console.log('X-Header: ' + response.headers.get('X-Header'));
        // response url (redirections)
        console.log(response.url);
        // body as text
        response.text()
        .then(
            function(result)
            {
                console.log(result);
            }
        );
    }
)
.catch(
    function(err)
    {
        console.log(err);
    }
);

Note: in the examples I use the method text to get the text of the body of the response. You may also use the method json that will get the body and parse it directly. There is also a blob method, which can be useful if the response is multimedia among other things.

Theraot
  • 31,890
  • 5
  • 57
  • 86
  • Thank you for this, I will try this out after I fully understanding the first method. Its alot easier for me to learn while tinkering with the code as I read tutorials/videos about it. – born2gamble Nov 16 '17 at 06:28
  • @born2gamble I found a polyfill that will make (most of it) work in IE: [window.fetch polyfill](https://github.com/github/fetch). It uses [XMLHttpRequest internally](https://github.com/github/fetch/blob/master/fetch.js#L425) which may as well serve as case study. – Theraot Nov 17 '17 at 02:28
  • Thank you I will check it out in depth soon – born2gamble Nov 17 '17 at 19:01