pass json values across pages - javascript

I have defined a json object as
function getPost()
{
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var v = {
"name": {
"firstname": fname,
"lastname": lname
}
};
}
How can I make this JSON variable v accessible to other pages. I want to pass the JSON data across pages.

You can store data locally within the user's browser using localStorage or SessionStorage(more information) to access your data in all pages.
Take a look at this example:
localStorage.setItem('a', '{ "name" : "test"}');
eval("var myObj = " + localStorage.getItem('a'));
myObj.name; // test

Related

add form data as object into another object

I'm having trouble getting form data into an object in the structure I want. currently it returns in this format:
mainObject = { name1:{}, name2:{}, name3{} }
what I am trying to achieve is
mainObject = { {name1:{}}, {name2:{}}, {name3{}} }
my js:
var users = {};
function formSubmit(){
var name = $("#name").val();
var age = $("#age").val();
var zip = $("#zip").val();
users[name] = {};
users[name].age = age;
users[name].zip = zip;
console.log(users);
};
I have a bin available if that helps, thanks!
https://jsbin.com/bofohabahu/1/edit?html,js,console,output
An object can be seen as a collection of keys and values. An object cannot contain a value (like an object) without also having a key for that value (think about it, how would you access it?).
So that's why { {name1:{}}, {name2:{}}, {name3{}} } isn't possible.
If you don't care about having keys for each of the objects, then may I suggest using an array instead? [ {name1:{}}, {name2:{}}, {name3: {}} ]
this is how you make the name as a key containing the age and zip
var users = {};
function formSubmit(){
var name = $("#name").val();
var age = $("#age").val();
var zip = $("#zip").val();
users[name] = {
age: age,
zip: zip
};
console.log(JSON.stringify(users));
};
try this
https://jsbin.com/vanusapixu/1/edit?html,js,console,output

Sava Data to a variable Place [Firebase]

