Get a var value from specific webpage - javascript

For example the webpage : www.test.com/a123 has a var called Value that stores quantity of products
the webpage www.test.com/b123 has the same variable also.
On the console of each page, I can call the variable and get their values, but there is some way to get this values without being on that specific page?
I need to get the value table from this pages having only to specify which page I would like.
Something like :
document.getElementByClassName('tamanho__item_pdpjs-tamanho__item_pdp')[5]
But for variables referencing from which page to get

Use the localStorage property of JS.
localStorage.setItem("a123", "value");
// Retrieve on b123 page
document.getElementById("result").innerHTML = localStorage.getItem("a123");

It sounds like you might be struggling to understand where state should live in your application.
The example you mentioned in the comments, Nike and the "SKUsSizes" is likely getting that data from a backend API. Not by accessing a variable on another "web page".
This would be easier to explain if you had a more concrete example but say you need the page b123 to know how many products there are for a123.
The b123 page would make an HTTP request to your backend API requesting details about a123 which may include the number of products.
This data would be stored in a database.
On the other hand, if the product count is coming from some user action that happens over on a123 and you want to see that state change on page b123 then using local storage as suggested in another answer might be one way to solve that problem.
Although it's probably a better idea to use a framework like React, Vue or Angular and use the state management options they have instead of trying to figure out how to do this from scratch.

Related

What is the best way to manipulate an API AJAX JSON response and pass it to another page?

I think I have a tough one for you guys. Or at least it's been tough for me. I've been searching for the best way to do this in Stack Overflow and everyone that has asked has been given a different response.
I have this code that is accessing an API and calling a maintenance list of all the vehicles in a fleet.
function getMaintenanceList() {
var settings = {
"url": "API URL HERE",
"method": "GET",
"timeout": 0,
"headers": {
"Authorization": "Bearer token here"
},
};
$.ajax(settings).done(function (response) {
// The response the API sends is a JSON object.
// It is an array.
var jsonMaintenance = response;
var parsedJson = JSON.stringify(jsonMaintenance);
//Left over code from when I was trying to
//pass the data directly into the other page
// I was unable to do so
//return jsonMaintenance;
//Left over code from when this was in a PHP file
//and I was posting the stringified response to the page
// for testing purpose
//I had to disable CORS in Google Chrome to test the response out
//console.log(jsonMaintenance);
//document.getElementById("main").innerHTML = parsedJson;
});
};
The code above works well. What I was attempting to do here was write the stringified response to a file. Save that file in the server. Call it from another page using JavaScript and save it as an object in JavaScript, parse it using JSON.parse(), and then pull the required information.
Here's an explanation as to why I'm trying to do it this way. When I call the maintenance list from the API, I'm getting the entire maintenance list from the API, but I need to be able to display only parts of the information from the list.
On one page, we'll call it vehicle-list.php, on it I have a list of all the vehicles in our fleet. They all have unit numbers assigned to them. When I click on a unit number on this page it'll take me to another page which has more information on the vehicle such as the VIN number, license plate, etc. we'll call this page vehicle-info.php. We're using this page for all the vehicles' information, in other words, when we click on different unit numbers on vehicle-list.php it'll always take us to vehicle-info.php. We're only updating the DOM when we go to the page.
I only want to include the information specific to each vehicle unit in the page along with the other info in the DOM. And I only want to call the info from the API once as I am limited to a certain amount of calls for that API. This is why I am attempting to do it this way.
I will say that what I originally wanted to do was get this JSON response once every 24 hours by using a function in vehicle-list.php save the reponse as a variable as seen above var jsonMaintenance = response; and then just access certain parts of the array every time a unit number is clicked. However, I have been unable to access the variable in any other page. I've written many test files attempting to call jsonMaintenance without success so I've been trying to to just save it as a text file to the server and I haven't been able to figure that out either.
After explaining all of the above. My questions are these:
How do I best manipulate this data to accomplish what I want to accomplish? What would be the best standard? Is the above code even the right way to call the data for what I'm trying to do?
There doesn't seem to be a set standard on accomplishing any of this when I search on Stack Overflow. I'd like to be as efficient as possible.
Thank you for your time.
there is a lot of ways how you pass your data through your website after getting it in from an api call, the best approach is to store these information in a database and call it back in which ever way you want, you can do that as far as you are using php, you can store it to sql or to access, if you don't want to store these information in a database like in sql or access, then best way is to store it to localStorage and call it back whenever you want.
I will show you briefly how you can do that, if you want better explanation post an example of your returned data.
to store an item in localstorage use,
localStorage.setItem('key', 'value');
to call an item back from localstorage use,
var somevar = localStorage.getItem('key')
to remove specific item from localstorage use,
localStorage.removeItem('key')
to clear all items saved to localstorage use,
localStorage.clear()
be aware storing the data to localStorage is only at the station you are using
I would do it somehow like this.
Call the maintenance list from the API with the server side language of your choice which seems to be PHP in your case. Lets say the script is called: get-list.php. This can be triggered by a cron job running get-list.php in intervals limited to the certain amount of calls that you are allowed to do for that API. Or if you are not able to create cron jobs then trigger the same get-list.php with an AJAX-call (eg jQuery.get('sld.tld/get-list.php') - in this case get-list.php have to figure out if its the right time to call the API or not).
Now that you have the data you can prepare it as you want and store it as a JSON-string in a text file or database of your choice. If I get you right you have a specific dataset for each vehicle, which have to be identified by an id (you named it "unit number") so your JSON would look kind of: {"unit1": { property1: "val1", property2: "val2" }, "unit2": { property1: "valXYZ", property2: "valABC" }} or alike.
Now when you link to vehicle-info.php from vehicle-list.php, you do it like so: ancor or similar as well. Of course you can also grab the data with AJAX, its just important to deliver vehicle-info.php the corresponding unit number (or id - better to say) and you are good to go.
vehicle-info.php now have all there is to render the page, which is the complete data set stored in text file or data base and the id (unit number) to know which part of the whole dataset to extract.
I wanted to give you this different approach because in my experience this should work out just so much better. If you are working server side (eg PHP) you have write permissions which is not the case for JavaScript-client side. And also performance is not so much of an issue. For instance its not an issue if you have heavy manipulating on the data set at the get-list.php-level. It can run for minutes and once its done it stores the ready-to-use-data making it staticly available without any further impact on performance.
Hope it helps!
If i ran into a similiar problem i would just store the data in a database of my own and call it from there, considering you are only (willing/abe/allowed) to request the data from the API very rarely but need to operate on the data quite frequently (whenever someone clicks on a specific vehice on your applicaiton) this seems like the best course of action.
So rather than querying the data on client side, I'd call it from server, store it on server and and have the client operate on that data.

