This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 7 years ago.
not sure if this should be done in javascript or something else. Basically, I have a little quiz type thing where all questions are on a single page. I have an ajax function which checks what question it is, and if it is the last question, it will redirect the user to a new page e.g.
if(totalScore <= 10) {
$.ajax({
method: "POST",
url: "php/handleData.php",
data: { answers: ansArray, page: window.location.href, pt: "aa" }
}).done(function( response ) {
window.location.replace("page2.html" + '?le=' + le + '&ch=' + ch);
}).fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
window.location.replace("page2.html" + '?le=' + le + '&ch=' + ch);
});
return false;
}
As you can see, the redirect also includes some additional parameters. Therefore, when I am redirected, I am on a page like
page2.html?le=1&ch=2
Now I dont necessarily need these params in this url, but it is the only way I could think about getting them over to page2. Page 2 has a button on it like
Visit link1.com >
It is in this href where I need the params le and ch to be injected.
How would I go about doing this?
Thanks
With JQuery on Page2.html you can do that:
$(document).ready(function(){
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var le_val = getParameterByName("le");
var ch_val = getParameterByName("ch");
$("a.btn.btn-primary").attr("href","www.link1.com?le="+le_val+"&ch="+ch_val);
});
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to build a 5-day forecast using open weather API. The parameters I'm using based on the website are not working, it returns undefined. Also, is there a way I can get the main temp from day 1, 2 and etc. Please help
here's my code:
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/forecast', //API Call
dataType: 'json',
type: 'GET',
data: {
q: city,
appid: key,
units: 'metric',
cnt: '10'
},
success: function(data) {
var wf = '';
$.each(data, function(index, val) {
wf += '<p><b>' + data.city.name + '</b><img src=http://openweathermap.org/img/w/' + data.list[0].weather.icon + '.png></p>' + data.list[0].main.temp + '°C' + ' | ' + data.list[0].weather.main + ", " + data.list[0].weather.description
});
$("#showWeatherForcast").html(wf);
}
});
Your current code is not too far off. I suggest that you use console.log(data) in your success function to see what pops out while you are testing. It will help you understand the returned data structure.
If you take a look in your browser console now, you will likely see some warnings. I recommend you use https instead of http URLs for both your main API call and your image URLs to avoid some of them, including Mixed Content warnings.
The below code is adapted from yours and displays a temperature, a description, and an icon per each val in data.list in city. Note that $.each here loops through properties of each val (0-9) in the array data.list to access the data you need. Your current code tries to access a val of data.list[0][some property] each time, returning undefined.
var key = "YOUR KEY";
var city = "YOUR CITY"; // My test case was "London"
var url = "https://api.openweathermap.org/data/2.5/forecast";
$.ajax({
url: url, //API Call
dataType: "json",
type: "GET",
data: {
q: city,
appid: key,
units: "metric",
cnt: "10"
},
success: function(data) {
console.log('Received data:', data) // For testing
var wf = "";
wf += "<h2>" + data.city.name + "</h2>"; // City (displays once)
$.each(data.list, function(index, val) {
wf += "<p>" // Opening paragraph tag
wf += "<b>Day " + index + "</b>: " // Day
wf += val.main.temp + "°C" // Temperature
wf += "<span> | " + val.weather[0].description + "</span>"; // Description
wf += "<img src='https://openweathermap.org/img/w/" + val.weather[0].icon + ".png'>" // Icon
wf += "</p>" // Closing paragraph tag
});
$("#showWeatherForcast").html(wf);
}
});
Try this in the url and remove the data property
'http://api.openweathermap.org/data/2.5/forecast?appid='+key+'&q='+city+'&count=10'
I can't test without an api key but the docs pretty much tell you what to do http://openweathermap.org/forecast5
I have a button that takes a value from a checkbox and inserts it dynamically into a URL parameter. the URL looks like this:
example.com/search?q=searchterm&site=site1&page=1
&site=site1 is what is being updated dynamically by the value of a checkbox. My code for that looked like below at first:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = '&site=' + filterSelection + '&page=1';
console.log(filterUrl + " - " + filterSite);
window.location.replace(filterUrl);
});
The problem with the first approach is when you click the button multiple times, it just adds the new parameters to the URL, so it ends up looking like:
example.com/search?q=searchterm&site=site1&page=1&site=site2&page=1&site=site3&page=1
When I only need to change &site=site3&page=1 - I tried using a regex to select that part of the URL and replace it with the new one. My attempt at that is below:
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
console.log(filterUrl + " - " + filterSite);
window.location.replace(url, filterUrl);
});
What this block does is remove the search query and just returns
example.com/site=site1&page=1 which gives a 404.
I need to somehow update a segment of a URL, and not the entire thing. I believe I need to do some sort of regex to target it and change it. What are the next steps? How can I update a certain section of a URL?
EDIT: This is where it stands now:
// apply filter, go to page
$("#apply-filter").click(function() {
var filterSite;
var filterSelection;
var filterUrl;
filterSite = "http://" + location.host + location.pathname + location.search;
filterSelection = $('.search-filter-dialog input[type="checkbox"]:checked').val();
filterUrl = filterSite + '&site=' + filterSelection + '&page=1';
var url = filterUrl.match(/&([^ ]*)/)[1];
// console.log(filterUrl + " - " + filterSite);
if (window.location.href.indexOf("&site=") > -1) {
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
window.location.replace(filterSite);
console.log(filterSite);
} else {
window.location.replace(filterUrl);
}
});
but the .replace() method doesn't seem to be working.
Correct me if I got it wrong:
You have something like this: example.com/search?q=searchterm&site=site1&page=1 and you need to update ONLY THIS PART: &site=site1.
One way:
filterSite.replace(/&site=site\d+/,'&site=site' + filterSelection);
This works only if the updatable part of the url is ALWAYS going to be of the form &site=site<number>, ie: filterSelection is always a number
anyhow, let me know
REGARDING YOUR EDIT:
Assuming what you mean by The .replace() method won't change the parameter, is that the URL won't change, you are right: when you do this:
filterSite.replace(/&site=\d+/,'&site=' + filterSelection);
what you are modifying is the variable filterSite, the page won't automatically reload to the new url, which I think is what you intend after seeing this other line:
window.location.replace(filterSite);
replace it with:
window.open(filterSite);
to make the page go to the new url
More about window.open and its arguments
One last thing, I noticed you are using /&site=\d+/,'&site=' + filterSelection as args for replace which will not match example.com/search?q=searchterm&site=site1&page=1. So, unless you changed the structure of the url, you might want to look on that too.
let me know
URL Constructor
EXAMPLE: 1
;
var uri = new URL( "http://example.com/search?q=searchterm&site=site1&page=1" );
uri.searchParams.has("q");
>> true
uri.searchParams.set( "site", "site2" );
uri.searchParams.set( "page", "2" );
uri.href;
>> "http://example.com/search?q=searchterm&site=site2&page=2"
;
Browser Suport: ( ? )[ Chrome 49, Firefox 44, Opera 36, IE12 ]
I suggest you to use A POST request method and Jquery has already a method to construct that params to send based in the form
https://api.jquery.com/serialize/
I'm trying obtain some data from the following URL, using a JavaScript code:
http://data.cityofnewyork.us/resource/erm2-nwe9.json
That's how I construct my query:
//data URL variables
var start_date = '2013-08-01'; //YYYY-MM-DD
var end_date = '2013-08-08'; //YYYY-MM-DD
var c_type = 'Noise'; // Complaint Type
// Build the data URL
var URL = "http://data.cityofnewyork.us/resource/erm2-nwe9.json"; // API Access Endpoint
URL += "?";
URL += "$where=";
URL += "(latitude IS NOT NULL)";
URL += " AND ";
URL += "(complaint_type='" + c_type + "')";
URL += " AND ";
URL += "(created_date>='" + start_date + "') AND (created_date<='" + end_date + "')";
URL += "&$group=complaint_type,descriptor,latitude,longitude";
URL += "&$select=descriptor,latitude,longitude,complaint_type";
URL = encodeURI(URL);
And how I'm testing it so far:
$.getJSON(URL, function(data)
{
console.log(data)
});
Right now it works fine, but I should consider any complaint type that contains a single world ("Noise"):
URL += "(complaint_type LIKE '%" + c_type + "%')";
Encoded URL (seems OK):
http://data.cityofnewyork.us/resource/erm2-nwe9.json?$where=(latitude%20IS%20NOT%20NULL)%20AND%20(complaint_type%20LIKE%20'%25Noise%25')%20AND%20(created_date%3E='2013-08-01')%20AND%20(created_date%3C='2013-08-08')&$group=complaint_type,descriptor,latitude,longitude&$select=descriptor,latitude,longitude,complaint_type
Error:
{
"code" : "query.compiler.malformed",
"error" : true,
"message" : "Error, could not parse SoQL query \"select descriptor,latitude,longitude,complaint_type from #erm2-nwe9 where (latitude IS NOT NULL) AND (complaint_type LIKE '%Noise%') AND (created_date>='2013-08-01') AND (created_date<='2013-08-08') group by complaint_type,descriptor,latitude,longitude\"",
"data" : {
"query" : "select descriptor,latitude,longitude,complaint_type from #erm2-nwe9 where (latitude IS NOT NULL) AND (complaint_type LIKE '%Noise%') AND (created_date>='2013-08-01') AND (created_date<='2013-08-08') group by complaint_type,descriptor,latitude,longitude"
}
}
The documentation seems that it is possible to use LIKE, but I can't get it to work.
I don't know how to do this.
I have just figured out how it works, it seems that it does not accept just percent symbols '%' in the condition, it should be preceded by backslash(or is it just slash, anyway).
So this is the valid URL for using 'like' statement:
http://data.cityofnewyork.us/resource/erm2-nwe9.json?$where=(latitude%20IS%20NOT%20NULL)%20AND%20(complaint_type%20like%20%27\%Noise\%%27)%20AND%20(created_date%3E=%272013-08-01%27)%20AND%20(created_date%3C=%272013-08-08%27)&$group=complaint_type,descriptor,latitude,longitude&$select=descriptor,latitude,longitude,complaint_type
Or appropriate row in your code:
URL += "(complaint_type LIKE '\\%" + c_type + "\\%')";
Let me know if it works, and sorry for not replying on time, I really have no experience with Salesforce and SOQL. But thanks to you there is another new space for me to explore :)
I've been strugling looking for a way to set a cookie if a URL parameter is persent. The problem is, the name of the URL parameter is half dynamic.
The URL would be:
http://zzzz.test.bbbb/index.html?transaction[XXXX]=YYYYY
The XXXX is the userID that will change depending on the customer and YYYY is the actual value (transaction number).
I have the following code but it won't recognize the brakets nor what is inside. How can I set it to recognize the URL parameter including the brakets and the dynamic userID within the brakets?
Here is my code:
function URLparam(name) {
return unescape(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
if (URLparam("transaction") !== null && !get_cookie ("Transacion_ID")) {
set_cookie ("Transacion_ID", URLparam("transaction"));
}
if (get_cookie ("Transacion_ID")) {
console.log(get_cookie ("transaction"));
}
});
Any hint would be much appreciated.
Thanks!
NEW ADDITION ==========================
For a link with the following format:
http://zzzz.test.bbbb/index.html?transaction[XXXX][zzzzz]=YYYYY
How would the correct getParameterByName function look like in order to recognize the URL parameter transaction[XXXX][zzzzz] ?
I've tried this but it does not work:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp(name + '(?:\\[\\d+\\]?:\\[\\d+\\])?=' + '(.+?)(&|$)'),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Any ideas?
This version of URLparam() allows an optional [XXX] after the name:
function URLparam(name) {
return unescape(
(RegExp(name + '(?:\\[\\d+\\])?=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
To allow multiple array indexes, change ? (for optional) to * (for any number of repetitions):
function URLparam(name) {
return unescape(
(RegExp(name + '(?:\\[\\d+\\])*=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
I need get only this part of current url and redirect after 5 seconds...
example of current url:
http://www.page.com/?archive=filename
i need get only filename and put in javascript code
here my code:
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script type="text/javascript">
var country,url;
country = geoip_country_code()
if(country=="US"){
url="http://www.page.com/1.php?archive=filename";
} else if (country == "UK") {
url="http://www.page.com/2.php?archive=filename";
} else if (country == "ES") {
url="http://www.page.com/3.php?archive=filename";
}
setTimeout("location.href = url;",5000);
</script>
please i need help with this code, thanks.
you can use the code posted here:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var country,
url,
codemap = {
US: 1,
UK: 2,
ES: 3
};
url = "http://www.page.com/" + codemap[geoip_country_code()] + ".php?archive=" + getParameterByName('archive');
setTimeout(function () { location.href = url; },5000);
Here's a previous question on parsing query strings in JavaScript. That one's already marked as a duplicate, so there's undoubtedly more info out there. If this doesn't help, the keywords you want to search for are "Parse query string in JavaScript".
Parse query string in JavaScript