So I want to use ajax request and I know how to use it.
But problem that i had that I want to pass parameters to request. So My first page had 4 parameter then I build url like this,
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
but now parameter is increasing like now I have 20 more. So now building url like this going to be messy approach. Is there a better way to do this.
Here is my function where i am building URL in javascript function.
function closeAssessment() {
var closeReason = document.getElementById("SectionClousureReason");
var closeReasonStr = closeReason.options[closeReason.selectedIndex].value;
var closeCmt=document.getElementById("SectionCloseAssessmentCmt").value;
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
ajaxRequest(url);
return;
}
edit:
As you ask here is my ajaxRequest function,
function ajaxRequest(url) {
strURL = url;
var xmlHttpRequest = false;
var self = this;
// Mozilla, Safari
if (window.XMLHttpRequest) {
self.xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
self.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpRequest.open("POST", strURL, true);
self.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xmlHttpRequest.onreadystatechange = function() {
if (self.xmlHttpRequest.readyState == 4) {
if (self.xmlHttpRequest.status == 200) {
var htmlString = self.xmlHttpRequest.responseText;
var parser = new DOMParser();
var responseDoc = parser.parseFromString(htmlString, "text/html");
window.close();
} else {
ajaxFailedCount++;
// Try for 1 min (temp fix for racing condition)
if (ajaxFailedCount < 1200) {window.setTimeout(function() {ajaxRequest(url)}, 50);}
else {alert("Refresh failed!")};
}
}
}
self.xmlHttpRequest.send(null);
}
You could make an object with the key/value pairs being what you want added to the URL.
var closeReason = document.getElementById("SectionClousureReason");
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true',
closeReasonStr: closeReason.options[closeReason.selectedIndex].value,
closeCmt: document.getElementById("SectionCloseAssessmentCmt").value
};
Then add them to the URL via a loop.
var url = "./ControllerServlet?";
var urlParams = Object.keys(params).map(function(key){
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
url += urlParams;
ajaxRequest(url);
Note: I added encodeURIComponent just to be safe.
EDIT: From your comment, it seems you want to submit a <form> but you want to use AJAX to do so. In that case, you can loop over the form elements and build the above params object.
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true'
};
var form = document.getElementById('yourForm'),
elem = form.elements;
for(var i = 0, len = elem.length; i < len; i++){
var x = elem[i];
params[x.name] = x.value;
}
Build up an object of your parameters and put them in the uri through a loop like this:
var values= {
page_id: 'BPCLA',
action: 'test'
},
uri_params = [],
uri = 'http://yoururl.com/file.php?';
for (var param in values) uri_params.push( encodeURIComponent( param ) + '=' + encodeURIComponent( values[ param ] ) );
uri = uri + uri_params.join( '&' );
console.log( uri );
Or consider using POST to transport your parameters, as many browsers have limitations on the query string.
Edit: you can also build yourself a function which traverses your form and builds up the values object for you so you don't have to do it manually.
Be aware however that anyone can inject custom url paramters simpy by appending form elements before submitting the form (by using the developer tools for example) so keep that in mind.
If you are using jQuery you can use .serializeArray() or have a look at this answer for a possible function you could use.
Related
I'm trying to post # sing to make some words turn to hashtags but the code doesn't work and it's via API using this code:
true == function()
{
var getMyItem = function (str)
{
if (sessionStorage.getItem(str) == null)
{
setMyItem(str, 0);
return 0;
}
return sessionStorage.getItem(str);
}
var setMyItem = function (key, value)
{
sessionStorage.setItem(key, value);
}
function bot(post)
{
const Http = new XMLHttpRequest();
var Token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Token
var ID= "xxxxxx";
var url= 'https://bot.xxx/api/'+Token+'/sendMessage?text='+post+'&chat_id='+ID;
Http.open("GET", url);
Http.send();
}
// you need to change the url variable contents for your own Telegram API or those of the same SN APIs..
So when it comes to call the post like with this code:
var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
var post_n = "%23Hi. It's: " + myDate + "\n";
var post = encodeURI(post_n);
if (getMyItem(key + "htr") != "yes")
{
bot(post);
setMyItem((key + "htr"),"yes");
}
return true;
}
}()
, it doesnt support # sign in my browsers including Chrome an Firefox and nothing is sent actually.
So if it were for Telegram, the bot would look like this (and I donno if it works or not but I'm talking about another SN):
var url= 'https://api.telegram.org/'+Token+'...
Please tell me how to send # code. By the way, "%23" doesn't work.
So I m working on API when i need to set x-auth header for every request in PRE-REQUEST script.
I have variables in my request url i.e {{baseUrl}}{{basePath}}{{businessID}}/users?name={{userName}}......etc
I need to take whole address and add secretKey variable to the end of address, then get hash512 from it.
I was able to achieve that if i have no variables in my address i.e.: dummy.com/12321-e213-21-3e?name=John
I did this by :
var secret = "1234qwerHr2";
var url = request.url.slice(9); //sliced because I don't need to include baseUrl to hash
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(url+secret));
This will return the desired result.
Here is what I logged when trying the same code with variables
console.log(url); =>>>>>>> asePath}}{{businessID}}/users?name={{userName}}......etc
All variables defined , that`s for sure
Basically question is : how to get url with values of variables using var url = request.url; I need not {{businessID}}/users?name={{userName}} but 12321-e213-21-3e?name=John
I lost source where i found it. Somewhere on postman github issue thread
var secret = pm.globals.get("devSecretKey");
pm.myUtility = {
interpolateVariable: function (str) {
return str.replace(/\{\{([^}]+)\}\}/g, function (match, $1) {
// console.log(match)
let result = match; //default to return the exactly the same matchd variable string
if ($1) {
let realone = pm.variables.get($1);
if (realone) {
result = realone
}
}
return result;
});
},
getUrl: function () {
let url = pm.request.url.getRaw();
url = this.interpolateVariable(url)
let {
Url
} = require('postman-collection')
return new Url(url);
},
getUrlTest: function () {
let url = pm.request.url.getRaw();
url = this.interpolateVariable(url)
// let {
// Url
// } = require('postman-collection')
//return new Url(url);
return pm.request.url.parse(url);
}
}
var requestPath = pm.myUtility.getUrl().getPath();
var requestQuery =pm.myUtility.getUrl().getQueryString();
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(requestPath+"?"+requestQuery+secret)); //I added '?' because when you use getQueryString() i does not have '?' before query
pm.environment.set("tempAuthHash", hashedPayload);// use this in your header
This function he wrote is converting your {{variable}} to 'variableValue'
No need to change anything in his functions if you are not good with coding. Guy who created it has golden hands. Just place in your pre request
So I have a URL that looks like this:
localhost:9031?redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&scope=test
I want to redirect to the URL localhost:8080/something which makes use of part of the redirect uri but drops the /callback from it.
In order to get the redirect uri I have a method that does the following and I pass it the string redirect_uri:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
}
This gives me back the string http://localhost:8080/callback. Then to get the index of callback I use the following function.
function getPosition(string, subString, index) {
return string.split(subString, index).join(subString).length;
}
Then when the button is clicked I put it all together and do:
$('.button').click(function(e) {
var query = window.location.search.slice(1);
var redirect = getQueryVariable('redirect_uri');
var index = getPosition(redirect, '/', 3);
var baseUrl = redirect.slice(0, index);
window.location.href = baseUrl + '/something';
});
This all works as intended but it doesn't seem particularly foolproof or efficient. Looking for optimizations or suggestions to use functionality of JavaScript or JQuery that I don't know of. Looking to avoid 3rd party libraries but if they are good enough I will definitely still use them.
I would recommend letting the browser do the heavy lifting of parsing the URL. Assuming you have the decoded redirect URI from the query string, you can do the following:
var myUrl = 'http://localhost:8080/callback&scope=test';
function parseURL(url) {
var a = document.createElement("a");
a.href = url;
return {
protocol: a.protocol,
hostname: a.hostname,
port: a.port,
pathname: a.pathname
};
}
var parsedURL = parseURL(myUrl);
console.log(parsedURL.protocol + '//' + parsedURL.hostname + ':' + parsedURL.port + '/something');
You can build the base url from the results and, optionally, parse the pathname if necessary.
This is based on a well known Gist to parse URLs in JavaScript, which was introduced by John Long.
function parseURL(url) {
var parser = document.createElement('a'),
searchObject = {},
queries, split, i;
// Let the browser do the work
parser.href = url;
// Convert query string to object
queries = parser.search.replace(/^\?/, '').split('&');
for( i = 0; i < queries.length; i++ ) {
split = queries[i].split('=');
searchObject[split[0]] = decodeURIComponent(split[1]);
}
// return all fragments
return {
protocol: parser.protocol,
host: parser.host,
hostname: parser.hostname,
port: parser.port,
pathname: parser.pathname,
search: parser.search,
params: searchObject,
hash: parser.hash
};
}
// using the method
(function() {
// your first url
var temp = parseURL('localhost:9031?redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&scope=test');
// second (the redirect_uri param);
var url = parseURL(temp.params.redirect_uri);
// now you could do:
window.location.href = url.protocol + '://' + url.host + '/whateverYoWant';
})();
I have a mp3 link like this :
http://example.com/932937293723.mp3
but i want to rename it when user downloads the file to be like this
http://example.com/Artist - Title.mp3
My code :
DOWNLOAD
The mp3 file stored in remote server. And i'm not the owner of that server.
HTML download attribute seem not good solution. because it's not cross-browser. Any cross-browser solution to solve this ? Javascript maybe :D
If you insist on working from the front end, try working with the following code. The getblob method is depreciated, but you need to update that side. Let me know.
function getBinary(file){
var xhr = new XMLHttpRequest();
xhr.open("GET", file, false);
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xhr.send(null);
return xhr.responseText;
}
function sendBinary(data, url){
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
if (typeof XMLHttpRequest.prototype.sendAsBinary == "function") { // Firefox 3 & 4
var tmp = '';
for (var i = 0; i < data.length; i++) tmp += String.fromCharCode(data.charCodeAt(i) & 0xff);
data = tmp;
}
else { // Chrome 9
// http://javascript0.org/wiki/Portable_sendAsBinary
XMLHttpRequest.prototype.sendAsBinary = function(text){
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0);
for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
var bb = new BlobBuilder(); // doesn't exist in Firefox 4
bb.append(data);
var blob = bb.getBlob();
this.send(blob);
}
}
xhr.sendAsBinary(data);
}
var data = getBinary("My music.mp3");
sendBinary(data,'http://www.tonycuffe.com/mp3/tailtoddle_lo.mp3');
In your back end code, you can fetch the file to your server, store it to a variable, rename it from there, define the corresponding headers, and return it. this could happen as an ajax call initiated on the javascript click.
Post further details about your backed and i can help you more.
You can use something like below (ASP.NET)
In ASPX
Download
In ASP.NET
Response.ContentType = "audio/mpeg3";
Response.AddHeader("content-disposition", "attachment;filename=New_file_name.mp3");
Server.Transfer(decoded_URL_of_MP3_file);
Look here for other MIME types
Update#1 - Using Javascript alone, you can try something like this, though I've not tested in different browsers
function Download(url, fancyFileName)
{
var file = document.createElement('a');
file.href = url;
file.target = '_blank';
file.download = fancyFileName;
var event = document.createEvent('Event');
event.initEvent('click', true, true);
file.dispatchEvent(event);
window.URL.revokeObjectURL(file.href);
}
Download('http://server.com/file.mp3','Artist_file.mp3');
I am trying to run multiple Ajax functions on load in a single page which will get data from two different php pages. Both the Ajax functions will then print the retrieved data onto the page from which the ajax function was called. The problem I encountered was that the last function call which I make from the Ajax overrides the first function call, and so only the second function result is showed.
The code for one of the Ajax function (since both of the are very similar to each other):
function favorite_track_request(str){
switch(str){
case 'next_track':
var feed = 'require_fav_track_info';
var offset = track_currentOffset + 5;
if(offset > max_track_range){
offset -= 5;
}
break;
case 'prev_track':
var feed = 'require_fav_track_info';
var offset = track_currentOffset - 5;
if(offset < 0){
offset = 0;
}
break;
default:
var feed = 'require_fav_track_info';
var offset = 0;
}
request = new ajaxRequest()
request.open("GET", "scripts/"+feed+".php?offset="+offset, true)
request.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(this.responseText != null){
if(request.responseText){
document.getElementById('fav_tracks').innerHTML = request.responseText;
}
}else alert("No data recieved");
}else {
alert("Ajax error: "+this.statusText);
}
}
}
request.send(null);
track_currentOffset = offset;
}
This ajax would then print to <div id="fav_tracks"></div>, however this gets overridden because another call (similar to the Ajax above) is made and that overrides the previous one. Is there any way to stop this?
I built a data handler "class" to manage just such a thing. You are right, the one overrides the other. I haven't investigated it, but it's probabably because your are re-assigning the onEvent that AJAX uses.
Below is the class I built (I know, it's not JQuery... it works). What it does is uses timeouts to "know" when to fire the second and third async request. There probably is a JQuery function that does the same thing.
You would call this by using the below for each AJAX call (giving each call a unique var name):
dataHandler = new DataHandler("[name of datafile to call]");
dataHandler.query['[myQueryName]'] = 'myValue' //this is an Object used to build a query string, if needed, so use as many data pairs as you need
dataHandler.asynchronous(myOnReadyStateChangeFN);//put the fn you want to use for readystatechange as a reference... do not includ the ()
Here's the "class":
function DataHandler(dataFile){
this.dataFile = dataFile;
dataInProgress = false;
this.query = new Object();
this.asynchronous = function(fn){
var thisFunction = this.asynchronous
var rand = Math.floor(Math.random()*100001);
var query, timeOutFunctionString;
if(this.dataInProgress){
timeOutFunctionString = callingObjectName+".asynchronous("+fn+")";
this.thisTimeout = setTimeout(timeOutFunctionString,500);
}else{
dataInProgress = true;
this.assignRequestObject.xmlHttp.onreadystatechange = function () {
fn();
dataInProgress = false;
return;
};
}
query = this.dataFile + '?r=' + rand;
for (var key in this.query) query = query + '&' + key + '=' + this.query[key];
//console.info("DataHandler.asynchronous\nquery = "+query+'\nthis.dataFile = ' + this.dataFile);
this.assignRequestObject.xmlHttp.open('GET', query, true);
this.assignRequestObject.xmlHttp.send(null);
};
this.AssignRequestObject = function() {
try { this.xmlHttp = new XMLHttpRequest() } catch (e) {
try { this.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {
try { this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) {
alert("Your browser does not support AJAX!");
return false
}
}
}
};
this.assignRequestObject = new this.AssignRequestObject();
};