I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.
Related
I have built a Status Page for my servers with HTML and CSS, and instead of updating the Server Status every time one of them goes down, I was wondering if it's possible to add something to query the IP's of the server every 10m or so, and if the query fails, to turn the status button to RED.
Here's what I'm working with: https://status.floridastaterp.org
Any help is largely appreciated!
Thanks.
You can do it without PHP, for that use javascript and make a ajax call:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// You change the status of button
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
And to call it every 10min, warp your function with:
setTimeout(request(),1000);
function request(){
if(response == true){
// This makes it unable to send a new request
// unless you get response from last request
response = false;
var req = $.ajax({
type:"post",
url:"https://status.floridastaterp.org"
});
req.done(function(){
console.log("Request successful!");
// This makes it able to send new request on the next interval
response = true;
});
}
setTimeout(request(),1000);
}
request();
I'm trying to get movie data for BlackBerry 10 apps.
I don't know where I'm making a mistake.
Please, can you help me?
Thank you all.
import bb.cascades 1.4
Page {
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var data = "{}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send(data);
}
}
You need to use the onreadystatechange EventHandler.
Also, you don't need to pass data when making a GET request.
I have removed the withCredentials line as it isn't needed in this example.
You can learn more on XMLHttpRequest here :
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
var json = JSON.parse(xhr.responseText);
var results = json.results;
var count = results.length;
console.log("There are " + count + " results :");
json.results.forEach((value, index) =>
{
console.log(index + " - " + value.title);
});
}
};
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send();
}
Here's an example of using XMLHttpRequest I've made a long time ago :
https://github.com/RodgerLeblanc/Markup/blob/master/assets/main.qml
I want to wait for the XHR to open after I continue with the program but synchronous XHR is deprecated in chrome api. How can I get around this?
Using a callback to continue execution seems like the best method. Without a clear example of your project here's a generalized option:
function performRequest() {
// ... Some code
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bar/foo.txt", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
useRequest(xhr.responseText);
}
};
}
function useRequest(data) {
// Continue with your application
}
performRequest();
I want to make a demo on how to combine ASP and AJAX. I have found snippets from http://www.aspjax.com and implemented it in my project. However, the text that should be displayed cannot be output properly.
Here's the code. Basically the same as the one in the original:
In index.asp
<script language="javascript" type="text/javascript">
/** XHConn - Simple XMLHTTP Interface - bfults#gmail.com - 2005-04-08 **
** Code licensed under Creative Commons Attribution-ShareAlike License **
** http://creativecommons.org/licenses/by-sa/2.0/ **/
function XHConn()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
// doAJAXCall : Generic AJAX Handler, used with XHConn
// Author : Bryce Christensen (www.esonica.com)
// PageURL : the server side page we are calling
// ReqType : either POST or GET, typically POST
// PostStr : parameter passed in a query string format 'param1=foo¶m2=bar'
// FunctionName : the JS function that will handle the response
var doAJAXCall = function (PageURL, ReqType, PostStr, FunctionName) {
// create the new object for doing the XMLHTTP Request
var myConn = new XHConn();
// check if the browser supports it
if (myConn) {
// XMLHTTPRequest is supported by the browser, continue with the request
myConn.connect('' + PageURL + '', '' + ReqType + '', '' + PostStr + '', FunctionName);
}
else {
// Not support by this browser, alert the user
alert("XMLHTTP not available. Try a newer/better browser, this application will not work!");
}
}
// launched from button click
var getMessage = function () {
// build up the post string when passing variables to the server side page
var PostStr = "";
// use the generic function to make the request
doAJAXCall('ajaxtest.asp', 'POST', '', showMessageResponse);
}
// The function for handling the response from the server
var showMessageResponse = function (oXML) {
// get the response text, into a variable
var response = oXML.responseText;
// update the Div to show the result from the server
document.getElementById("responseDiv").innerHTML = response;
};
</script>
<body>
<button onclick="javascript:getMessage();">Get Message From Server</button>
<div id="responseDiv">Original Text</div>
</body>
So, the code tells it to replace the Original Text in the div with the one in ajaxtest.asp
In ajaxtest.asp
<%# Language=VBScript %>
Response.Write "The Server time is " & Now()
The problem is when I click the button Get Message From Server, the stuff in ajaxtest.asp is rendered as plain text, but not in ASP. How to fix this? Is it because of the extension used is wrong?
EDIT: by plain text I mean exactly as Response.Write "The Server time is " & Now()
You probably want the contents of your ASP page to be:
<%# Language=VBScript %>
The Server time is <%=Now()%>
I'm working on multifile upload using html5 and xhr, as you can see I'm sending requests in loop which is a bad
concept but I'm not able to upload files when I send it outside the loop and only the last file gets upoaded.
Where am I going wrong?
$('#uploadimg').on('click', function(e) {
var files = document.getElementById('files').files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('Something went terribly wrong...');
}
};
xhr.send(formData);
}
// now post a new XHR request
});
Codeigniter
public function uploadimg (){
$config['upload_path'] = FCPATH . 'uploads/' ;
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc';
$config['remove_spaces'] = 'TRUE';
$this -> load -> library('upload', $config);
//$this->upload->initialize($config);
foreach ($_FILES as $k => $f) :
$this -> upload -> do_upload($k);
endforeach;
//$this->index();
}
Its seems the first thing you should look at is your js for loop. ID's should be unique so I would rule that approach out.
I would maybe loop each input field, check to see if the attr type == file, then append that to your formData object.
var inpts = document.getElementsByTagName('input');
for(var i=0; i < inpts.length; i++)
{
if(inpts[i].getAttribute('type') == 'file')
{
formData.append('myFiles[]', inpts[i].files[0]);
}
}
On the server side I would look at your foreach loop, maybe a for loop might suffice.
for($i=0; $i < count($_FILES); $i++){
$this->upload->initialize(); //new initialization for each file
$this->upload->do_upload($_FILES[$i]);
continue;
};
Hi guys i figured out the problem codeigniter is working fine, the problem is in the jquery. this is the line causing the problem. "formData.append(files[i].name, files[i]);" Thanks for all for takign efforts to solve my issue
$('#uploadimg').on('click', function(e) {
//console.log(files);
// files = document.getElementById('files').files;
var formData = new FormData();
$(files).each(function(i) {
formData.append(files[i].name, files[i]);
})
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg');
xhr.onload = function(data) {
console.log(xhr.responseText);
};
xhr.send(formData);
});