what I need
I need to toggle image on click.
like if user select favorite choice & then it mark unfavorite image is altered and data is deleted from localstoarge.
html code
<div style="display:block; float:right; width:auto; color:#7c7c7c;">
</div>
js code
function favaorite(sess_id,name,city,country,event_url,pointer){
var eventData;
//is anything in localstorage?
if (localStorage.getItem('eventData') === null) {
eventData = [];
} else {
// Parse the serialized data back into an array of objects
eventData = JSON.parse(localStorage.getItem('eventData'));
//alert(eventData);
$.each(eventData, function(key, value){
//console.log(value);
var imageUrl='http://im.gifbt.com/images/star1_phonehover.png';
//var imageUrl='http://im.gifbt.com/images/star1_phone.png';
$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
//$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
});
}
var details={};
details.sess_id=sess_id;
details.name=name;
details.city=city;
details.country=country;
details.event_url=event_url;
// Push the new data (whether it be an object or anything else) onto the array
eventData.push(details);
// Alert the array value
//alert(eventData); // Should be something like [Object array]
// Re-serialize the array back into a string and store it in localStorage
var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
}
problem
I'm new in localstorage I need to know how could I delete data from json string.
I have implemented add to favorite now I need to mark unfavorite.
data is stored:
[{
"sess_id":182104,
"name":"AUTOMECH FORMULA",
"city":"Cairo",
"country":"Egypt",
"event_url":"automech-formula"
},]
To delete data from localstorage you use localStorage.removeItem('itemNam')
example
localStorage.setItem('name','hello');
to delete the name item from the localStorage you use
localStorage.removeItem('name');
BUT IF YOUR QUESTION IS HOW TO DELETE DATA FROM JSON OBJECT THEN YOU HAVE TWO METHODS
1: changing the original json object
delete originalJson.attributeName
originalJson = {name:'myname',age:30};//our object to test with
example :
delete originalJson.age //in this case originalJson.age is no more available
2: don't change the original object and make another copy instead
originalJson2 = JSON.stringify(originalJson);
originalJson2 = JSON.parse(originalJson2);
delete originalJson2.age //originalJson.age is available but originalJson2.age is not available
here is the : jsfiddle
let assume that sess_id is your unique id for events
function unfavorite(sess_id){
var eventData = localStorage.getItem('eventData');
//is anything in localstorage?
if (localStorage.getItem('eventData') === null) {
console.log('invalid event');
}
eventData = JSON.parse(eventData);
// Keep all without the one with specified sess_id
$.grep(eventData, function(value) {
return value.sess_id != sess_id;
});
var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
}
Related
I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.
This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?
I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).
Here's what I have so far:
HTML for textbox (page 1):
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />
</div>
JS on page 1:
$('#sales_order_form_button').click(function() {
let table_info = [];
$('input[type=checkbox]').each(
function(index, value) {
if($(this).is(':checked')) {
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
}
);
}
});
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
});
JS on page 2:
// Helper function
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
for(let i = 0; i < data_from_page_1.length; i++){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue);
$('#output_table').append(row);
}
// code to sum CPC column
var sum1 = 0;
$("#output_table tr > td:nth-child(2)").each(
(_,el) => sum1 += Number($(el).text()) || 0
);
$("#sum1").text(sum1);
//datetime stamp
var dt = new Date();
document.getElementById("datetime").innerHTML = dt.toLocaleString();
Output HTML table (page 2):
<table id="output_table">
<tr>
<th>Name</th>
<th>Value</th>
<th>Number of Clicks</th>
</tr>
<tfoot>
<tr>
<th id="total" colspan="1">Total CPC:</th>
<td id="sum1"></td>
</tr>
</tfoot>
</table>
As stated in the #Manu Varghese comment, the way to go would be using sessionStorage or localStorage.
First, let's differentiate both. According to the Stack Overflow question "HTML5 Local storage vs Session Storage", we have the following answer:
localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.
That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.
Considering they are used the same way and you must to choose between what better fits your case, I will proceed using sessionStorage.
For that, in the first page you must use:
sessionStorage.setItem("key", "value")
You may set the item right when you perceives a change, like in the input 'blur' event.
and when you land in the second page (right when jQuery calls its start event), you will retrieve your data using:
sessionStorage.getItem("key")
Take in mind that localStorage/sessionStorage can support a limited amount of data. Even if that limit is way bigger than URL, most browsers will store only 2.5MB to 10MB per origin, according to the browser implementation (you may test by yourself in the link recommended in MDN (Mozilla Development Network), http://dev-test.nemikor.com/web-storage/support-test/).
Also, you may want to avoid storing sensitive data in the storages, due to some some discussions about security, which seems not to be a complaint here.
Implementation in the given case
Your code can be modified in three steps:
Change the way you save the data to use the storage
Creates a JSON of an object containing the array, instead the make the JSON using the array itself. Then you can add more fields.
Load the JSON object and its fields (the array and the number).
Step 1 - Changing to sessionStorage
Just now you have your Javascript on page 1 creating an array of data and stringifying that data to a JSON string.
If you want to use the storage rather than the URL for all the data, just change these lines of code from:
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
to the code that will save the data into a (local/session)Storage:
let jsonStr=JSON.stringify(table_info); // converts to JSON string
sessionStorage.setItem("oldData", jsonStr); // save to storage
window.location = "page2.html"; // navigate to other page
Notice that the storage can receive any string, but only strings, then we can remove the btoa function, but we must keep the stringify.
Step 2 -- Adding more data to save
Now you have one JSON that is an array of items. But what do you want is to include one more field, parallel to this array. Of course, you can't include it in the array, as it is a different thing. So, what we must to do is to create a JSON object which has a number field AND the array field itself.
Your function to create the array is all ok, then we will use the same "table_data" as the array and include it to a new JSON object:
let table_data = []; // the array you have
$('input[type=checkbox]').each(
... rest of code ...
); // the function that creates the array (I abbreviated it here)
// Creates an object with an array and a number
let jsonObj = {
table_data: table_data,
number_of_clicks: theNumberYouHave/* your variable with the number here */
};
// This is the bit above with CHANGES into variable names
// Instead of "table_data", now we save "jsonObj"
let jsonStr=JSON.stringify(jsonObj); // converts the "jsonObj" to a JSON string
sessionStorage.setItem("oldData", jsonStr);
window.location = "page2.html";
Remember to change "theNumberYouHave" to whatever your variable with the number is called. The you will append the number as a field of the JSON object.
In other words, this simply will create an structure like that:
{
number_of_clicks: 5216,
table_data: [
{ name: "...", value: "..."},
{ name: "...", value: "..."},
{ name: "...", value: "..."},
...
]
}
See? Your table_data is still there, but with a new sibling (number_of_clicks) inside an object.
Step 3 -- Loading data from page 1
For now, you have these two lines of code in page 2 to read data from page 1:
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
What do you need there, is to simply replace the getUrlParameter function to read from the storage, and remove the atob function to reflect the changes we made in page 1, this way:
let jsonObj = sessionStorage.getItem("oldData"); // reads the string
let data_from_page_1 = JSON.parse(jsonObj); // parse the JSON string
let table_data = data_from_page_1.table_data; // grab the table data
let number_of_clicks = data_from_page_1.number_of_clicks; // grab the number
Now you are free to use the variable "table_data" like you did, and to use the "number_of_clicks" in the way you want to use it. It is the number passed from page 1, then you may set it to your table cell.
You have it with the unique ID "sum1", the you may just:
$("#sum1").text(number_of_clicks);
And you are done!
I highly recommend localStorage and sessionStorage to be used, as per this and this
Page 1 code full source
$('#next_page_button').click(function(){
let table_info = [];
// Do for checkboxes
$('.campaignstrategy input[type=checkbox]').each(
function(index, value){
if($(this).is(':checked')){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
type: 'checkbox'
}
);
}
});
$('.campaignstrategy input[type=text]').each(
function(index, value){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
type: 'text'
}
);
});
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
});
Page 2 Code full source
// Helper function
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
// clear table
$('#output_table').html("");
// generator checboxes
for(let i=0;i<data_from_page_1.length;i++){
if(data_from_page_1[i].type == "checkbox"){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
let recordCount = $("<td></td>").text("");
row.append(recordName, recordValue, recordCount); // not used but needed
$('#output_table').append(row);
}
}
// generate textboxes
for(let i=0;i<data_from_page_1.length;i++){
if(data_from_page_1[i].type == "text"){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text("");
let recordValue = $("<td></td>").text("");
let recordCount = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue, recordCount);
$('#output_table').append(row);
}
}
ANSWER:
What would be the best way to approach this?
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session
Hello I currently have a script where I append some data into a table then I type into a input and press the add button and that saves all the cells in that table as whatever you typed into the taskName input.
It gets set as localstorage and pops up in two selects one on another html page and one on the html page that it was made in.
the script works well and Im able to call the cells depending on which one I select. The only problem is that I cant delete the task. I want to be able to select the task in the html select and then have it append all the cells into the html page where I can delete all the cells and after I do It removes the task from the localStorage or other words just deletes it completely here is my html code:
<div id="taskContainer">
<table id="items-table">
<!--<caption>Task</caption>-->
<tr>
<th>Item</th>
<th>Size</th>
<th colspan="3">Options</th>
</table>
</div>
<label for="loadTask">Load Task:</label>
<label for="taskName">Task Name:</label>
<select id="loadTask">
<option></option>
</select>
<input type="text" id="taskName"></input>
<button type="submit" id="addTask">Add</button>
and here is my JS:
$(function() {
loadAllTasks();
$("#addTask").click(function() {
let cells = Array.prototype.map.call(document.getElementById("items-table").rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
// create task object from cells
var task = { cells: cells };
// set name property of the task
task.Name = $("#taskName").val();
// call save method using the new task object
saveTaskInStorage(task);
});
});
function saveTaskInStorage(task) {
// Get stored object from localStorage
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof (savedTasks) !== "object")
savedTasks = {};
// Set the new or exists task by the task name on savedTasks object
savedTasks[task.Name] = task;
// Stringify the savedTasks and store in localStorage
localStorage.setItem('tasks', JSON.stringify(savedTasks));
alert("Task has been Added");
}
function loadAllTasks() {
// Get all saved tasks from storage and parse json string to javascript object
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof (savedTasks) !== "object")
return;
// Get all property name of savedTasks object (here it means task names)
for (var taskName in savedTasks){
$("#loadTask").append('<option>' + taskName + '</option>')
}
}
function loadTaskFromStorage1(taskName) {
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// Return the task by its name (property name on savedTasks object)
return savedTasks[taskName];
}
var tasky = loadTaskFromStorage1($("#loadTask").val());
$("#items-table").append(tasky.cells);
if ((tasky.cells) = "") {
delete savedTask[taskName]
}
as you can see at the very bottom I have tried to do what I wanted but it didn't work. I changed up to task(y) and loadTaskFromStorage(1) because I already have these functions called in the other html page as (task =) and (loadTaskFromStorage) and they work perfectly fine.
When I try and run the very bottom script it does not recognize the task and says that it is undefined. Am I not able to call localStorage in the same file as I set it? or is there something else I am missing.
I have html code and JS that I missed out its just the inputs and when I press the button it ads there val(); into the table
I want to be able to make tasks and delete them easily.
update:
I added the loadTasksFrom Storage function outside of the function where the task is created then I made a test button the see if that would work:
$(function() {
$("#test-add").click(function() {
var task = loadTaskFromStorage1($("#loadTask").val());
$("#items-table").append(task.cells);
})
})
when I ran this I got this error:
html.replace is not a function
that pointed to this line:
$("#items-table").append(task.cells);
but when I changed this line to:
alert(task.cells);
I got it to actually alert the cells in the task Which has never happend before so that is huge progress!
the only thing I need to solve now is:
How to get it to append into the table
Be able to add the task into the table just by changing the select (not by clicking button)
be able to delete the task completely from all the selects when I delete it with the small delete buttons that each task gets added with.
another update:
I am able to append task.cells[1][0] with stuff like that but I cant just do task.cells I also dont want to append the so.. How would I append row by row with each X button that is added into each table row something like
.append(task.cells[1][0], task.cells[1][1], task.cells[1][2] etc...
this code above just adds in each cell eight beside each other it doesnt add in the cell under its specific table header. How would I do that.
I appreciate anyone taking the time out of there day to help me out.
With a few code corrections, the code is running without error, yet I am unsure if it is working as intended.
Example: https://jsfiddle.net/Twisty/h901jryt/
JavaScript
$(function() {
loadAllTasks();
$("#addTask").click(function() {
let cells = Array.prototype.map.call($("#items-table")[0].rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
// create task object from cells
var task = {
cells: cells
};
// set name property of the task
task.Name = $("#taskName").val();
// call save method using the new task object
saveTaskInStorage(task);
});
function saveTaskInStorage(task) {
// Get stored object from localStorage
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof(savedTasks) !== "object")
savedTasks = {};
// Set the new or exists task by the task name on savedTasks object
savedTasks[task.Name] = task;
// Stringify the savedTasks and store in localStorage
localStorage.setItem('tasks', JSON.stringify(savedTasks));
alert("Task has been Added");
}
function loadAllTasks() {
// Get all saved tasks from storage and parse json string to javascript object
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof(savedTasks) !== "object")
return;
// Get all property name of savedTasks object (here it means task names)
for (var taskName in savedTasks) {
$("#loadTask").append('<option>' + taskName + '</option>')
}
}
function loadTaskFromStorage1(taskName) {
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// Return the task by its name (property name on savedTasks object)
return savedTasks[taskName];
}
var tasky = loadTaskFromStorage1($("#loadTask").val());
$("#items-table").append(tasky.cells);
$.each(tasky.cells, function(k, v) {
if (v == "") {
delete tasky.cells[k];
}
});
});
In your click function, I update some of the JavaScript code to jQuery. Simply for consistency.
In regards to the code you attempted, I used this as a replacement:
var tasky = loadTaskFromStorage1($("#loadTask").val());
$("#items-table").append(tasky.cells);
$.each(tasky.cells, function(k, v) {
if (v == "") {
delete tasky.cells[k];
}
});
The object tasky is populated with elements, one being cells that is an array of Strings. I assumed you were looking for empty cells. the $.each() is a good way to iterate these. See More: http://api.jquery.com/jquery.each/
The function will run and receive k as the Key and v as the Value from each array element. So for example, if tasky.cells was assigned the following Array:
var tasks = [
"Wake Up",
"Eat Breakfast",
"Help Mom",
"Drive to Work"
"",
"Go to Bed"
];
You would have an array called tasks with 6 keys: 0,1,2,3,4,5; and 6 elements. Using something like:
$.each(tasks, function(k, v){
$("#results").append(k + ": " + v + "<br />");
});
We would see resulting HTML like:
0: Wake Up<br />
1: Eat Breakfast<br />
2: Help Mom<br />
3: Drive to Work<br />
4: <br />
5: Go to Bed
We can use this key value to manipulate the array. To fully remove the element, you might want to consider .splice() versus delete.
$.each(tasks, function(k, v) {
if (v == "") {
tasky.cells.splice(k, 1);
}
});
If we have the above data and perform this operation, the resulting array wil lbe:
[
"Wake Up",
"Eat Breakfast",
"Help Mom",
"Drive to Work"
"Go to Bed"
];
This will also have a re-indexed set of keys. See more: Deleting array elements in JavaScript - delete vs splice
Hope that helps.
In local storage I have an object named favourites and it contains this..
"{
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
}"
How can I delete an object based on its ID (id3333 & id4444 for examples)
I have tried the following along with some other voodoo..
localStorage.removeItem('id3333'); // no errors, no removal
localStorage.removeItem('favourites':'id3333'); // SyntaxError: missing ) after argument list
localStorage.removeItem('favourites[id3333]'); // no errors, no removal
localStorage.removeItem('id3333', JSON.stringify('id3333')); // no errors, no removal
Also, I will need to get the key name to delete based on a variable, so like this..
var postID = 'id3333';
localStorage.removeItem(postID);
or
var objectName = 'favourites';
var postID = 'id3333';
localStorage.removeItem(objectName[postID]);
Is it possible to remove a nested item directly or do I need to retrieve the full object and then delete the item and then set the object back to local storage again?
The closest I can get to deleting anything directly so far is..
localStorage.removeItem('favourites');
But that of course removes the entire object.
You have a a single key and you are acting like there are multiple keys
var obj = {
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
};
window.localStorage.favs = JSON.stringify(obj); //store object to local storage
console.log("before : ", window.localStorage.favs); //display it
var favs = JSON.parse(window.localStorage.favs || {}); //read and convert to object
var delKey = "id3333"; //key to remove
if (favs[delKey]) { //check if key exists
delete favs[delKey]; //remove the key from object
}
window.localStorage.favs = JSON.stringify(favs); //save it back
console.log("after : ", window.localStorage.favs); //display object with item removed
With localStorage.removeItem you can only remove top level keys, i.e. keys directly on localStorage.
Because id3333 is on localStorage.favourites you cannot remove it using localStorage.removeItem.
Instead try delete localStorage.favourties['id3333']
Simple, actually: you just delete it. :)
x = {
"id3333":{
"URL":"somewhere.comm/page1/",
"TITLE":"Page 1 Title",
},
"id4444":{
"URL":"somewhere.comm/page2/",
"TITLE":"Page 2 Title",
}
};
console.log(x);
delete x.id3333;
console.log(x);
delete does what you're looking for. You could also do something like delete x.id3333.TITLE if you were so inclined. Note also that delete returns true if successful and false if not.
Suppose you set a nested object in localStorage like that
const dataObj = {
uid: {
name: 'robin',
age: 24,
}
}
window.localStorage.setItem('users', JSON.stringify(dataObj));
Now you want to delete the age property. You can't remove it with removeItem native function since it allows to delete from top level.
So you need to get the data first and delete the property you want and set the data again to localStorage with updated value like that
const existingLocalStorage = JSON.parse(window.localStorage.getItem('users') || {});
if(existingLocalStorage['uid']['age']) { // if throws any error, use lodash get fucntion for getting value
delete existingLocalStorage['uid']['age'];
}
window.localStorage.setItem('users', JSON.stringify(existingLocalStorage));
In the given fiddle , click on Addons buttons and on selection and unselection
of Checkboxes , i am trying to update the data-attr
array present as data-stuff .
Once i set the data how can i fetch the existing and update it with new data .
http://jsfiddle.net/kgm9o693/9/
// checkbox checked
$(document).on('click', '.ui-checkbox-off', function (event) {
var vendoritemsdata = $(".lastItm_Wrap").data('stuff');
var checkboxid = $(this).next().attr("id");
var cost = $(this).attr("cost");
var toppcrusts = [];
toppcrusts.push({
'name': checkboxid,
'cost': cost
});
if (vendoritemsdata.length == 0) {
$('.lastItm_Wrap').attr('data-stuff', toppcrusts);
}
else {
var existingdata = $('.lastItm_Wrap').data('data-stuff');
}
});
Could you please tell me how to resolve this ??
You are trying to use the DOM as a variable. It should be the other way around. Use the DOM only to show results (total cost in your case). But before that keep everything into an array serialize the array if you need it as json or data-stuff.
Examine the example at the bottom of this http://api.jquery.com/serializeArray/
If you want to keep doing it your way, convert the data to JSON and use this:
Set data
$('.lastItm_Wrap').attr('data-stuff', JSON.stringify(toppcrusts) );
Get data
var existingdata = JSON.parse( $('.lastItm_Wrap').attr('data-stuff') );
http://jsfiddle.net/kgm9o693/12/
I hope my question is not as stupid as I think it is...
I want to extract (the value of) a single variable from an JSONarray. I have this jquery code
$(document).ready(function(){
$("#gb_form").submit(function(e){
e.preventDefault();
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
if(data !== false) {
var entry = data;
$('.entries').prepend(entry);
}
});
});
});
the content of data looks like this ("MyMessage" and "MyName" are values written in a simple form from user):
[{"message":"MyMessage","name":"MyName"}]
the var "entry" should give (more or less) following output at the end:
"Send from -MyName- : -MyMessage-"
I'm not able to extract the single array values from data. I tried things like that:
var message = data['message'];
var name = data['name']
var entry = "Send from" + name + ":" +message;
but that gives "Send from undefined: undefined"
Hope you can help me with that.
you can do like this to get first item of array:
var msg = "Send from"+data[0].name + " "+data[0].message;
console.log(msg );
SAMPLE FIDDLE
UPDATE:
as you are using $.post you will need to explicitly parse response as json:
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
var response = jQuery.parseJSON(data);
var msg = "Send from"+response [0].name + " "+response [0].message;
console.log(msg );
});
To access an array you use the [] notation
To access an object you use the . notation
So in case of [{JSON_OBJECT}, {JSON_OBJECT}]
if we have the above array of JSON objects in a variable called data, you will first need to access a particular Json Object in the array:
data[0] // First JSON Object in array
data[1] // Second JSON Object in array.. and so on
Then to access the properties of the JSON Object we need to do it like so:
data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array
data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array