HTML Append Variable to Query String - javascript

I have http://localhost/?val=1
When I click on a link, is there a way this link can append a query variable to the current string, for example:
Link
so when I click it the url would be:
http://localhost/?val=1&var2=2
but when I click the link it removes the first query string and looks like
http://localhost/&var2=2
Is such a thing possible with normal HTML?

You can't do that using only html, but you can do it with js or php:
Using JS:
<a onclick="window.location+=((window.location.href.indexOf('?')+1)?'':'?')+'&var2=2'">Link</a>
Using Php:
Link
Notice 1: make sure you don't have the new variable in the current link, or it'll be a loop of the same variable
Notice 2: this is not a professional way, but it could work if you need something fast.

Basically you want to get your current URL via JavaScript with:
var existingUrl = window.location.href; // http://localhost/?val=1
Then append any Query Strings that are applicable using:
window.location.href = existingUrl + '&var2=2';
or some other similar code. Take a look at this post about Query Parameters.
Note: A link would already have to exist with an OnClick event that calls a function with the above code in it for it to work appropriately.
Now obviously this isn't very useful information on it's own, so you are going to want to do some work either in JavaScript or in Server code (through use of NodeJS, PHP, or some other server-side language) to pass those variable names and their values down so that the button can do what you are wanting it to do.
You will have to have some logic to make sure the query parameters are put in the URL correctly though. I.E. if there is only one query param it's going to look like '?var1=1' and if it's any subsequent parameter it's going to look like '&var#=#'.

Related

How to get element from HTML stored in variable

I am running an API to retrieve email from external system. I managed to get HTML code from the returned JSON and store it in a variable. Now, I would like to run some further operations on this HTML - for example get all elements with
[data-type="whatever"].
It would be easy in html document:
var x = document.querySelectorAll('[data-type="whatever"]');
However the HTML document I want to work with is stored in the variable so the code I write in API does not recognise it as a document. How can I do it? Any suggestions with vanilla JS?
You can try something like this.
let rawDoc = '<html><head><title>Working with elements</title></head><body><div id="div1">The text above has been created dynamically.</div></body></html>'
let doc = document.createElement('html');
doc.innerHTML = rawDoc;
let div1 = doc.querySelector('#div1');
console.log(div1)
What if you use innerHTML? or maybe I don't fully understand the question.
Since you are working without a document you have 2 options.
1. Use regex to get what you need (something like /<.+>.+ data-type="whatever".+<\/.+>/gi) should do (but for an exact match you may need to make something better).
2. Insert the html in a hidden part of the dom and select what you need from it (like in Zohir answer - he provided a good example).
I used following code with angular to store whole html content in a variable and pass it as argument to call API.
var htmlBody = $('<div/>').append($('#htmlBody').clone()).html();
This might work for you as i was working on sending email to pass invoice template so try this.

Add parameters to url with onSubmit using a Javascript function

I want to add html parameters to the url with onsubmit. I have 2 forms(1 GET, 1 POST), want to use 1 button to submit them both(Using the POST form button) When the submit button is pressed use onSubmit to call a javascript function, where parameters are "appended" to the url.
I was thinking about doing something like this:
function onSubmitForm() {
url = "localhost:8080/test/index.php?Title=document.getElementsByName('title')[0].value";
//I don't know how to actually call the url.
}
EDIT
I got what I wanted:
Appending form input value to action url as path
First, you have to concatenate the string's static and dynamic parts. Then, you can redirect.
function onSubmitForm() {
window.location = "localhost:8080/test/index.php?Title=" +
document.querySelector('title').textContent;
}
NOTES:
Only form fields have a .value property. If you are trying to get
the text within an element, you can use .textContent.
.getElementsByName() scans the entire document and makes a
collection of all the matching elements. That's wasteful when you
know you want only the first one and, in the case of <title>, there
is only ever going to be one of those in a document anyway. Use
.querySelector() to locate just the first matching element.
ES6
NOTES :
Don't forget to use Babel for converting your code in ES5.
I purpose to you this solution :
function onSubmitForm() {
window.location = `localhost:8080/test/index.php? Title=${document.querySelector('title').textContent}`
}
This way of doing with backtick is even simpler than in ES5, let me explain, before we had to concatenate with the sign + ourVariable + the continuation of our string of character.
Here we have more of that. And we can write on several lines as well.
Then ${} is used to pass a variable inside
Documentation if you want : Literal template string

