Function execute after Ajax request is complete (pure JavaScript) - javascript

In my application I use MVC model and Views are built with JavaScript DOM API.
On each page I have to check user's information to find out if session is active and if user's role gives him ability to access that page.
To make this happen, on each page I have "onload" function that triggers "sessionCheck" function which sends AJAX request to controller and returns information with which application makes decisions.
As I said JavaScript is also used to build Views, which means that after "sessionCheck" function I also have "headerView", "sectionView" and other functions that build the structure of page.
So the problem is that, before "sessionCheck" is finished other functions are loaded and nearly for 1-2 seconds users have ability to see what happens on that page and only after that they are transported out of that page by application if that is needed.
I read that there are some solutions in JQuery where "ajax.Complete" functions are available, but I couldn't same solutions in pure JavaScript. Can someone help me to solve this problem ?
This is HTML
<body onload="sessionCheckAdmin(); adminHeaderView(); adminUser(); modalView();">
sessionCheckAdmin functions looks like this
function sessionCheckAdmin()
{
var formData = new FormData();
formData.append("Code", "3");
formData.append("Sequence", "27");
formData.append("TaskId", "All");
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
var array = JSON.parse(xmlHttp.responseText);
if(array["userRole"] != "Administrator")
window.location.href = "task.php";
}
}
xmlHttp.open("POST", "../Controller.php");
xmlHttp.send(formData);
}
Part of PHP controller
case 27:
$array = json_encode($_SESSION);
echo $array;
break;

Related

Adblocker blocks XMLHttpRequest

I understand the fact, that adblockers try to deny loading (image) data later on. Anyway, I want to send some data to a php script (/log.php) to save it in a sql database. So in fact I don't care about the responsetext. This is my current js function I use to call the php script:
function log(id, unix_ms, frameid, eventtype, targetid, value){
var parameters = "";
parameters = parameters.concat("id=", encodeURI(id), "&unix_ms=", encodeURI(unix_ms), "&frameid=", encodeURI(frameid), "&eventtype=", eventtype, "&targetid=", targetid, "&value=", value);
var httprequest = new XMLHttpRequest();
httprequest.open("POST", "/scripts/log.php", true);
httprequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
httprequest.onreadystatechange = function() {
if(httprequest.readyState == 4 && http.status == 200) {
console.log(httprequest.responseText);
}
}
httprequest.send(parameters);
}
What can I change to pass the adblocker? I mean facebook uses things like ajax in masses to load text and even images in the timeline.
Is there maybe a way to use frames in the background since I don't care about the answer?
After analysing the log as suggested in a comment I found out that log.php seems to be in the blocklist, even if it's on the same server. So name you php files a little more complex to avoid this.
log.php -> submitlog.php

passing localStorage data to PHP

I want to view and manipulate Javascript localStorage information on a PHP page using PHP. I have gotten pretty far with this, but I'm not where I need to be. I'm using PHP 7.3 and vanilla JS.
I have AJAX POSTing the data to a PHP processing page (not the one that calls the javascript function). However, I need to access the POST variable on the page that called the javascript. How can I pass the information back without a click?
The page wishlist.php contains a link to the js file and <div id="temporary_wishlist"></div>.
Javascript called from wishlist.php:
window.addEventListener("load", function() {
loadWishlist();
});
// get wishlist contents
function loadWishlist() {
var items = wishlistStorage.data.items.join("%20");
var item_notes = wishlistStorage.data.item_notes.join("%20");
var comments = wishlistStorage.data.comments;
var wishlistRequest;
var response = null;
if(window.XMLHttpRequest) {
wishlistRequest = new XMLHttpRequest();
} else {
wishlistRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
wishlistRequest.onreadystatechange = function() {
if(wishlistRequest.readyState == 4 && wishlistRequest.status == 200) {
response = wishlistRequest.responseText;
document.getElementById("temporary_wishlist").innerHTML = response;
}
}
wishlistRequest.open("POST", "/wishlist-processor.php", true);
wishlistRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
wishlistRequest.send("wishlist_items=" + encodeURIComponent(items)
+ "&wishlist_itemnotes=" + encodeURIComponent(item_notes)
+ "&wishlist_comments=" + encodeURIComponent(comments));
}
Given the above, I have access to $_POST['wishlist_items'] inside wishlist-processor.php. Whatever I output inside of wishlist-processor.php is visible to the visitor on wishlist.php inside <div id="temporary_wishlist"></div>. It is not, however, visible in the Console.
On wishlist.php, I want to load the information into a PHP variable so I can send it to a MySQL query. If I could just POST to self like I do with form validation I would have access to $_POST['wishlist_items'] from wishlist.php. I already tried setting the URL in the open("POST", URL, true) function to _self or wishlist.php, and that didn't work for me.
I know it's suggested that I use Fetch, but I'm already overwhelmed learning new things I want to understand AJAX better. Also, Fetch doesn't work on Firefox Android.

How To Get an HTML element from another HTML document and display in current document?

I'm building a web site which lets users post requests on site and others to respond. I have built an app-like form to collect information. In that form I need to display 3 pages.
So I have created one page with the from and and a JavaScript file to handle these 3 pages. Other form-pages are designed separately (HTML only).
I'm planning to load the other two pages into that 1st page with XMLHttpRequest and it works.
But I need to take 3rd page into the 1st form-page (display the 3rd page of form) and change the innerHTML of that 3rd page. I tried it with
function setFinalDetails() {
document.getElementById("topic").innerHTML = object1.start;
}
//creating a XMLHttpObject and sending a request
//requiredPage is the page we request.
//elementId is the element we need to display
function requestAPage(requiredPage) {
selectElementId(requiredPage);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
m = xhttp.responseXML;
y = m.getElementById(elementId).innerHTML;
document.getElementById("hireForm").innerHTML = y;
//m is a global variable
//m is the object recieved from XMLHttpRequest.
//it is used to change the innerHTML of itself(m) and display.
//y is displaying the 3rd page in the form-page one("id =hireForm")
return m;
}
};
xhttp.open("GET", requiredPage, true);
xhttp.responseType = "document";
xhttp.send();
}
but that gives an error:
Cannot set a .innerHTML property of null
find my work on https://github.com/infinitecodem/Taxi-app-form.git
It it hard to help you in detail because we do not have a way to reproduce your error and test your code. I can suggest you to use a service like plunker to share your code. I do not know if this service will support to do some xhrRequest on other files in its working tree, you can try.
Your error message seems to reveal that one of your document.getElementById(...) is returning null instead of the html elt you want (so the id do not exist in the page).
But again without a way to test, it is hard to help you more sry. I really encourage you to try to share a link to a service (like plunker, etc) that will help others to play with your use case.

