I got a web app working with a PHP MVC on the server side and javascript on the client side.
What I'm trying to do, is upload a file and meanwhile, do other tasks in the website until the response comes from the server.
Here bellow I post the code I'm using right now:
function xhr(url, data, callback) {
'use strict';
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
callback('The content has been uploaded');
}
};
request.open('POST', url);
request.send(data);
}
The main problem here is when I request a new page, I don't know how to get the response.
Any help with this?.
If your site is not a single page application, once the user clicks on a link and gets redirected the upload progress might get canceled if it's not complete. If the upload to the server is complete at the time the user goes to another page, it will succeed but you will loose the reference to the object that has initialized the xhr object, thus, you won't be able to get the response. Now, What I would do, is take a look at the shared webworkers API.
You could delegate the file upload to the worker (which is a separate thread).
//define a worker
var worker = new Worker('worker.js');
worker.addEventListener('message', function (e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.
And your worker.js file:
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
self.postMessage(data);
}
};
request.open('POST', url);
request.send(data);
Related
i am getting this error (index):31 POST https://amrit.github.io/scripts/sendData.php net::ERR_FAILED 405
function ajaxpost() {
// (A) GET FORM DATA
var form = document.getElementById("myForm");
var data = new FormData(form);
// (B) AJAX
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://amrit.github.io/scripts/sendData.php");
//
//xhr.open("POST", "scripts/sendData.php");
// What to do when server responds
xhr.onload = function() {
console.log(this.response);
};
xhr.send(data);
}
i am getting following error when i deploy the html on website. Uncaught SyntaxError: Unexpected token '<', "<?php
"... is not valid JSON
at JSON.parse ()
at xmlhttp.onreadystatechange
function get_component_states() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "scripts/receiveData.php", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// update the form with the new values
// stringify the response
var response = JSON.parse(this.response);
//var response = JSON.parse(this.response);
console.log(response);
// update the form with the new values
document.getElementsByName("mainVoltage")[0].innerHTML = response.mainVoltage;
document.getElementsByName("loadPower")[0].innerHTML = response.loadPower;
document.getElementsByName("exportPower")[0].innerHTML = response.exportPower;
document.getElementsByName("solarPower")[0].innerHTML = response.solarPower;
document.getElementsByName("todayKwh")[0].innerHTML = response.todayKwh;
document.getElementsByName("totalKwh")[0].innerHTML = response.totalKwh;
document.getElementsByName("circuit1")[0].checked = response.circuit1;
}
// show the response in the console
console.log(this.response);
};
}
Github Pages does not allow POST requests and cannot execute PHP either. It's only for displaying simple, static or Javacript-driven pages, with no backend.
References:
https://docs.github.com/en/pages/getting-started-with-github-pages/about-github-pages says
GitHub Pages is a static site hosting service that takes HTML, CSS, and JavaScript files straight from a repository on GitHub, optionally runs the files through a build process, and publishes a website
Do GitHub pages support PHP?
says
Github pages currently do not support PHP as it only supports static website.
Instead, deploy your application to a hosting environment which provides the correct environment for the code you want to host. There are thousands of hosting providers around the world which provide a PHP-capable environment.
I'm creating a controller for lights using thingsboard.
I need to change device's telemetry data (thingsboard) using rest put request
$.post("http://<ip_here>:8080/api/v1/<device_accesscode_here>/telemetry",{ selectedPreset:2 });
REST calls work using swagger.io and postman, but when calling from widget or any other web page, request returns 400.
Can't seem to find solution to this and url is correct. i have tried both $.post and $.ajax styles.
YAY! i got it working!
for some reason, only XHR approach worked..
var data = "{\"selectedPreset\":\"2\"}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "IP HERE");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "33c35ded-140d-e016-fa35-ee8185d7bd44");
xhr.send(mydata);
i ripped this right out of postman.
I have created a mobile application that scans the surrounding Bluetooth devices and I am able to put the devices into an array list.
Now, using the http POST method, I have to send a JSONObject having this array list to a url and even for this I have written an expected code on the android app(I am sure this code will work because I have already worked on this using POST method to URL's and displaying the response on the activity).
But, how to listen the JSONObject, sent by any android app to the URL, parse it and show it on that particular URL's webpage ?
(In short I am looking for a Javascript code which can handle this and show the list.)
if you already have the URL where the JSON is being posted to you can do:
plain js:
var request = new XMLHttpRequest();
request.open('GET', 'URL', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
with jquery:
var getData = $.getJSON('URL');
getData.done(function(data){
// you have access to data here
});
I'm currently sending POST requests to a PHP file of mine via a button with the following function:
function buttonFunction() {
$.post("http://ipaddress/core/file.php",{username:username, password:pword, coins:coins}, function(data) {
// Stuff
});
}
However, I recently found out that if the file process/PHP script is still running (trying to obtain the resulting data/response), and the user refreshes the page, the PHP process would still be running on the server. Also, if the user then decided to click the button again (after refreshing), there would be TWO PHP proccesses running from the same user on the server (that is, if the first one was still running):
Javascript Abort POST Request on Retry/Refresh (HIGH CPU Usage)
However, I came across sending POST data with XMLHttpRequest with Javascript:
Send POST data using XMLHttpRequest
So let's say I send my POST request this way, would it be safe to say when the user refreshes/closes out of the page, the PHP execution ends?
function buttonFunction() {
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
However, if this also does not work, how can I fix this issue (multiple scripts running in the background from the same user)? Whether that fix be in the PHP file or in the JavaScript itself, any help would be appreciated.
Edit 1:
Possible Solution?
What if I use XMLHttpRequest and abort the request before the page unloads?
window.onbeforeunload = function(event) {
http.abort();
};
How can to request url or website address and show response code with javascript or jquery?
i.e
request www.google.com
if (response_code = 200) {
print "website alive"
} else if (response_code = 204) {
print "not found";
}
I'm assuming from the jquery tag that you mean to do this in a browser, not from a server running NodeJS or similar (although there is a NodeJS module for jQuery).
Although you can request URLs and see the response code using the XMLHttpRequest object, the Same Origin Policy will prevent your accessing virtually any sites other than the one the page itself was loaded from. But if you're pinging the server your page was loaded from to make sure it's still there, you can do that:
function ping(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("get", url);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) { // Request is complete
callback(xhr.status); // Tell the callback what the status code is
}
}
}