Passing variable when opening another html page using JavaScript

This is probably a really silly question, but I can't find it online anywhere and I've been looking for at least an hour.
I have a link Instruments which I want to get the ID of it once clicked, as I need to pass some variable to the page I am opening to know that the instruments link was clicked. This is being called from productInformation.html
I have also tried doing Instruments and then in my JavaScript, window.open("MusicMe.html", "_self"); and then tried passing a variable that way, but still absolutely no luck. Any help as to how I would pass a variable back to the page when it opens would be brilliant.
Once it opens, I am using the variable to set the ID of an element so it only displays a certain set of the information, which is working on it's own, but when I go back to try and call it, it's always thinking it is showing them all as I cannot work out how to set the variable to define it. Unfortunately I need to use JavaScript not PHP.
Thanks.
I would just tell you some ways, hope you would be able to implement it:
Use query params to pass the variable.
When you're navigating to another page, add query params to the url.
window.open("MusicMe.html?variable=value", "_self");
In your next page, check for queryParam by getting window.location.href and using regex to split the params after ? and get that data.
Use localStorage/cookies
Before navigating to the next page, set a variable in your localStorage
localStorage.setItem("variable","value");
window.open("MusicMe.html", "_self");
In your second page, in the window load event.
$(function() {
if(localStorage.getItem("variable")) {
// set the ID here
// after setting remember to remove it, if it's not required
localStorage.removeItem("variable");
}
});
You can use localStorage to keep the value, or use parameter like
href="MusicMe.html?id=111"
to pass the value to new page.
You can always pass a GET variable in you re URL just like this myhost.com?var=value
You can get the value of this variable by parsing the URL using Js see this
How can I get query string values in JavaScript?
You can simply pass # value into url, get it and then match it with 'rel' attribute given on specified element.
Here I have done materialize collapsible open from link on another page.
JS:
var locationHash = window.location.hash;
var hashSplit = locationHash.split('#');
var currentTab = hashSplit[1];
$('.collapsible > li').each(function() {
var allRels = $(this).attr('rel');
if(currentTab == allRels){
$(this).find('.collapsible-header').addClass('active');
$(this).attr('id',currentTab);
}
});

php remove single variable value pair from querystring