I want to write some User Data to a variable place. But I don't know how I can tell this to Firebase. The normal save function doesn't work with a variable save location. Like in the example below I want to save the data on a variable save location.
function Writevariabledata(userId,data)
{
firebase.database().ref('user/testdata/' + userId).set({
$userId: data
});
}
this works for me
function Writevariabledata() {
var name = document.getElementById("name");
var firebaseref = firebase.database().ref("user/testdata/" + userId);
var messagetext = {};
messagetext.cat_name = name.value;
firebaseref.push().set(messagetext);
window.alert('Inserted Successfully..');

Javascript / Jquery - How to set a variable name based on a variable

This has been asked a bunch of times before but I'm not grasping it.
In the following..
var variableName = "hello";
How do I make the variable name 'variableName' based on another variable?
PHP Example
$a = 'hello';
$$a = 'hi'; // same as $hello..
echo $hello; // and $hello outputs 'hi'
I specifically need this variable variable to be used for localstorage so it may be syntax that I'm having a problem with.
What I'm Using It For (you can probbaly skip to This Seems To Work)
I want to generate a unique variable name for storing information in local storage. Variable name will be based on the post id of the wordpress post/page which I retrieve with php.
For example we will say the post id is 3333
I add the letters id to the beginning of each post id
So now I have id3333
var postIdNumber = 'id3333';
Then I get 3 other pieces of information that I want to store into local storage about this post (for simplicity I have shown an example output, not the code to get it)
var postURL = 'website.comm/a-wp-post/';
var postTitle = 'A Wordpress Post';
var postThumb = 'website.comm/images/thumb3333.jpg';
Now I want to store this information into local storage
var lsTest = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('lsTest', JSON.stringify(lsTest));
That works fine. Except that I want to be able to store multiple posts into local storage to retrieve later from a 'my favourite posts' page.
So I need a dynamic variable name.
For post ID 3333 I need the variable currently named lsTest to be named id3333
For post ID 4444 I need the variable currently named lsTest to be named id4444
This seems to work (Though I dont fully comprehend it)
solution modified from https://stackoverflow.com/a/5187652/3377049
var variableVariable = {}
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
jQuery('.test-div').text(variableVariable[vv]); // outputs id3333
While this does not..
var variableVariable = {} // also, should this have a ';' ?
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
var variableVariable[vv] = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('variableVariable[vv]', JSON.stringify(variableVariable[vv]));
In PHP I could maybe do something like this.. (for examples sake i'm mixing php variables into JS)
$uv = 'id3333';
$$uv = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('$$uv', JSON.stringify($$uv));
You just need to create an object of objects, keyed off of the unique post id. But then you need to stringify the object before storing it, and parse it when retrieving it.
function saveObject(key, object) {
object = JSON.stringify(object);
window.localStorage.setItem(key, object);
}
function getSavedObject(key) {
var saved = window.localStorage.getItem(key);
if (saved) {
return JSON.parse(saved);
} else {
return null;
}
}
your object:
var lsTest = {
id3333: {
postUrl: postUrl1,
postTitle: postTitle1,
postThumb: postThumb1,
},
id4444: {
postUrl: postUrl2,
postTitle: postTitle2,
postThumb: postThumb2,
}
}
store it:
saveObject('myUniqueSiteName', lsTest);
retrieve it:
var lsTest = getSavedObject('myUniqueSiteName');
adding a new post:
var lsTest = getSavedObject('myUniqueSiteName');
var postId = 'id555';
lsTest[postId] = {
postUrl: postUrl3,
postTitle: postTitle3,
postThumb: postThumb3,
}
saveObject('myUniqueSiteName', lsTest);
Variable variables are not a good idea even in PHP. Just make an array or a hash (which is an object, but it's used as a hash or map, where you can add and delete properties or entries as you please).
var posts = {};
var someId = 3333; //or '3333' if it isn't a number
posts[someId] = {
URL: postURL,
title: postTitle,
thumb: postThumb
};
localStorage.setItem('post' + someId, JSON.stringify(posts[someId]));
A property named "foo" on an object named "bar" can be accessed like so:
bar.foo = 'baz';
console.log(bar.foo);
or like so:
bar['foo'] = 'baz';
console.log(bar['foo']);
Which is the same as:
var name = 'foo';
bar[name] = 'baz';
console.log(bar[name]);
Finally, the global object in JavaScript (which in the browser is window) "holds" the global variables.
var myGlobal = 10;
console.log(window.myGlobal); // logs 10
var globalName = 'foo';
window[globalName] = 'baz';
console.log(foo); //logs 'baz'
Using global variables in general is discouraged. Using them to store posts where the name of the var is the id is highly unorthodox and many JS developers would consider it simply wrong.

insert key=>value pair in PHP from a submitted Javascript object

im trying to figure out how to properly insert key=>value pair to an array using array_unshift
this is my code.
Javascript/AJAX
var array= {};
array['name'] = name;
array['lname'] = lname;
$.ajax ({
type:"POST",
url:"some.php",
data: {array:array},
success: function(html) {}
});
PHP will then receive the array via POST
$array = $_post['array'];
//add additional key=>value pair in the array
array_unshift($array, "['middle']=>test");
return $array;
Im not getting any errors from it, i just dont see the value being printed from the function.
Printed Result:
Object {name: "John", lname: "Smith"}
edit:typo
I don't think you're doing it right...
You can't alter a JavaScript array (it's an object actually) via PHP. However, you can fetch new data and replace the JavaScript object.
Because I'm expecting an object, I might as well use the JSON format - thus use $.getJSON() instead. Note that this is a GET request on default.
var url = 'file.php';
var obj = {
name: name,
lname: lname
};
$.getJSON(url, { data:obj }, function(data) {
// replace object with new content
obj = data;
console.log(obj);
});
As for your PHP code:
// get data (remember we're using a GET request)
$data = $_GET['data'];
// add an index
$data['middle'] = 'test';
// echo data in JSON format
echo json_encode($data);
// not var array= {};
var person = {}
person['name'] = name;
person['lname'] = lname;
Rename the person to array like
var array= {};
array['name'] = name;
array['lname'] = lname;
$.ajax ({
type:"POST",
url:"some.php",
data: {array:array},
success: function(html) {}
});
Or send the person array as array
data: {array:person},
EDIT :.Simple try like
$array['middle'] = 'test';

JSON parsing with JsonResult and JavaScript

Environment: ASP.net MVC:
Given anonymous structure as such:
var test = new {
name = "me",
age = "100"
};
that then gets parsed as
result = Json(test)
data = result.Data // Comes back with { name = "me", age = "100" }
Which then gets successfully passed into a JS function, how do I go about using that as a JSON object, so that I can do something like
function(data) // Where data = { name = "me", age = "100" } or similar
{
var name = data.name // "me"
}
Try
var object = eval('(' + data + ')');
then you should be able to do object.name.
The JSON is invalid, it should be
{
"name" : "me",
"age" : "100"
}
And new {..} doesn't do anything meaningful -- the object literal is alone sufficient.

Categories

Resources