How to interactively get data from php script using javascript - javascript

I have this php script:
<?php
$arr = array(array("a","b"),array("c","d"));
qq($arr);
function qq($arr){
foreach($arr as $ar => $r){
//getting some work done
//sending the array $r (or values)to javascript
}
}
?>
Is it possible to get the value of 0 array using javascript before array 1.
what i get so far is this js from stackoverflow:
<script type="text/javascript">
function q(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://127.0.0.0.1/q.php");
xmlhttp.send(null);
xmlhttp.onreadystatechange = callbackFunction;
function callbackFunction(){
if (xmlhttp.readyState == 4){
xml = xmlhttp.responseText;
document.getElementById("q").value = xml;
}}}
</script>
but it's not doing what i want(i think i'm missing something).
my html:
<input type="submit" onclick="q();" />
<div id="q"></div>
<div id="q1"></div>
Is it possible to put array 0 value in div(id=q) and when array 1 is ready put it's value in div(id=q1)

The "normal" HTTP Requests via XMLHttpRequest() do not allow such behaviour in a single request.
You have the following options instead:
Server Send Events
upside
They are incredibly easy to build. Nothing really special is needed on the server. Just google for server sent events and you'll find some examples on how they work.
They go through proxys and firewalls just as well as any other http request, because it is a normal http request.
downside
Does not run on Internet Explorer (?)
May fail to update in realtime if a proxy somewhere buffers too much. However in this case it still works, it just misses the realtime communication
Websockets
upside
Works in all recent browsers. Enables you to do full duplex communication and gets everything right that you need.
downside
May or may not work through proxies depending on their configuration.
Special extensions are needed on the server
(Long-) polling
upside
Best compatibility (works even in older browsers, no issues with proxies or firewalls)
downside
Creates lots of overhead because it does create for each message a new http connection
You need to store intermediate results somewhere because the poll requests come in different threads to your application than your code generation mechanism.

can you try with
if (xmlhttp.readyState == 4){
xml = xmlhttp.responseText;
document.getElementById('q').innerHTML=xml;
}}}

Related

How to replace ajax with webrtc data channel

** JAVASCRIPT question **
I'm using regularly ajax via XMLHttpRequest. But in 1 case, I need 1 ajax call per seconds....
but long term wise and with growing number of simultaneous users, it could bloat easily...
I'm reading stuff about webRTC data channel and it seems interesting and promissing.
Here my working AJAX function as an example of how easy and there is a few lines of codes to communicate from the browser to the server and vice-versa
function xhrAJAX ( divID , param2 ) {
// random value for each call to avoid cache
var pcache = (Math.floor(Math.random() * 100000000) + 1);
// parameters
var params = "divID="+encodeURIComponent(divID)+"&param2="+encodeURIComponent(param2);
// setup XMLHttpRequest with pcache
var xhr = new XMLHttpRequest();
xhr.open("POST", "/file.php?pcache="+pcache, true);
// setup headers
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// prepare onready scripts
xhr.onreadystatechange = function(e) { if (xhr.readyState == 4) { $("#"+divID).html(e.currentTarget.responseText) ; } }
// send the ajax call
xhr.send(params);
}
How can I "transpose" or "convert" this ajax workflow into a webRTC data channel ? in order to avoid to setup a setInterval 1000...
Note: I mean how to replace the javascript portion of the code. PHP here is only to illustrate, I don't want to do a webRTC via PHP...
Is there a simple few lines of code way to push/receive data like this ajax function ?
the answer I'm looking for is more like a simple function to push and receive
(once the connection with STUN, ICE, TURN is established and working...)
If I need to include a javascript library like jquery or the equivalent for webRTC, I'm welcoming good and simple solution.
*** The main goal is this kind of scenario :
I have a webapp : users in desktop and users within webview in Android and IOS
right now I have this workflow => ajax every 3 seconds to "tell" the main database that the user is still active and using the browser (or the app)
But I'd like to replace with this kind : when the user uses the browser => do a webrtc data chata in background between the browser and the server
While reading on the web I think that webRTC is a better solution than websocket.
** I did a bit of search and found peerjs....
https://github.com/jmcker/Peer-to-Peer-Cue-System/blob/main/send.html
I'll do some testing, but in the meantime, if someone can trow ideas, it could be fun.
Cheers

