Javascript ajax request not working - javascript

I have created a js file to fetch data from a txt file and display it on html but it does not seem to work properly.
//Event Handling
document.addEventListener("DOMContentLoaded",
function (event){
console.log("Inside DOMContentLoaded");
document.getElementById('but').addEventListener("click", function (){
console.log("inside first");
$ajaxUtils.sendGetRequest("/Data/name.txt", function(res){
console.log("inside getRequest");
console.log(request.responseText);
});
});
});
console.log("HELLO");
And here is the code for sendGetRequest.
(function (global){
var ajaxUtils = {};
//Returns an Http Request Object
function getRequest()
{
if(window.XMLHttpRequest){
return (new XMLHttpRequest());
}
else {
global.alert("Ajax is not supported");
return (null);
}
}
//Makes an AJAX request to 'requestURL'
ajaxUtils.sendGetRequest = function(requestURL, responseHandler, isJsonResponse) {
var request = getRequest();
request.onreadystatechange = function() {
handleResponse(request,responseHandler,isJsonResponse);
}
request.open("GET", requestURL, true);
request.send(null); //For POST only
}
//Only calls user provided 'responseHandler'
//function if response is ready
//and not an error
function handleResponse(request,responseHandler,isJsonResponse)
{
if((request.readyState == 4) && request.status == 200){
if(isJsonResponse == undefined)
isJsonResponse = true;
if(isJsonResponse === true)
responseHandler(JSON.parse(request.responseText));
else {
responseHandler(request.responseText);
}
}
}
global.$ajaxUtils = ajaxUtils;
})(window);
Location of js file: /js/ajax-utils.js and /js/script.js and Location of data file: /Data/name.txt

Related

Trigger `PHP` file using JS