Updating a page from another page whats the best and easy way?

So my problem is if there are 2 pages for example. PricePage.html has the list of prices and UpdatePrice.html has the input text and etc. If I use the UpdatePrice.html to change the prices of PricePage.html, whats the best way should I use? via php to php or via php to mysql or theres even an easier way to do it. Sorry for my bad english.
Don't think of it as updating one page from another. Think of it as two separate pages that both interact with a database.
Store your price information in a database (such as MySQL).
Have PricePage query the database to get the price information, and generate the HTML to display it. (This means the page can't be just static HTML; it needs to use something like PHP that can generate HTML dynamically.)
Have the UpdatePrice page store the new price information in the database. (This doesn't directly modify PricePage, but next time someone views that page, it'll retrieve and display the latest information in the database.)
If you want the data to get updated in real time like once the data is updated it gets reflected on other page,then you can use sockets which will listen for the update event and once the event is fired the contents will get updated.
One of the most popular framework for this business is socket.io.
I would suggest you to have a look to it.The benefit for using this approach is that you save a lot of resource and the functions work in realtime.

Keeping a global value in the next page [duplicate]

I want to send some data from one HTML page to another. I am sending the data through the query parameters like http://localhost/project/index.html?status=exist. The problem with this method is that data remains in the URL. Is there any other method to send the data across HTML pages using JavaScript or jquery.
why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.
To store values for a session:
sessionStorage.setItem('label', 'value')
sessionStorage.getItem('label')
or more permanently:
localStorage.setItem('label', 'value')
localStorage.getItem('label')
So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..
I know this is an old post, but figured I'd share my two cents. #Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:
var val = sessionStorage.myValue
in place of getItem and
sessionStorage.myValue = 'value'
in place of setItem.
Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:
sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags
like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)
I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.
But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.
These two links might help you, it shows the example via Node backend, but you get the point how it works:
Link 1
And, of course, the CORS spec:
Link 2
~Cheers

Host multiple pages in one page

I want to know How to have pages like YouTube's watch page, http://www.youtube.com/watch?v=abc123 ?
I need it to do the following:
when just going to the main file watch.php, I want it to :show certain code for when they go to that page,
when they go to example /watch?v=abc123, I want it to : show different code only for that link.
I also don't want the main watch.php page to be all cluttered up with code as I'll be at nearly 50+ times using these ?v= I heard you can use Databases but I don't know.
Just whichever ones the best and easiest to make also please try and get it not to be clustered up and easy for me to edit. Thank you
Please Edit this if needed. My website and page i'll be using
This is only available via php. Using $_GET method.
Basically, the link is only www.mysite.com/watch.php. But if you use watch.php?v=123 then the $_GET['v'] will have the value of 123.
For more info: http://www.php.net/manual/en/reserved.variables.get.php
EDIT: basically your step would be like this
Set up a database. This depends on where you host your site. But most host service allow you to create and manage database.
Create a table with values you wanted to store.
Get the "v" value through $_GET
Run queries to connect to the database, and get the stored value. Ue echo to print it out on HTML

HTTP cookie between two HTML pages

I have two HTML pages. After entering few inputs users will be redirected from first page to second page. Before redirecting the user to second HTML page(using window.location="new HTML URL"), I persist few of the user inputs in cookie using document.cookie DOM API.
When I am in the second HTML page, I could not retrieve the value from this cookie. I think since document object would have changed in the new HTML page, my cookie values become inaccessible.
Can someone tell me: how do I retrieve the value from a cookie persisted by one javascript in one HTML page in other HTML page i.e cookie written by HTML A's javascript in HTML B's javascript?
I don't have any server-side code, so I could not take advantage of server-side logic. Also I am not supposed to pass the values in URL. So I need a solution on plain javascript and HTML.
If some one has a better solution please let me know. Thanks
try to use localStorage instead of cookies,
// set your values in the first page
localStorage.setItem('itemKey', 'values');
// on the second page, retrieve them
var values = localStorage.getItem('itemKey');
you can use a jStorage plugin for cross browser behaviour.
also refer to this question for storing objects instead of strings
JAAulde is on point with his answer.
For what the OP is trying to do something like PHP would be great, in that case I wouldn't bother with cookies in order to just pass data between two pages, that's just silly. However, if true persistence was needed and the data requirements were simple cookies would be the way to go even while using a language such as PHP.
Those are rather draconian constraints, is this a class project? That said there aren't any other ways to do what you're attempting, save for an ugly and highly insecure hack of the DOM.

Categories

Resources