From polling to long polling

So I have a script that uses basic polling to show the total amount of records in the database in real time
so nothing complicated so can any one give me an example of my code in a long polling structure. The reason why I ask this question because all the articles on google
search gives me examples in jQuery I cant seem to find a plain JavaScript example that makes sense in my situation. This is a .gif screenshot
of my code in action so you guys know what I mean in detail.
This is my basic polling example code that I need to convert or change into long polling.
index.php
<style>
#label{
margin: 0;
color: red;
font-weight: bold;
}
</style>
<script>
document.addEventListener('DOMContentLoaded',function(){
/**********************************************************************
Check for a new record amount in the data base
**********************************************************************/
function checkForNewRecords(){
var xhr= new XMLHttpRequest();
xhr.onreadystatechange= function(){
if(xhr.readyState == 4){
document.querySelector('#output').innerHTML= xhr.responseText;
}
}
xhr.open('POST','check-for-new-records.php');
xhr.send();
}
setInterval(function(){checkForNewRecords()},1000);
});
</script>
<p id='label'>Total records in the database in real time in basic polling</p>
<div id='output'></div>
check-for-new-records.php
<?php
$db_servername= 'localhost';
$db_username='jd';
$db_password= '1234';
$db_name= 'test';
$db_connect= new mysqli($db_servername,$db_username,$db_password,$db_name);
$db_query= "SELECT COUNT(id) AS id FROM example";
$db_result= $db_connect->query($db_query);
$db_row= $db_result->fetch_object();
$total_records= $db_row->id;
?>
<style>
#total-records{
margin-top: 0;
}
</style>
<p id='total-records'><?php echo $total_records; ?></p>
So how would you guys convert this into long polling and please don't suggest other methods or don't provide an answer that is not helpful i'm only interested in what i'm asking for and i'm pretty sure others are also interested in a plain JavaScript version as well and the reason why I say this is because I
been asking about this topic online for a long time and nobody seems interested in answering this or perhaps they think its too hard to answer this if so why is there so many jQuery examples about this topic and not based on plain JavaScript and not everyone likes to use libraries. I'm just saying I been unsatisfied about the unhelpful answers I been getting from this topic that is based on plain JavaScript, just a heads up.
You should never use setInterval use setTimeout instead.
If you use setTimeout then basic difference for polling and long polling is only where the delay happens. For polling the server will respond immediatly (even if no change happened) and the client will wait n seconds to send the next request. For long polling the server will wait with the respond until new data is available (or a timeout occurs) and the client will immediately send a new request when it gets a response.
There is absolutely no different in implementing it with XMLHttpRequest, fetch or jQuery, the only difference client side is the delay for the next request.
Polling:
function checkForNewRecords() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
document.querySelector('#output').innerHTML = xhr.responseText;
setTimeout(checkForNewRecords, 1000); // polling has the delay on the client
}
}
xhr.open('POST', 'check-for-new-records.php');
xhr.send();
}
checkForNewRecords()
Long-Polling:
function checkForNewRecords() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
document.querySelector('#output').innerHTML = xhr.responseText;
setTimeout(checkForNewRecords, 0);
// long-polling has the delay on the server
// the client initiates a new request immediatly after receiving the response.
}
}
xhr.open('POST', 'check-for-new-records.php');
xhr.send();
}
checkForNewRecords()
On the server side, on the other hand, you usually have to change a couple of things to make long polling work efficiently.
The important differences between polling and long polling that target optimizations, in how to tell the server when to send update informations, but thats completely independent form the method you use to request the data.

How to make JS wait until protocol execution finished

