XMLhttpRequest> PHP> XMLhttpRequest

I have another question. XMLhttpRequests is haunting me. Now everything is in the database, but I need this data to refresh my page when loading or reloading the page. XHR runs in a JavaScript file that runs PHP-Script. PHP-Script access to the MySQL database. But how to get the returned records back to my JavaScript to refresh the page. I can not understand.

First my synchronous XMLhttpRequest:

function retrieveRowsDB()
{
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari

     xmlhttp=new XMLHttpRequest();

  }
  else
  {// code for IE6, IE5
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.open("GET","retrieveRowData.php", false);
  xmlhttp.send(null);

  return xmlhttp.responseText;
}

Then my PHP Script:

<?php

 $con = mysql_connect("localhost","root","*************");
 if (!$con)
 {
   die('Could not connect: ' . mysql_error());
 }

 mysql_select_db("sadb", $con);

 $data="SELECT * FROM users ORDER BY rowdata ASC";

 if (!mysql_query($data,$con))
 {
  die('Error: ' . mysql_error());
 }
 else
 {
  $dbrecords = mysql_query($data,$con); 
 }

 $rowdata = mysql_fetch_array($dbrecords);

 return $rowdata;

        mysql_close($con);

?>

What am I missing here? Anyone got it?

+3
source share
3 answers

There is still not much technically wrong with your code - you just need to do something with it.

PHP return $rowdata; - . javascript, echo . , javascript JSON . json_encode.

, js, . .

ajax , jQuery, , , , .

+4

PHP return JavaScript. echo ( - , json_encode).

, - ajax, , ajax library.

+7

The task xmlhttp.responseText, it does not exist at that time, try adding this immediately before the return statement:

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            doSomething(xmlhttp.responseText);
        }
    }
}

Basically, you need to wait until the data is available, it takes time to request an HTTP and receive a response.

+2
source

Source: https://habr.com/ru/post/1750090/


All Articles