I'm looking for a way to access the Query String of a page that has been loaded into a div, through jquery or javascript.
The reason is that I need to modify how the page calls a function based on whether a parameter has been loaded into the page or not.
I've tried this inside the page that has been loaded into the div
var fileIDPresent = false;
var url = this.window.location.href;
alert(url);
if (url.indexOf('?' + 'FileID' + '=') != -1)
fileIDPresent = true;
else if (url.indexOf('&' + 'FileID' + '=') != -1)
fileIDPresent = true;
The page is loaded into the div through the following code:
$('#loadedContentHolder').load('/ViewDetails.aspx?FileID=' + File, function () {
// load finished...
$('#loadedContentHolder').slideDown('slow');
});
The URL is lost when you inject the code into the DIV. You need to save the URL to the div node somehow.
You could do this:
var url = '/ViewDetails.aspx?FileID=' + File;
$('#loadedContentHolder').load(url, function () {
// load finished...
$('#loadedContentHolder').data('url', url).slideDown('slow');
});
Next time you want to know what URL was used you can fetch the url like this:
var url = $('#loadedContentHolder').data('url');
This will return the URL that was used and you can use that url to extract the params:
var params = getUrlParams(url);
function getUrlParams(url) {
var vars = [], hash
,hashes = url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if (hash.length === 2) {
vars.push(hash[0]);
vars[hash[0]] = unescape(hash[1]);
}
}
return vars;
}
Related
I am currently running a for loop that takes in A users data for the item name and colour for a clothing product he wishes to purchase..
I am creating a loop to run as many times as the amount of items the user specifies/ putts in..
This loop goes to a JSON url, and looks for an item name using a keyword finder (.includes)
once it finds the array with the specified item name, it takes a value from that array called id, this id is applied to the websites url and it takes you directly to that item.
Then once it gets to that Item It loads the HTML source and parses it from string.
Inside this html data there is a list that has all the items colors listed. It then finds the specified color inside a (li).
Inside that li with the color there is another url, it takes that url and goes to it. And that is the final step.. it succesfully goes to the item that the user wanted..
It does this in a loop with each item until there are none left.
Here is the problem...
When I console and log everything It should work perfectly.
But for some odd reason It always loads the console perfectly,
(console logs all the urls for each item in its proper order)
But for some reason It just goes to the url of the last item.
Im pretty sure a solution to this would be to use async/ await. But.. Im not sure were to put it so It would go to each url in its order..
Here is the code:
function loadHTMLSource(urlSource){
xhttp = new XMLHttpRequest();
xhttp.open("GET", urlSource, false);
xhttp.send();
return xhttp.response;
}
function finder() { // do I put async function finder here?
var json_url = "http://www.example_shop.json";
var xhr = new XMLHttpRequest();
xhr.open("GET", json_url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
for (i=0; i < data.count; i++) {
var item = data.task[atc_count][0].split(' - '); // splits the item name and color
const searchStr = item[0]; // item name
const lowerSearchStr = searchStr.toLowerCase();
const foundItem = resp.products.find( another category
({ name }) => name.toLowerCase().includes(lowerSearchStr));
console.log(searchStr);
console.log(foundItem);
var id = (getValues(foundItem, 'id', ''));
//atc_count += 1;
//loop += 1;
//var url = []
//url[i] = ("https://shopping_example/shop/" + id);
var url = ("https://shopping_example/shop/" + id);
chrome.tabs.query({currentWindow: true, active: true}, function (tab){
chrome.tabs.update(tab.id, {url: url}); // the url of the users specified item, but default first color, parses this html to get its color url below
})
console.log(i);
//i += 1;
console.log(i);
console.log(url);
var page_html = loadHTMLSource(url);
parser = new DOMParser()
my_document = parser.parseFromString(page_html, "text/html");
search_str = (item[1]); // the color
search_attr_name = "style-name";
var all_styles = my_document.querySelectorAll("[style-name]");
atc_count += 1;
loop += 1;
matching_url = "";
//atc_count += 1;
//loop += 1;
if(all_styles.length){
all_styles.forEach(function(e){
var style_name = e.attributes[search_attr_name].value;
if(style_name.length && style_name.toLowerCase().indexOf(search_str) > -1) {
if(typeof e.attributes["href"].value !== "undefined"){
color = e.attributes["href"].value
}
}
});
console.log(color);
var color_url = ("https://www.shopping_example.com" + color);
chrome.tabs.query({currentWindow: true, active: true}, function (tab){
chrome.tabs.update(tab.id, {url: color_url}); // final url the url of the item with the users specified color
})
console.log(color_url);
//i += 1;
//window.open(color_url);
}
}
my Main question is:
Where would I put async and await in this code to make it go to each url (temporary delay(add to cart process would go here))
and go to the next url and do the same as a loop
I found this but I cant really understand how to implement it into my script:
https://javascript.info/async-await
I would really appreciate If someone could post an example with async and await to go to each url
Thank You <3!!
I have been having some issues with opening multiple webpages in phantomjs, I am first opening a website which contains a few links, which I want to open as well, and save a piece of text from each URL to my jobs_list which has many objects inside of it. And after all the URL's have been run, I want to exit phantomjs. But as it is right now it never exits, and I have trouble recieving data from second function.
var webPage = require('webpage');
var page = webPage.create();
var jobs_list = [];
page.open('url', function (status) {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.onConsoleMessage = function(msg) {
console.log(msg);
};
var list = page.evaluate(function() {
var jobs = [];
var job;
$('.test').each(function(){
$(this).find('span').each(function(){
var job_link = $(this).find('a');
var url = job_link.attr("href");
job = {title : job_link.text(), url : url, location : ""};
jobs.push(job);
})
});
return jobs;
});
var i = 0;
jobs_list = list;
next_page(i);
});
});
function next_page(i){
if (i <= (jobs_list.length-1)) {
var current_job = jobs_list[i];
var url = current_job.url;
page.open(url, function (status) {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
var location = page.evaluate(function() {
var job_location;
$('.job-location').each(function(){
$(this).find('li').each(function(){
job_location = $(this).text();
})
})
console.log(job_location);
return job_location;
});
jobs_list[i].location = location;
if(i == (jobs_list.length-1)) {
phantom.exit(0);
}
});
});
console.log(i, current_job.title);
next_page(++i);
}
}
The problem is that the page.open call is asynchronous. If you look closely to your next_page function it can be shortened to this:
function next_page(i){
if (i <= (jobs_list.length-1)) {
var current_job = jobs_list[i];
var url = current_job.url;
page.open(url, function (status) {
...
});
console.log(i, current_job.title);
next_page(++i);
}
}
It means that next_page(++i); is executed before page.open(url, ...) even managed to load the first HTML content. This call leads to the next page.open(url, ...) being executed immediately, thus overwriting the previous request. And you're never going to get any data this way.
You have to do two things:
move the next_page(++i); call where the execution of one page is finished
reduce the number of condition checking
I propose:
function next_page(i){
if (i <= (jobs_list.length-1)) {
var current_job = jobs_list[i];
var url = current_job.url;
page.open(url, function (status) {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
var location = page.evaluate(function() {
var job_location;
$('.job-location').each(function(){
$(this).find('li').each(function(){
job_location = $(this).text();
})
})
console.log(job_location);
return job_location;
});
jobs_list[i].location = location;
console.log(i, current_job.title);
next_page(++i);
});
});
} else {
phantom.exit(0);
}
}
That's quite an old version of jQuery. Perhaps you want to load a newer version. If the page already has jQuery included, you will likely break the page by loading another jQuery into it. Don't load an additional jQuery version at all in this case.
I want to send json data through url to next html page. I checked it by emulator as I am working for mobile app, the url could not redirect to next page it is crashing at the moment what is the reason behind this. How can I parse it on next page .I am new to the jquery any idea? my json data contains result of two different sql queries in an array
$.ajax({
type : "POST",
datatype : "json",
url : "http://Localhost/phpBB3/check_pass.php?username="+ username + "&password="+ password+"&f=68",
success: function(data){
alert(data);
window.location.href="source/testmenu.html?varid=" + data +"&username=" + username +"&password=" + password;
}
});
This is the code on next page
$(document).ready(function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var arr = SearchString.split('&');
console.log(arr);
//Set session variables
var username = arr[1].split('=')[1];
var password = arr[2].split('=')[1];
document.getElementById('username').value = username;
document.getElementById('password').value = password;
)};
in your case in first page urlencode json
window.location.href="source/testmenu.html?varid=" + encodeURIComponent(data) +"&username=" + username +"&password=" + password;
and in next page
var data= arr[0].split('=')[1];
var recieved_json = $.parseJSON(data);
Then try this one:
var data = {
username: username,
password: password
};
$.ajax({
type: "POST",
url: "http://Localhost/phpBB3/check_pass.php",
params: $.param(data),
success: function(a) {
window.location.href = "source/testmenu.html?"
+ $.param(a) + "&" + $.param(data)
}
});
And this would be your code for the next page (the iterator is from Satpal's answer):
$(document).ready(function() {
var params = window.location.search;
var getURLParams = function(params) {
var hash;
var json = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
json[hash[0]] = hash[1];
}
return json;
}
params = getURLParams(params);
var username = params.username;
var password = params.password;
$('#username').val(username);
$('#password').val(password);
});
Though I agree with #Jai that sending username and password in url is not recommended.
Once you get the URL to load you'll need to run your data through some encoding and decoding. You might have the wrong path. If you want "http://Localhost/source/testmenu.html" make sure the first character is a "/".
Make sure your data object is encoded correctly.
// Encode data for querystring value.
var data = {
foo: "bar"
};
var data_str = JSON.stringify(data);
data_str = encodeURIComponent(data_str);
Decode and test your URL.
// Get data from querystring value.
// Get the query as an object with decoded values.
// Note that JSON values still need parsing.
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.data);
} catch (err) {
alert(err + "\nJSON=" + q.data);
}
Parameter should be html encode while navigating or requesting to the URL and decode at the receiving end. It may suspect potentially dangerous content which may leads to crash.
I want to redirect to particular page.
For that I am using some Javascript function in MVC project as::
function rootUrl(url) {
var _rootUrl = '#Url.Content("~")';
var x = url;
if (url.indexOf(_rootUrl) != 0) {
x = _rootUrl + "/" + url;
x = x.replace(/\/\//g, "/").replace(/\/\//g, "/");
}
return x;
};
which is being used as ::
var url = rootUrl("Home/Company/") + $(this).val();
window.location.href = url;
But I am getting wrong URL in my browser as::
http://localhost:60294/Home/Company/#Url.Content(%22~%22)/Home/Company/7
Why not use Url.Action() directly which gives you url relative to root directory, instead of creating a javascript messy function:
var url = '#Url.Action("Company","Home")' + $(this).val();
Here,Home is the name of Controller and Company is the action of it
You can't access razor in Js file. When I need the urls from Razor in Js I just define them in the view, like:
<script>
var _rootUrl = '#Url.Content("~")';
</script>
This will work
In my view, I have a javascript function to handle a select event on a pie chart. The function is shown below:
function selectHandler() {
var selectedItem = visualization.getSelection()[0];
if (selectedItem) {
var val = data.getFormattedValue(selectedItem.row, 0);
location.href = '/Tickets';
}
}
Currently I am on the Home Controller in the Groups View. I want to navigate to the Index View of the Tickets Controller while passing the selected value from the javascript variable "val". How would I go about doing this?
Are you intending to manually navigate the user?
If you're looking for a redirect JavaScript way, then you would do something as simple as...
location.href = '/Tickets?value=' + val;
Now this may not work for everything. For example, if location.href already contains a '?', and you need to maintain that context, then you need to use '&'. Maybe your app lives in a Virtual Directory.
You might do something like...
var newUrl = location.href;
if (newUrl.indexOf('?') > -1)
newUrl += '&';
else
newUrl += '?';
newUrl += val;
This allows you maintain any existing context as well.
If you expect the ticket to already be defined, you might need to remove that from the query string, if it already exists.
In that case then you might want to do something like...
var params = location.search.substring(1).split('&'),
paramToRemove, indexOfValue,
hasSearch = false,
param;
for (var i = 0, len = i; i < len; i++)
{
param = params[i];
indexOfValue = param.indexOf('value');
hasSearch = param.indexOf('?') === 0;
if (indexOfValue === 0 || (indexOfValue === 1 && hasSearch ))
{
paramToRemove = params[i];
break;
}
}
var newUrl = location.href;
// Remove old value
if (paramToRemove) newUrl = newUrl.replace(paramToRemove, hasSearch ? '?' : '');
// Add proper search char
if (newUrl.indexOf('?') > -1)
newUrl += '&';
else
newUrl += '?';
// Add new value
newUrl += val;
location.href = '/Tickets?val=' + val;
//On page load the server will generate the URL for you.
var ticketURL = '#Url.Action("Index", "Tickets")';
//Append the value to the URL
ticketURL = ticketURL + '?val=' + val;
//Do your stuff!
Since, you are calling Controller methods from javascript. You should make an POST ajax call to Ticket Controller and passing Action method name also.
Your code would be like this:
return $.post('/Ticket(ControllerName)/Index(method name)/',parameters here);
Inside API Controller, Index method will accept the same param which we are passing from our javascript.
ActionResult Index(parameter){...}