I have a custom URL protocol handler cgit:[...]
It launches up a background process which configures some stuff on the local machine. The protocol works fine, i'm launching it from JavaScript (currently using document.location = 'cgit:[...]'), but i actually want JavaScript to wait until the associated program exits.
So basically the steps i want JavaScript to do:
JavaScript does something
JavaScript launches cgit:[...]
Javascript waits until cgit:[...] exits
JavaScript does something else
Code:
function launchCgit(params)
{
showProgressBar();
document.location="cgit:"+params;
document.addEventListener( /* CGit-Program exited event */, hideProgressBar );
}
or:
function launchCgit(params)
{
showProgressBar();
// setLocationAndWait("cgit:"+params);
hideProgressBar();
}
Any ideas if this is possible?
Since this isn't really an expected use of window.location I would doubt that there's an easy way. My recommendation would be to use an AJAX request and have the c++ program send a response when it's done. That way, whatever code needs to run after the c++ program can be run when the request completes.
As i didn't find a suitable way to solve my problem using ajax requests or anything similar, i finally solved my problem using a kind-of-ugly workarround including XmlHttpRequest
For launching the protocol i'm still using document.location=cgit:[...]
I'm using a server side system including "lock-files" - that's like generic dummy files, with generated names for each request.
Once the user requests to open the custom protocol, such a file is being generated on the server specifically for that one protocol-opening-request.
I created a folder called "$locks" on the server where these files are being placed in. Once the protocol-associated program exits, the appropriate file is being deleted.
The website continuously checks if the file for a request still exists using XmlHttpRequest and fires a callback if it doesn't (example timout between tests: 1 sec).
The structure of the new files is the following:
lockThisRequest.php: It creates a file in the $locks directory based on the req url-parameter.
unlockThisRequest.php: It deletes a file in the $locks directory; again based on the req url-parameter.
The JavaScript part of it goes:
function launchCgit(params,callback)
{
var lock = /* Generate valid filename from params variable */;
// "Lock" that Request (means: telling the server that a request with this ID is now in use)
var locker = new XmlHttpRequest();
locker.open('GET', 'lockThisRequest.php?req='+lock, true)
locker.send(null);
function retry()
{
// Test if the lock-file still exists on the server
var req = new XmlHttpRequest();
req.open('GET', '$locks/'+lock, true);
req.onReadyStateChanged=function()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
// lock-file exists -> cgit has not exited yet
window.setTimeout(retry,1000);
}
else if (req.status == 404)
{
// lock-file not found -> request has been proceeded
callback();
}
}
}
req.send(null);
}
document.location = 'cgit:'+params; // execute custom protocol
retry(); // initialize lockfileCheck-loop
}
Ussage is:
launchCgit("doThisAndThat",function()
{
alert("ThisAndThat finished.");
});
the lockThisRequest.php-file:
<?php
file_put_contents("$locks/".$_GET["req"],""); // Create lock file
?>
and unlockThisRequest.php:
<?php
unlink("../\$locks/".$_GET["req"]); // Delete lock file
?>
The local program / script executed by the protocol can simply call something like:
#!/bin/bash
curl "http://servername/unlockThisRequest.php?req=$1"
after it finished.
As i just said this works, but it's anything else than nice (congratulations if you kept track of those instructions)
I'd rather prefered a more simple way and (important) this also may cause security issues with the lockThisRequest.php and unlockThisRequest.php files!
I'm fine with this solution, because i'm only using it on a password protected private page. But if you plan to use it on a public or non protected page, you may want to add some security to the php files.
Anyways, the solution works for me now, but if anyone finds a better way to do it - for example by using ajax requests - he/she would be very welcome to add that way to the respective stackoverflow-documentation or the like and post a link to it on this thread. I'd still be interested in alternative solutions :)

Determining the HTTP status code of the initial request in javascript [duplicate]

