I'm passing data on a page1 through a querystring onto page2, when a user clicks the button "send" the data is passed on the querystring and page2 gets the 'data=..' parameter from the querystring and shows it's value on the page.
The problem is that the data on page1 is created through the user by the input textbox and can be quite long. This gives us the following error when the user clicks "send"
URL Requested is too long
This is the code used to get the span element(submitted text by user) and convert it to a variable which is added onto the querylink:
$('#send').click(function() {
var data_text = $('span').prop('outerHTML');
window.location.href = 'http://swter.com/send.php?data=' + data_text + '';
return false;
});
Are there anyways around it apart from limiting the amount of chars a user can type?
So you could split the contents of the textarea into multiple strings using String#split and then loop through the resulting array and make AJAX GET requests to your back end server. You will need to include a form of unique identifier that ties each batch of data together on the server, and an index so you can rebuild it, ie:
?id={{unique_id}}&page=1&total=6&body={{message_page_1_of_6}}
However, as pointed out, a POST request would be more appropriate here.
Related
This is the issue I'm facing:
I have multiple consecutive web pages where I hold the same id in the query params and send it forth from one to the next due to various reasons. All is fine when passing this param with GET routes. However, the third page (which has the query param as well) has a short form and POST method, which redirects to the fourth page at the end. Something like this:
app.post("/third", function(req, res){
req.body.id //returns undefined, but should not
some code here
res.redirect("/fourth?id="+id); //how i want to pass the param on
});
Whichever I use, req.body or req.query or req.params, I can never access the id 'abcd' from
web-app/third?id=abcd
and add it to the fourth page query params, I always get undefined.
Am I doing this wrong? Still quite new to Node JS and Express and everything to do with web-apps, so my logic might be off. I've searched Google, but due to my inexperience most of the posts were unhelpful for me. How to send the params when I have a POST method and cannot access the param from anywhere except the page holding the form query itself?
Any help is appreciated!
Edit:
How the front-end looks like:
<form action="/third" method="post">
...
a few inputs here
....
<input type="submit" rel="next" value="To signing" class="button"
id="nextbutton">
<a onclick="setUrl();" rel="prev" class="button" id="cancelbutton">Previous page</a>
</form>
/third is the current page, /fourth the next
I see what you mean now. Your url which you are POST'ing the form from contains a query parameter in the URL. That's the parameter which you can't access to. Well - that parameter is not in the POST parameters, it's not in the form. So you have 2 options.
When you're outputting the /third view with your GET request you should add that query parameter as a hidden input value into the form, so you can post it as a parameter to the back-end.
If you're using Node.js you just need to modify your /third view (might be a Jade / Pug template)
to have
// Make sure this line is in the form that you're posting (syntax is jade - any other way of replacing the idFromServer value with a server value would work just as well.
input(name="id", type="hidden", value="#{idFromServer}")
and update your view render code to be like:
// It's read from query because we know this one is a get request.
res.render('third', {idFromServer: req.query.id});
After this req.body.id should work!
What we did here is whenever you're getting the third view with an id parameter, we'll put a hidden POST request field in the form.
When you POST you can access your id variable because your form has an id field with a value. This is a common solution, but one thing to watch out is validating your query parameter because now you allowed people to randomly pass values onto your page - which will be posted back, you can never be sure that people won't pass some malicious values over there.
Another way of doing this - which I'm not recommending but it's a way - is to look into the headers. Because your current solution doesn't have the hidden form field - you can look into the referrer header and your missing query parameter would be there.
You can just do a
console.log(req.headers.referer);
in your /third view and it should have the full previous URL which also contains the parameter you're looking for.
What is the best practice to create unique shareable urls for some text lists users create?
It's a single page website with a content div where users create text lists. Once they click share, how can I store those values inside a shareable url so that another user going to that address loads the same list?
I'm using html, js, jquery, php.
EDIT: as suggested below i'm already saving the lists on a database (firebase), and each have an unique ID, so I'd need to understand how I can create urls with a list id in it, and how to read the url back.
EDIT 2: so this is the code i'm using right now, combining answers from marzelin and the Alchemist Shahed in my other question about my database structure (Firebase how to find child knowing its id but not its parent's id (js)):
//js inside window load function:
const keyOfDynamicHtmlItemRef = new URL(window.location).searchParams.get("share")
if (keyOfDynamicHtmlItemRef) {
var dynamicHtmlListRef = firebase.database().ref('users');
// var dynamicHtmlItemRef = dynamicHtmlListRef.child(keyOfDynamicHtmlItemRef);
// console.log(keyOfDynamicHtmlItemRef);
// dynamicHtmlItemRef.once("value").then(dynamicHtmlSnap => {
// texta.innerHTML = dynamicHtmlSnap.val();
// });
dynamicHtmlListRef.once('value').then((snapshot)=>{
snapshot.forEach(function(data) {
if (data.key == keyOfDynamicHtmlItemRef) {
myVar = data.c;
myContentDiv.innerHTML = myVar;
}
});
});
}
and i'm simply trying to manually write the url in the searchbar as a first step, as https://example.com/?share=<random list id i copied from db>, but it does nothing.
So the way I would to this is I would have the users share click trigger a save to database saving all the dynamically generated content into a table.
One of the table values would be a randomly generated unique identifier of some sort that I would use as a query in the url like https://www.example.org/?share=skd822475
Then when a user visits the site and that query is in the url id use the unique identifier to look up the database and publish the dynamic content back on the page.
I would also put a half life on the database entry's of say no more than 30 days so that it doesn't clog up the db.
Saving data and creating shareable link:
document.querySelector(".share").addEventListener("click" => {
var dynamicHtmlListRef = firebase.database().ref('dynamic_html');
var dynamicHtmlItemRef = dynamicHtmlListRef.push();
dynamicHtmlItemRef.set(userCreatedDynamicHtml);
var keyOfDynamicHtmlItem = dynamicHtmlItemRef.key;
var linkToDynamicHtmlItem = `${window.location}?share=${keyofDynamicHtmlItem}`;
alert(`link: ${linkToDynamicHtmlItem}`)
})
Showing the dynamic HTML based on query parameters:
const keyOfDynamicHtmlItemRef = new URL(window.location).searchParams.get("share")
if (keyOfDynamicHtmlItemRef) {
var dynamicHtmlListRef = firebase.database().ref('dynamic_html');
var dynamicHtmlItemRef = dynamicHtmlListRef.child(keyOfDynamicHtmlItemRef);
keyOfDynamicHtmlItemRef.once("value").then(dynamicHtmlSnap => {
document.querySelector(".dynamic-html-mountpoint").innerHTML = dynamicHtmlSnap.val();
});
}
Let's start with the first question "How to create urls with a list id in it?"
The thing is that to answer this one we need to answer the second question first witch is
"How to read the url back?"
Consider that you have a php page named "draft". when a user visit https://www.example.com/draft?listId=an_id you will get listId using php like so $_GET("listId") and use that value to retrieve the list data and display the page content.
Now coming back to the first question, if the user share the draft like in social media (ex: facebook) then there is no problem because he will share a link and all his followers and any other user can access it easily. but if the user just save the draft then you will have to change the page url dynamically like this window.history.pushState(null, null, '/draft?listId=your_newly_created_id'); and so the user will copy the url and do whatever he wnt with it (sharing it in stackoverflow maybe example using jsfiddle http://jsfiddle.net/F2es9/ (you can change the url to look like this using 'htaccess' file)) at the end I would like to tell you that we don't "create" urls.
Edit
without using php code (or any other server side code). the difference will be in retrieving the data.
instead of using $_GET("listId") you will use new URL(window.location).searchParams.get("listId") to get the list id in javascript then using this value you can retrieve data from firebase and display your content
Is there a way to redirect the user to a certain URL on the basis of what comes out of an XMLHttpRequest()? Here's what I am trying to achieve:
User hits submit, form gets submitted, XMLHttpRequest() fired
Response received from the server, stored in var hr
If hr = abc, show contents of hr
If hr = xyz, redirect user to http://www.something.com
What I am looking for is if there's any predesigned method in either JS or JQ to handle such redirects. I understand redirects can be specified in the <meta> tags in the <header> section of the page but if I did that, how will I be able to add conditions to it? I would have posted a copy of the script I have attempted but can't because right now, I have no idea where to even begin!
In case someone is curious about the scenario, this is a Web-based dictionary/conjugation service. So, on the verb conjugation page, if the user enters a valid verb, the response (i.e. the conjugation tables) is displayed. However, if the user enters a word that's valid but not a verb so it can't be conjugated, I want the user to be automatically redirected to the dictionary page where the entered word's dictionary entry will be displayed. Not sure if I have explained it well enough but please feel free to ask should you have any questions.
Try testing with switch(request.responseText) and call window.location.assign("http://your-url.com"); in the preferred case "xyz"! Alternatively window.open("http://anotherxxxwebsite.com") opens the link in a new browser window.
There's no "predesigned" method, but you can write that logic yourself. Depending on your current API you could either check if the returned value is an URI (or some other designated value instead) an redirect accordingly. Assuming a deferred object returned from jQuery.ajax:
defer.done(function(data, textStatus, jqXHR) {
// assuming a string, but this could really be anthing, e.g.
// an object containing an appropriate attribute, etc.
if (data.indexOf('http') === 0) {
window.open(data);
} else {
// render your stuff
}
});
I have a jobs website with several different job description pages and with 1 application page with a form.
i.e.
/admin-clark -> /application
/sale-rep -> /application
I would like to pre-populate an input field in the form with the id #jobTitle.
I would like to do the following-
Get the previous URL
Store it in local storage
Sanatize url(remove dashes etc)
Use jQuery to fill in the field with id jobTitle
Or is a there a better way of doing this?
This is what I have so far
var pathname = window.location.path.replace(/^\?$/, '').toUpperCase();
localStorage.setItem("pathname ", pathname );
$('#jobTitle').val(pathname);
in many cases(Not in every case) will get you the URL of the last page if they got to the current page by clicking a link using document.referrer; See here
You can also take help from here
I have an Instant Message feature on my site which uses a popup window. When a user makes an IM post, their picture is added to the post. I am able to save on a database query for each IM post (so the popup does not have to query the database to retrieve the user's picture for each post) by retrieving the stored user pic file name from a form (UserPicStorage...a separate query is not required to grab $sql['picture']...it's already present on each of the main pages when these pages load) on each of 5 non-popup, main pages (one page is an exception, see below) of my site as follows:
<form id="UserPicStorage"><input type="hidden" name="UserPic" value="<?=
$sql['picture'] ?>"></form>
I have an About Us page which does not need a database query to load. So to save a query if a user posts an Instant Message while on the About Us, I pass $sql['picture'] to the a href as follows:
About Us
so the popup can retrieve the userpic if there is an IM post while the user is on About Us.
However, the user can use AJAX on one of the 6 main pages to change his/her user picture.
So I can't use this:
About Us
because if the user changes his/her photo, $sql['picture'] (which was valid on page load)
is no longer the current photo. I did a lot of searching, but could find nothing to support
something like the following method:
About Us
I tried this and simply passed the literal string document.forms.UserPicStorage.UserPic.value. So did the following:
About Us
Is there any way to append the input value of a form directly to the a href?
You should just use
About Us
(well, probably you should encode $sql['picture'])
And when you make the AJAX request, update it as a success callback:
ajax.onreadystatechange = function() {
if (ajax.readyState===4 && ajax.status >= 200 && ajax.status < 300) {
/* AJAX successful */
myAnchor.src = "about.php?userpic=" + encodeURIComponent(
document.forms.UserPicStorage.elements.UserPic.value
);
}
};