I have a page that lists out items according to numerous parameters ie variables with values.
listitems.php?color=green&size=small&cat=pants&pagenum=1 etc.
To enable editing of the list, I have a parameter edit=1 which is appended to the above querystring to give:
listitems.php?color=green&size=small&cat=pants&pagenum=1&edit=1
So far so good.
When the user is done editing, I have a link that exits edit mode. I want this link to specify the whole querystring--whatever it may be as this is subject to user choices--except remove the edit=1.
When I had only a few variables, I just listed them out manually in the link but now that there are more, I would like to be able programmatically to just remove the edit=1.
Should I do some sort of a search for edit=1 and then just replace it with nothing?
$qs = str_replace("&edit=1, "", $_SERVER['QUERY_STRING']);
<a href='{$_SERVER['PHP_SELF']}?{$qs}'>return</a>;
Or what would be the cleanest most error-free way to do this.
Note: I have a similar situation when going from page to page where I'd like to take out the pagenum and replace it with a different one. There, since the pagenum varies, I cannot just search for pagenum=1 but would have to search for pagenum =$pagenum if that makes any difference.
You can use parse_str() to parse the query string, remove the unwanted parts and build the new one via http_build_query() like this
parse_str($_SERVER['QUERY_STRING'], $params);
unset($params['edit']);
$new_query_string = http_build_query($params);

What is common AJAX convention for knowing a particular state when a page is loaded?

This has been a question I've had since I started doing serious ajax stuff. Let me just give an example.
Let's say you pull a regular HTML page of a customer from the server. The url can look like this:
/myapp/customer/54
After the page is rendered, you want to provide ajax functionality that acts on this customer. In order to do this, you need to send the id "54" back to the server in each request.
Which is the best/most common way to do this? I find myself putting this in hidden form forms. I find it easy to select, but it also feels a bit fragile. What if the document changes and the script doesn't work? What if that id gets duplicated for css purposes 3 months from now, and thus breaks the page since there are 2 ids with the same name?
I could parse the url to get the value "54". Is that approach better? It would work for simple cases repeatedly. It might not work so well for complex cases where you might want to pass multiple ids, or lists of ids.
I'd just like to know a best practice - something robust that is clean, elegant and is given 2-thumbs up.
I think the best way to do this is to think like you don't have Ajax.
Let's say you have a form which is submitted using Ajax. How do you know what URL to send it to?
The src attribute. Simply have your script send the form itself. All the data is in the form already.
Let's say you have a link which loads some new data. How do you know the URL and parameters?
The href attribute. Simply have the script read the URL.
So basically you would always read the URL/data from the element being acted upon, similar to what the browser does.
Since your server-side code knows the ID's etc. when the page is being loaded, you can easily generate these URLs there. The client-side code will only need to read the attributes.
This approach has more than just one benefit:
It makes it simpler where the URLs and data is stored, because they are put exactly in the attributes that you'd normally find then in HTML.
It makes it easier to make your code work without JavaScript if you want to, because the URLs and all are already in places where the browser can understand them without JS.
If you're doing something more complex than links/forms
In a case where you need to allow more complex interactions, you can store the IDs or other relevant data in attributes. HTML5 provides the data-* attributes for this purpose - I would suggest you use these even if you're not doing HTML5:
<div data-article-id="5">...</div>
If you have a more full-featured application on the page, you could also consider simply storing your ID in JS code. When you generate the markup in the PHP end, simply include a snippet in the markup which assigns the ID to a variable or calls a function or whatever you decide is best.
Ideally your form should work without javascript, so you probably have a hidden form input or something that contains the id value already. If not, you probably should.
It's all "fragile" in the sense that a small change will affect everything, not much you can do about that, but you don't always want to put it in the user's hands by reading the url or query string, which can be easily manipulated by the user. (this is fine for urls of course, but not for everything. Same rules that apply to trusting $_GET and query strings apply here).
Personally, I like to build all AJAX on top of existing, functional code and I've never had a problem "hooking" into what is already there.
Not everything is a form though. For
example, let's say you click a "title"
and it becomes editable. You edit it,
press enter, and then it becomes
uneditable and part of the page again.
You needed to send an ID as part of
this. Also, what about moving things
around and you want those positions
updated? Here's another case where
using the form doesn't work because it
doesn't exist.
All of that is still possible, and not entirely difficult to do without javascript, so a form could work in either case, but I do indeed see what you're saying. In almost every case, there is some sort of unique id, whether it's a database id or file name, that can be used as the "id" attribute of the html that represents it. * Or the data- attribute as Jani Hartikainen has mentioned.
For instance, I have a template system that allows drag/drop of blocks of content. Every block has an id and every area that it can get dropped has one as well. I will use prefixes on the containing div id like "template-area_35" or "content-block_264". In this case, I don't bother to fallback w/o javascript, but it could be done (dropdown-> move this to area for example). In any case, it's a good use of the id attribute.
What if that id gets duplicated for
css purposes 3 months from now, and
thus breaks the page since there are 2
ids with the same name?
If that happens (which it really shouldn't), someone is doing something wrong. It would be their fault if the code failed to work, and they would be responsible. Ids are by definition supposed to be unique.
IMHO putting is at a request parameter (i. e. ?customerId=54) would be good 'cos even if you can't handle AJAX (like in some old mobile browsers, command-line browsers and so) you can still have a reference to the link.
Apparently you have an application that is aware of the entity "Customer", you should reflect this in your Javascript (or PHP, but since you're doing ajax I would put it in Javascript).
Instead of handmaking each ajax call you could wrap it into more domain aware functions:
Old scenario:
var customer_id = fetch_from_url(); // or whatever
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
New scenario:
var create_customer = function (customer_id) {
return {
"dosomething" : function () {
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
},
"dosomethingelse": function () {
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
}
};
}
var customer_id = fetch_from_url(); // or whatever
var customer = create_customer(customer_id);
// now you have a reference to the customer, you are no longer working with ids
// but with actual entities (or classes or objects or whathaveyou)
customer.dosomething();
customer.dosomethingelse();
To round it up. Yes, you need to send the customer id for each request but I would wrap it in Javascript in proper objects.

Categories

Resources