Javascript get php variable from other website [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make an HTML5 and PHP based web application.The objective of the application would be to fetch the data from another PHP based website and use that data within my application.How do I do it?

The above answer is partially incorrect; PHP doesn't have access to localStorage. However, you can use cookies to achieve what you want - although you CAN use JSON with AJAX, but I think cookies are easier. Since you're very new to JavaScript, I'll show you an example.
Let's assume I'm making a very insecure login system. Let's say:
$name = "John"; //set the name to John.
Now, to let JavaScript access this name variable, we'd have to use cookies. You can use them like so:
$username = "John"; //set the name to John.
setcookie("username", $username, time()+86400);
The setcookie method take the paramaters:
setcookie(name, value, expire, path, domain);
So in our case, it sets the name to username, the value to the user's name, the expiry date from 1 hour from now (60*60*24). This cookie will expire in one day.
Now, once this is done, make sure this function is added in your scripts.
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
Please credit the original author at this topic for the code above.
Then, to get the cookie, simply do:
name = getCookie(username);
I hope I helped!

I think you can use "cookies" or "localStorage"
http://www.w3schools.com/js/js_cookies.asp
http://www.w3schools.com/html/html5_webstorage.asp

Related

How set expiration date to an localStoarge item in Javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I am working on making premium access to my website. While doing so I want the login that had set the localStorage item as 1 to expire and get deleted after a month. I searched the web, but got confused as I am still learning JavaScript and jQuery. Can you help me out in setting expiration to the localStorage item? Here's the line of code that is setting the localStorage:
localStorage.setItem('ispremium', '1');
And my website is on Blogger platform, if that matters!
You can set the actual value as the first time user joined and the time to expire. And whenever the user opens again the website, you need to check that expiration date. But this is extremely unsecure, you shouldn't do that for sessions. Just to answer to your question, you can do the following:
const NAMESPACE = 'MY_ID';
const TIMESTAMP_MODEL = {
initial: null,
expiresOn: null
};
const TIMESTAMP = Date.now();
if (!JSON.parse(localStorage.getItem(NAMESPACE))) {
// when the user access your website for the first time, set the initial and expiresOn values:
localStorage.setItem(NAMESPACE, JSON.stringify({
initial: TIMESTAMP,
expiresOn: TIMESTAMP + 1000*60*60*24*30 // 1month in ms
}));
} else {
// then, when user access the website again, check the expiresOn, it it's value is bigger than current date
const EXPIRE_DATE = JSON.parse(localStorage.getItem(NAMESPACE)).expiresOn;
if (Date.now() > EXPIRE_DATE) {
console.log('session expired');
}
}
Normally this would be solved on the server side. The localStorage may be cleared if a user selects "clear browsing history" on some browsers. It may not be available across sessions if the user works with multiple browsers or incognito mode. Other than that someone with a bit of technical knowledge can insert the "ispremium" flag easily into his localStorage to gain access to your premium feature.
If you still want to solve this via client, you could store a timestamp instead of a boolean flag and check if the current time is still in the validity range. LocalStorage itself doesn't let you set an expiration date on entries.

saving and loading variables [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I made a game and its a type of game which takes hours to complete. Its a browser game. How can I store variables ( need to store 20-40 variables ) and load them using cookies ? ( so that I can access them even if browser is closed and opened again ). Please, I need help.
You would be better off using localStorage and not cookies. Pretty simple if you just do something like
//The defaults the user starts with
var _defaults = {
level : 1,
userName : null,
life : 100
};
//getting previous values from storage
var savedDetails = localStorage.settings ? JSON.parse(localStorage.settings) : {};
var settings = $.extend({},_defaults, savedDetails);
if(!settings.userName) {
//set username and save
settings.userName = window.prompt("name");
} else {
//username is there so say hi
console.log("Welcome back " + settings.userName);
}
//Save this back to the local storage since we made changes
localStorage.settings = JSON.stringify(settings);

What is the best practice to grab any url params from the URL? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm curious, what is the best practice to grab any url params from the URL ?
Example
http://localhost:8080/BIM/teacher/reports/chapter-quiz/assignment?assessmentId=206a9246&classroomId=722bfadb
The goal is to grab the value of :
assessmentId
classroomId
1. Make a parseUrl function
function parseUrl(url) {
var urlParamSplit = url.split("?");
if (urlParamSplit.length !== 2) {
return "InvalidUrlNoParamsSet";
}
var paramsList = urlParamSplit[1].split("&");
if (paramsList.length < 1) {
return "InvalidUrlNoParamsFound";
}
var paramsObj = {};
paramsList.forEach(function(item) {
var keyValueArray = item.split("=");
paramsObj[keyValueArray[0]] = keyValueArray[1];
});
return paramsObj;
}
var params = parseUrl(href);
console.log(params.assessmentId) // 206a9246
console.log(params.classroomId) // 722bfadb
2. Grab it from hidden input
Throw this in the HTML page
<input id="assessmentId" type="hidden" value="<c:out escapeXml="true" value="${param.assessmentId}" />" />
<input id="classroomId" type="hidden" value="<c:out escapeXml="true" value="${param.classroomId}" />" />
console.log($("#assessmentId").val()) // 206a9246
console.log($("#classroomId").val()) // 722bfadb
So far, I've tried 2 approaches,they both give me the data I wanted, but I'm not sure which one, I should use.
If there's other approach that I should consider that please kindly suggest.
I think the first method is more powerful if you have several parameters to grab from the url, or if you have some parameters that generate dynamicly instead of the second method in this case (dynamic params) you have to loop and create inputs also dynamicly.
Short : use the first method if you have several parameters to grap or dynamicly generated parameter, use the second if you have less parameters (static & controlables parameters).
For more solutions/ideas this link & this one may help you.
if the http request is going to change/add something in the server you should use POST request(not in your case)
if the http request is going to grab something using some data given by the client you should use GET query parameter to pass data to the server

Extra tags on the end of a URL for different pages [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Hello I really want to learn how to do something like this. If you go to a page for example it says http://example.net/search.html?catagory=food&includelevelone=true. I do not have access to php so it can only be HTML and Javascript/jQuery. Thanks in advance!
The part of the URL that is from the questionmark onwards is called a query string.
Here is a pure JavaScript function to parse the query string to obtain particular values:
function querystring(key)
{
var filter;
var value;
key = key.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
filter = new RegExp('[\\?&]' + key + '=([^&#]*)');
value = filter.exec(window.location.search);
if(value == null)
{
return '';
}
else
{
return decodeURIComponent(value[1].replace(/\+/g, ' '));
}
}
You just pass in the query string key name you're interested in (as a string) and you get the value back (also as a string.) An example of how you could use the function:
alert('Category = ' + querystring('catagory'));
Everything behind the questionmark is a url parameter. every word left of an equal sign is the name of the parameter, everything right of an equal sign is the corresponding value. The name-value-pairs are divided by &-signs
Here are two pages i quickly googled that are about getting these parameters in JavaScript (wich is really not that hard):
http://code-tricks.com/get-url-parameters-using-javascript
http://ziemecki.net/content/javascript-parsing-url-parameters

Fetch two control values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have two controls whos code are run time rendered as below:
ctl00_PlaceHolderMain_SPWebPartManager_g_3c1ba10a_23ec_4ab5_b303_18f8bd7ee7e7_ctl00_gdvItinerary_ctl03_txtTravelDate
ctl00_PlaceHolderMain_SPWebPartManager_g_3c1ba10a_23ec_4ab5_b303_18f8bd7ee7e7_ctl00_gdvItinerary_ctl04_txtTravelDate
How do I fetch the values of above two controls using jQuery?
In asp.net , your control's id is changed at runtime.
If you id was mycontrol, it would be changed to blahblahblahmycontrol (id will be there at the end) at client side.
So,
if you have an asp.net control (textbox), like below,
<asp:TextBox runat='server' id='mytxtbox'></asp:TextBox>
you can do,
$("input[id$='mytxtbox']").val();
It selects all input tags ending with _mytxtbox
or you can do something like this if the javascript is on the same .aspx file
$('#<%=mytxtbox.ClientID %>').val()
If you are using asp.net 4.0,
You can add ClientMode property to Static
<asp:TextBox ID="mytxtbox" runat="server" ClientIDMode="Static"></asp:TextBox>
This will retain the id of TextBox to mytxtbox
So, you can do,
$('#mytxtbox').val();
Yes, you can also, see the source code and use the converted id like this,
var txtboxValue = $('#ctl00_PlaceHolderMain_SPWebPartManager_g_3c1ba10a_23ec_4ab5_b303_18f8bd7ee7‌​e7_ctl00_gdvItinerary_ctl03_txtTravelDate').val();
But its not recommended.
Simple - use .val():
var firstValue = $('#ctl00_PlaceHolderMain_SPWebPartManager_g_3c1ba10a_23ec_4ab5_b303_18f8bd7ee7‌​e7_ctl00_gdvItinerary_ctl03_txtTravelDate').val();
var secondValue = $('#ctl00_PlaceHolderMain_SPWebPartManager_g_3c1ba10a_23ec_4ab5_b303_18f8bd7ee7e7_ctl00_gdvItinerary_ctl04_txtTravelDate').val();
You should seriously consider using shorted ids. From these ids alone, I have absolutely no idea what the value represents.
You can make it more readable with:
var baseID = "#ctl00_PlaceHolderMain_SPWebPartManager_g_3c1ba10a_23ec_4ab5_b303_18f8bd7ee7‌​e7_ctl00_gdvItinerary_";
var firstValue = $(baseID + 'ctl03_txtTravelDate').val();
var secondValue = $(baseID + 'ctl04_txtTravelDate').val();

Categories

Resources