So on the net I've come across a several ways to preload / redirect a webpage.
Now's the question is this the proper way to handle a redirect with preload (Load the next page async while still showing the current page)
$.get("page.php", function (data) {
document.open();
document.write(data);
document.close();
window.history.pushState("Title", "Title", "/page.php");
$.cache = {};
}, "html");
Or should I better stay with a regular redirect?
window.location = "page.php";
The next page contains a fullscreen video and a soundtrack (audio)
Thanks.
You can use Ajax to load next page asynchronous.
Here is an example of a simple Ajax request using the GET method, written in JavaScript.
AJAX stands for Asynchronous JavaScript and XML, and for the XMLHttpRequest object to behave as AJAX, the async parameter of the open() method has to be set to true: xhr.open('get', 'send-ajax-data.php', true);
get-ajax-data.js:
// This is the client-side script.
// Initialize the Ajax request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php', true); // `true` makes the request asynchronous
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
alert(xhr.responseText); // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
And at the end you can use below codes to reload or redirect page data:
document.getElementById("myDiv").innerHTML = xhr.responseText;
Related
I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};
I have an xmlhttprequest code that is executed on a button, it runs and access the advReqPage.aspx on the first run but when I press the button again, it doesn't access the advReqPage.aspx any more. What is the problem here?
function SaveAdvPayment() {
var xhr = new XMLHttpRequest();
var ornumber = document.getElementById("ORNumber").value;
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// OK
alert('response:' + xhr.responseText);
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
}
xhr.open("GET", "Server_Requests/advReqPage.aspx?poo=" + ornumber + "&sess=INSERT", false);
xhr.send();
alert('Saved');
$('#myModal').modal('hide');
}
Probably the first response is getting cached and when you make the second request your browser is not making this new request. This behavior is due to browser locking the cache and waiting to see the result of one request before requesting the same resource again. You can overcome this by making your requests unique like adding random query string.
I have an ExceptionListener implemented in Symfony3 (also works in Symfony2). The ExceptionListener identifies whether the request was normal HTTP or AJAX (XmlHttpRequest) and generates a response accordingly. When using jQuery .post() or .ajax(), the ExceptionListener returns $request->isXmlHttpRequest() as TRUE, but when using javascript var xhr = new XmlHTTPRequest(), the ExceptionListener returns $request->isXmlHttpRequest() as FALSE. I am using the latter in a small amount of instances where files need to be uploaded via AJAX (which cannot be done using .post() or .ajax().
I am looking for a solution (either frontend or backend) to resolve my ExceptionListener incorrectly picking this up as a normal HTTP request.
Frontend Code:
function saveUser()
{
var form = document.getElementById('userForm');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', '{{url('saveUser')}}', true);
xhr.onreadystatechange = function (node)
{
if (xhr.readyState === 4)
{
if (xhr.status === 200)
{
var data = JSON.parse(xhr.responseText);
if (typeof(data.error) != 'undefined')
{
$('#processing').modal('hide');
$('#errorMsg').html(data.error);
$('#pageError').modal('show');
}
else
{
$('#successMsg').html('User Successfully Saved');
$('#processing').modal('hide');
$('#pageSuccess').modal('show');
$('#userModal').modal('hide');
updateTable();
}
}
else
{
console.log("Error", xhr.statusText);
}
}
};
$('#processing').modal('show');
xhr.send(formData);
return false;
}
ExceptionListener.php (partial)
# If AJAX request, do not show error page.
if ($request->isXmlHttpRequest()) # THIS RETURNS FALSE ON JS XmlHTTPRequest()
{
$response = new Response(json_encode(array('error' => 'An internal server error has occured. Our development team has been notified and will investigate this issue as a matter of priority.')));
}
else
{
$response = new Response($templating->render('Exceptions/error500.html.twig', array()));
}
When using vanilla ajax you need to pass the following header to your ajax request
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
I'm writing a server-only app that fetches data from an API, checks if there's anything new, and emits an update to all connections. The only restriction is that updates have to be emitted in the order that they were created (chronologically, or by pk), and a request could be affected by the response of a previous request.
The problem I'm facing is when a request takes a long time, another request might overtake it, and start emitting updates "out of turn".
What's the best way to approach this? Ideally I would like this flow:
request -> response -> emit ... request -> response -> emit ...
Note: If a request fails or times out, I would like to retry it at least X times.
you can use callback
function check(){
//request to the api
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
// here you can emit your events
// do your events
// after done your events, you can call check again
check()
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
}
check()
There are two quick ways to counter this.
You can use callback and use your function recursively
var myCall = function(){
var request = new XMLHttpRequest();
request.open(<request_method>, <request_url>, true);
request.send(null);
if (request.status === 200) {
//put your emit function here
myCall();
}
}
myCall();
You can make calls synchronous. I would not recommend this if you are making continuous calls
var myCall = function(){
var request = new XMLHttpRequest();
request.open(<request_method>, <request_url>, false); //false makes it synchronous
request.send(null);
if (request.status === 200) {
//put your emit function here
}
}
myCall();
myCall();
myCall();
myCall();
.
.
.
as many times as u want
This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
I use pageinit to load page. I call an XMLHttpRequest to send and get request to PHP programs on Linux, using RESTful API on server side. The server side accept an array I send to it and echo an JSON back. It all work well. However, HTTP_GET functions returns back to page and displays content before it finished and got a response from server.
How can I prevent it from going back before it responded?
pageinit
$(document).on("pageinit","#quote_open1",function(){
alert('pageinit quote_open1');
openPage(); });
openPage
function openPage(url, jsontest){
var jsonResponse=HTTP_GET( url, jsontest);
alert('!!!!!!!!!!!!!!!!-->'+jsonResponse);
}
HTTP_GET
function HTTP_GET( url, jsonToSend){
alert('START HTTP_GET');
var jsonResponse;
//send get request to server
xhr = new XMLHttpRequest();
xhr.open("GET",url+"jsonToSend",true); //open server connection
xhr.send();//this is where json string will be sent out
//
//this function send
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4) //read server response
{
alert(xhr.readyState);
jsonResponse=xhr.responseText;
alert("!!!jsonResponse="+jsonResponse);
alert("!!!xhr.responseText"+xhr.responseText);
return "server returned a response 1"; //RETURNS this all the time
}
};
alert('END HTTP_GET');
if (xhr.readyState == 4) return "server returned a response 2"; //want to return this when leaves this function
return "stil in progress returns before it's finished";
};
(this 3 functions are in different js)
Thanks.
what you miss here is the fact that xhr is asynchrone, so your function HTTP_GET returns before the request is done.
You could use a callback function like this :
$(document).on("pageinit","#quote_open1",function(){
console.log('pageinit quote_open1');
openPage(); });
function openPage(){
var doTheJob = function(jsonResponse){ console.log('jsonResponse : '+jsonResponse); }
HTTP_GET( url, doTheJob);
}
function HTTP_GET( url,callBackFunc){
console.log('START HTTP_GET');
var jsonResponse;
//send get request to server
xhr = new XMLHttpRequest();
xhr.open("GET",url,true); //open server connection
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4) //read server response
{
callBackFunc(xhr.responseText);
}
};
xhr.send();//this is where json string will be sent out
//
console.log('END HTTP_GET');
};