I have 3 files, one HTML, PHP and JS. I have a button in HTML and I want to trigger the PHP file when it's clicked, through Javascript. I tried the following code, but for some reason it gives me the error message every time:
JavaScript
function getOutput() {
getRequest(
'create_json.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
<button id="submit" onclick="getOutput()">Submit</button>
<div id="output">waiting for action</div>
<?php
function get_data(){
$connect=mysqli_connect("localhost", "root", "root", "openingpage");
$query="SELECT * FROM created_list ";
$result=mysqli_query($connect, $query);
$list_data=array();
while($row=mysqli_fetch_array($result)){
$list_data[]=array(
'ModelID' => $row["ModelID"],
'ImageID' => $row["ImageID"],
'ListID' => $row["ListID"]
);
}
return json_encode($list_data);
}
$file_name=date('d-m-Y').'.json';
if(file_put_contents($file_name,get_data())){
echo $file_name.' file created';
}
else{
echo 'There is some error';
}
?>
I'm always getting the "Bummer: there was an error!" message. Why can't I get it . I checked the code more than 100x times but can't find whats going wrong in this code.
Thanks in advance.

Is there any security flaw in using iframe as a communication layer cross site?

Goal of this poc:
a way to keep the user logged in across webapps
on different domains
do it once, import it everywhere
The poc:
So I thought of this possible solution. I call it the user widget.
Let's say we have service AUTH that provides the endpoint to login and logout, it also sets the httpOnly cookie.
This should be the header, distributed across webapps. The header downloads the iframe and with postMessage send calls to it, to understand if the user is already logged in, otherwise shows login:
<script>
/**
****************************************
* Code that should be inside the header
****************************************
*/
window.onload = function() {
(function(){
if (window.addEventListener) {
window.addEventListener("message", handleMessage, false);
} else {
window.attachEvent("onmessage", handleMessage);
}
//- This could be * meaning no preferences, or a URI,
//- but SHOULD not be * but the correct origin
var iframeOrigin = "*";
var iframeId = 'IFRAME-PROXY';
createIframe(checkStatusOfLogin);
var doLoginButton = document.getElementById('do-login');
doLoginButton.onclick = doLogin;
function createIframe(onLoadCallback) {
var iframe = document.createElement('iframe');
iframe.id = iframeId;
iframe.style.display = 'none';
iframe.src = 'https://mysecureiframe.securedomain.com/file.html';
document.body.appendChild(iframe);
iframe.onload = function () {
onLoadCallback(iframe);
};
}
function checkStatusOfLogin(iframe) {
var iframeWin = iframe.contentWindow;
var payload = {
action: 'status'
};
iframeWin.postMessage(JSON.stringify(payload), iframeOrigin);
}
function doLogin() {
var iframeWin = document.getElementById(iframeId).contentWindow;
var payload = {
action: 'login',
username: document.getElementById('username').value,
password: document.getElementById('password').value
};
iframeWin.postMessage(JSON.stringify(payload), iframeOrigin);
}
function handleMessage(evt) {
console.log('Inside client tab, received: ', evt);
var userContainer = document.getElementById('user-container');
try {
var parsedResponse = JSON.parse(evt.data);
if (parsedResponse.isCIA) { // checking it's a postmessage from us and not an extension
if (parsedResponse.status == "LOGGED_IN") {
userContainer.classList.remove('not-logged-in');
} else if (parsedResponse.status == 'NEED_LOGIN') {
userContainer.classList.add('not-logged-in');
}
} else {
throw new Error('not CIA message');
}
} catch (e) {
console.log('not CIA message');
}
}
}());
};
/**
*******************
* End of header code
* *****************
*/
</script>
The iframe contains a really simple body:
<!DOCTYPE html>
<html>
<head>
<script src="https://mysecureiframe.securedomain.com/loginProvider.js" type="text/javascript" ></script>
</head>
<body>
<p>IFRAME NON VISIBILE</p>
</body>
</html>
And here's the content of loginProvider.js:
(function() {
if (window.addEventListener) {
window.addEventListener("message", handleMessage, false);
} else {
window.attachEvent("onmessage", handleMessage);
}
// to read: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
// Guardare HEADER Content-Security-Policy instead of X FRame Options
function checkStatus(success, failure) {
var http = new XMLHttpRequest();
var url = "https://mysecureiframe.securedomain.com/status"; // AUTH endpoint
http.open("GET", url, true);
http.onreadystatechange = function() { //Call a function when the state changes.
if (http.readyState == 4 && http.status == 200) {
if (http.responseText == "true") {
success();
} else {
failure();
}
}
};
http.send();
}
function doLoginIframe(user, pass) {
var http = new XMLHttpRequest();
var url = "https://mysecureiframe.securedomain.com/login"; // AUTH endpoint
http.open("POST", url, true);
http.onreadystatechange = function() { //Call a function when the state changes.
if (http.readyState == 4 && http.status == 200) {
if (user == 'username' && pass == 'password') {
var payload = getPayload();
payload.status = 'LOGGED_IN';
parent.postMessage(JSON.stringify(payload), "http://targetOrigin");
alert(http.responseText);
}
}
};
http.send();
}
function getPayload() {
return {
isCIA: true
};
}
function handleMessage(evt) {
console.log('Inside iframe, got: ', evt); // TODO Check targetOrigin is from trusted sites
var parsedRequest = JSON.parse(evt.data);
if (parsedRequest.action == "status") {
checkStatus(function() {
var payload = getPayload();
payload.status = 'LOGGED_IN';
parent.postMessage(JSON.stringify(payload), "http://targetOrigin");
},
function () {
var payload = getPayload();
payload.status = 'NEED_LOGIN';
parent.postMessage(JSON.stringify(payload), "http://targetOrigin");
});
} else if (parsedRequest.action == "login") {
doLoginIframe(parsedRequest.username, parsedRequest.password);
}
}
}());
Besides adding the check to see if origin is a trusted site, do you see particular security flows with this strategy?

How to get HTML source with JavaScript?

I am trying to get HTML source with JavaScript:
Why this does not work?:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function MyGetHTML()
{
$.get("www.example.com/test1.html", function(data){
return data;
});
}
</script>
</head>
<body>
test 30.9.2015
<script>
alert(MyGetHTML());
</script>
</body>
</html>
(Below, i'm assuming that you need to get content from filen IN your source, from the same origin of your page.)
Your code doen't works because the the return of your MyGetHTML method is the get request itself, and the success callback of your request returns the data.
You could do:
function MyGetHTML(){
$.get("www.example.com/test1.html", function(data){
//alert(data);
//or use console.log() instead.
console.log(data);
});
}
And then
MyGetHTML(); //This will log your data after the succesfull request.
Further reading: https://api.jquery.com/jquery.get/
Hint on your use case:
A simple tutorial from Tuts+ on making simple ajax requests.
With pure JS:
load('test.html', function(xhr) {
document.getElementById('container').innerHTML = xhr.responseText;
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Or with jquery library
$('#container').load('test.html');
Because you're returning to the get not the function itself. Try like this:
function MyGetHTML()
{
var datum = '';
$.get("www.example.com/test1.html", function(data){
datum = data;
});
return datum;
}

changing the text of a button in ajax

I Have list confirmation buttons generated dynamically using PHP.When I click a button i want it change to "approved".But it is not doing so?Nothing changes though the query is submitted successfully.Any help please.Here is my js code snippet:
function appr ($ref) {
var job_id= $ref;
var resp;
var buttons=$('.confirm');
buttons.click(function(){
var $this=$(this);
$this.text=('approved');
});
if (window.XMLHttpRequest) {
resp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
resp = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "job_id="+job_id
resp.open("POST",
"approve.php",
true);
resp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
resp.send(data);
resp.onreadystatechange = display_data;
function display_data() {
if (resp.readyState == 4) {
if (resp.status == 200) {
document.getElementById("myDiv").innerHTML=resp.responseText;
} else {
alert('Request not successful.');
}
}
}
}
you can do it like that
$this.html("approved");

How do I have the text and xml files open in a new window/tab?

Here is the code. I am fairly new to JavaScript and I'm learning more every day. This code is from an example from a textbook. Thank you for your responses. Another question I'd like to ask is how can I display the returned text in an unordered list? Would that be something to include in the html side of things or can it be done within the JavaScript file?
window.addEventListener("load",initAll,false);
var xhr = false;
function initAll() {
document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);
document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);
}
function getNewFile(evt) {
makeRequest(this.href);
evt.preventDefault();
}
function makeRequest(url) {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (xhr) {
xhr.addEventListener("readystatechange",showContents,false);
xhr.open("GET", url, true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);
}
else {
var outMsg = xhr.responseText;
}
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
function getText(inVal) {
if (inVal.textContent) {
return inVal.textContent;
}
return inVal.text;
}
}
By the looks of it, you are making an AJAX request and are receiving XML.
In this case, I would:
Open up a new page with window.open()(returns a new Window object)
And then change the document.body.innerHTML of that new page to the XML you have
If you had a webpage that held the XML(maybe the server you are requesting to has one), you can just do:
window.open("page.xml");

Categories