Is there any way to get the http status of the current web page from javascript?
Spent some time searching on the web, but no luck at all... Seems like it's not possible, but wanted to check with Stack Overflow for maybe some fancy workaround.
(Providing it from the server as part of the response body is not acceptable, the status is supposed to be only available via the http header)
This is not in any way possible, sorry.
Yes You can
Simply request the same page, i.e. URI, using the XMLHttpRequest. Suppose that your page on /stop.php in stop.php you may do something like:
<script>
function xhrRequest(){
console.log(this.status);
// Do some logic here.
}
function getReq(url){
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", xhrRequest);
oReq.open("GET", url);
oReq.send();
}
getReq("/stop.php");
</script>
Checkout this DEMO
🕯 Note:
You have to note that, it is a copy of the page not the page itself.
I, already, have used this solution on a page in which the server may
generate Forbidden HTTP status code when the request is come from
unauthorized IP address, so the condition here is very simple and
there is no much difference between the original and the copy page
that you have simulate its visit.
As a one liner:
fetch(location.href).then(response => console.log(response.status));
This is asynchronous, if you need a synchronous solution use XMLHttpRequest (as in the other answer) together with async: false or use async/await which feels synchronous, but is still asynchronous under the hood.
Alternatively
An approach without an extra call would need to include the status code in the page on the server side (e.g. in a meta tag), then read it on the client side via JavaScript.
Java + Thymeleaf:
<meta name="statuscode" th:content="${#response.status}">
PHP (unverified):
<meta name="statuscode" content="<?php echo http_response_code() ?>">
It is not beautiful, but you can use:
t = jQuery.get(location.href)
.success(function () { console.log(t.status) })
.error(function() { console.log(t.status) });
That When Eric says, this solution will make a new request from the same paga, and not show status of current request.
you can only check status of page loading
try:var x = document.readyState;
The result of x could be:
One of five values:
uninitialized - Has not started loading yet
loading - Is loading
loaded - Has been loaded
interactive - Has loaded enough and the user can interact with it
complete - Fully loaded

Server doesn't respond to an xmlHTTP request using the get method

I'm doing a project with arduino in which I send different requests to the server (the arduino board) with the method XMLHttprequest and Get from a webpage. Except one of the request the others are used only for sending orders to the server, so I don't expect for an XML response. The other one is a request sent in intervals of 5 seconds for getting different values from the server.
The problem arrives with this last one. Actually the webpage sends the request (because I see it on the browser console and the arduino serial monitor) every 5 seconds, but it doesn't get anything, just the headers of the answer confirming the response but nothing about the XML file. Surprisingly, when I write a normal request using the get method in the browser I get instantly the XML file with the values, and It happens all the time I do that.
I'm going to write the javascript code I'm using on the webpage
setInterval(function tiempo()
{
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
// extract XML data from XML file (containing switch states and analog value)
document.getElementById("input1").innerHTML = this.responseXML.getElementsByTagName('dato')[0].childNodes[0].nodeValue;
document.getElementById("input2").innerHTML = this.responseXML.getElementsByTagName('dato')[1].childNodes[0].nodeValue;
document.getElementById("input3").innerHTML = this.responseXML.getElementsByTagName('dato')[2].childNodes[0].nodeValue;
document.getElementById("input4").innerHTML = this.responseXML.getElementsByTagName('dato')[3].childNodes[0].nodeValue;
document.getElementById("input5").innerHTML = this.responseXML.getElementsByTagName('dato')[4].childNodes[0].nodeValue;
document.getElementById("input6").innerHTML = this.responseXML.getElementsByTagName('dato')[5].childNodes[0].nodeValue;
document.getElementById("input7").innerHTML = this.responseXML.getElementsByTagName('dato')[6].childNodes[0].nodeValue;
}
}
}
}
request.open("GET", "URL" + Math.random(), true);
request.send(null);
}
, 5000);
On the other hand, if I only write in the browser URL, I get the XML without any problem.
One las thing I have to say is that right now I'm using a webpage stored in my computer but before I was using a webpage stored in the arduino (on an SD card) and loaded also through the internet from arduino. The same code in that case worked perfectly. The reason because I changed It is because arduino ethernet is not too fast and It took so much time. With the webpage stored in my computer It goes faster because It only needs to send the orders.
Thanks!!
Finally, I figured out the problem. It is the browser. For any reason only Internet Explorer works correctly with the webpage. Neither firefox nor other web browsers got the xml file. I don't know the reason but I would like to find it.
If someone knows something about I would be glad of trying to resolve the problem.
Thanks!!

Categories

Resources