Continuous DB calls with AJAX in straight JS

This is my first question here so I will start by saying: Hello to everyone!
I am trying to make a live data "presentation" in the form of a fancy table using straight JavaScript and Ajax, backend is PHP. In order to refresh the table I need to make requests at every, lets say 3 seconds, 4 is ok to. The database is RedisDB. I made the php script to fetch the data and its ok. I made a single JS file to request and handle/process the data and it's sort of ok.
The presentation looks great and the algorithm that is written in JS works excellent, it's about 600 lines, some simple if-else's and switches other a little more complex.
It now gets nasty. I can't get the freaking thing to do this continuously, I tried ways with setTimeout() and setInterval(), I made timers and infinite loops with sleep-like functions and so on, but it just can't survive that next request after the initial when the page loads.
The code for Ajax request is pretty straightforward for pure JS. I get my JSON string data parse it with jsonParse() and then do my processing of the data.
This all works, it's the next request that fails, no matter how it's initiated (user action or something else).
AJAX code:
window.onload = function(){
getEventdataFromDB();
}
function getEventdataFromDB(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var dbData = xmlhttp.responseText;
if(dbData != ''){
processEvents(dbData); //function for data processing
}
}
}
xmlhttp.open('GET','getEvents.php?dataRequest=true',true);
xmlhttp.send();
}
I know that it's a bit of a sin these days not to follow the flow and use jQuery and other frameworks but I'm just not big on the latest and greatest simplification of stuff that works just fine, to begin with.
What is the best way to do this, how should I proceed, what to use. I did some researched and things point to chaining callbacks and Promise objects.
There is obviously no way that I am the first one to do this so what is the way forward here.
The only way to ensure the previous request is over before starting the next one is so start the next call from the onreadystatechanged event of the previous one. Because ajax runs asynchronously, there's no guarantee whether any other code you run will execute before or after the ajax call finishes.
So you need to re-organise your script a bit:
var xmlhttp;
window.onload = function(){
setupAjaxObject();
getEventdataFromDB();
}
function setupAjaxObject()
{
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
var dbData = xmlhttp.responseText;
if(dbData != ''){
processEvents(dbData); //function for data processing
}
}
getEventdataFromDB(); //run the next request
}
}
}
function getEventdataFromDB(){
xmlhttp.open('GET','getEvents.php?dataRequest=true',true);
xmlhttp.send();
}
If you wanted a little delay between the requests, you could wrap the call to the next request inside a timeout.

Using JavaScript Ajax to retrieve content from another site

I'm currently experimenting with replacing a number of function I currently use jQuery for with a Vanilla Javascript alternative. This is to:
Increase my understanding of JavaScript as a whole
Make me a better front-end developer (ties into the above)
Improve the speed and responsiveness of my web applications by negating the need for a library such as jQuery for simple tasks.
My aim today is to produce a JavaScript function that allows me to make an Ajax call to another site to retrieve a specific Div and use the content from that Div within my page. I can do this pretty easily with jQuery by filtering the response from an Ajax call with the .find() method to retrieve the specific Div I require then use the .html() function to strip the content and append it to the Div on my site. However, I cannot see an alternative method of doing this using Vanilla JavaScript.
My code so far can be found below:
function fireAjaxRequest(requestType,requestUrl,contentPlaceholder){
var ajaxRequest;
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
contentPlaceholder.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open(requestType,requestUrl, true);
ajaxRequest.send();
}
I call my function as follows:
var contentArea = document.getElementById('news');
fireAjaxRequest('GET', 'http://www.bbc.co.uk',contentArea);
When I load my page, I can see in Firebug that the request completes successfully and I get
a 200 Success response from the Ajax call however, nothing is displayed in my target element. At first I thought this was because you cannot store a whole page within a single element but after altering my code slightly I found the the following snippet of code does not seem to be executed upon the success of the Ajax call:
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
contentPlaceholder.innerHTML = ajaxRequest.responseText;
}
}
Am I doing something incorrectly here?
You really need to look into XSS. I think you'll understand why there are serious restrictions with what you're trying to do.
If you control both domains, you can use JSONP or CORS.
You could also write send an ajax request to your own server that acts as a proxy. Your server would "forward" the request to the destination server, and relay the response to the client.

Categories

Resources