Pass Localstorage json data into php sql query through Ajax (A read posts later function)
I'm trying to build a "read later"(favorites) function for my blog website.
I want to use localstorage to save the postID of my blog posts (often very short posts) as json and then through simple AJAX (no jquery) POST and php GET, show the save post on one page
I write the postID list to the localstorage the following way save.php:
<html>
<head>
<style>
.list li {
cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
content: ' 2605';
color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
content: ' 2606';
}
</style>
</head>
<body>
<ul class="list">
<li id="1">PostID1</li>
<li id="2">PostID2</li>
<li id="3">PostID3</li>
<li id="4">PostID4</li>
<li id="5">PostID5</li>
<li id="6">PostID6</li>
</ul>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || ;
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
</script>
</body>
</html>
It returns the following localstorage input (if I add postID 1 and 2):
favorites ["1","2"]
What I'm struggling with is how to the pass the data (Guess some AJAX, but I have no knowledge on how to do that) to my query that shows the posts.
If I manually paste the values (see variable $q, it works, but I do not know how to do this with simple ajax.
The post list, where I want the data that get's passed to be on is see-saved-posts.php
<?php require('includes/config.php'); ?>
<?php
$q = ("1,2");
try {
$stmt = $db->query('SELECT postID, postTitle, postSlug, postDesc, postDate FROM blog_posts_seo WHERE postID IN ('.$q.') ');
while($row = $stmt->fetch()){
echo '<div>';
echo '<h1><a href="'.$row['postSlug'].'">'.$row['postTitle'].'</a></h1>';
echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).' in ';
$stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID');
$stmt2->execute(array(':postID' => $row['postID']));
$catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$links = array();
foreach ($catRow as $cat)
{
$links = "<a href='c-".$cat['catSlug']."'>".$cat['catTitle']."</a>";
}
echo implode(", ", $links);
echo '</p>';
echo '<p>'.$row['postDesc'].'</p>';
echo '<p><a href="'.$row['postSlug'].'">Read More</a></p>';
echo '</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Thanks in advance. P.s. I'm new to this community, but have been using it for years. Usually I can find an answer through the search function, but not this time.
javascript php json ajax
add a comment |
I'm trying to build a "read later"(favorites) function for my blog website.
I want to use localstorage to save the postID of my blog posts (often very short posts) as json and then through simple AJAX (no jquery) POST and php GET, show the save post on one page
I write the postID list to the localstorage the following way save.php:
<html>
<head>
<style>
.list li {
cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
content: ' 2605';
color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
content: ' 2606';
}
</style>
</head>
<body>
<ul class="list">
<li id="1">PostID1</li>
<li id="2">PostID2</li>
<li id="3">PostID3</li>
<li id="4">PostID4</li>
<li id="5">PostID5</li>
<li id="6">PostID6</li>
</ul>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || ;
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
</script>
</body>
</html>
It returns the following localstorage input (if I add postID 1 and 2):
favorites ["1","2"]
What I'm struggling with is how to the pass the data (Guess some AJAX, but I have no knowledge on how to do that) to my query that shows the posts.
If I manually paste the values (see variable $q, it works, but I do not know how to do this with simple ajax.
The post list, where I want the data that get's passed to be on is see-saved-posts.php
<?php require('includes/config.php'); ?>
<?php
$q = ("1,2");
try {
$stmt = $db->query('SELECT postID, postTitle, postSlug, postDesc, postDate FROM blog_posts_seo WHERE postID IN ('.$q.') ');
while($row = $stmt->fetch()){
echo '<div>';
echo '<h1><a href="'.$row['postSlug'].'">'.$row['postTitle'].'</a></h1>';
echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).' in ';
$stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID');
$stmt2->execute(array(':postID' => $row['postID']));
$catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$links = array();
foreach ($catRow as $cat)
{
$links = "<a href='c-".$cat['catSlug']."'>".$cat['catTitle']."</a>";
}
echo implode(", ", $links);
echo '</p>';
echo '<p>'.$row['postDesc'].'</p>';
echo '<p><a href="'.$row['postSlug'].'">Read More</a></p>';
echo '</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Thanks in advance. P.s. I'm new to this community, but have been using it for years. Usually I can find an answer through the search function, but not this time.
javascript php json ajax
You are right you will need AJAX. Localstorage can only be accessed through js as its client side service. PHP is a server side language. You will need to make an AJAX call to posts page and passing the favourites ids and then retrieve the post and display it. I shall a solution once i get on the computer.
– Mohammad C
Nov 17 '18 at 20:21
add a comment |
I'm trying to build a "read later"(favorites) function for my blog website.
I want to use localstorage to save the postID of my blog posts (often very short posts) as json and then through simple AJAX (no jquery) POST and php GET, show the save post on one page
I write the postID list to the localstorage the following way save.php:
<html>
<head>
<style>
.list li {
cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
content: ' 2605';
color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
content: ' 2606';
}
</style>
</head>
<body>
<ul class="list">
<li id="1">PostID1</li>
<li id="2">PostID2</li>
<li id="3">PostID3</li>
<li id="4">PostID4</li>
<li id="5">PostID5</li>
<li id="6">PostID6</li>
</ul>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || ;
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
</script>
</body>
</html>
It returns the following localstorage input (if I add postID 1 and 2):
favorites ["1","2"]
What I'm struggling with is how to the pass the data (Guess some AJAX, but I have no knowledge on how to do that) to my query that shows the posts.
If I manually paste the values (see variable $q, it works, but I do not know how to do this with simple ajax.
The post list, where I want the data that get's passed to be on is see-saved-posts.php
<?php require('includes/config.php'); ?>
<?php
$q = ("1,2");
try {
$stmt = $db->query('SELECT postID, postTitle, postSlug, postDesc, postDate FROM blog_posts_seo WHERE postID IN ('.$q.') ');
while($row = $stmt->fetch()){
echo '<div>';
echo '<h1><a href="'.$row['postSlug'].'">'.$row['postTitle'].'</a></h1>';
echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).' in ';
$stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID');
$stmt2->execute(array(':postID' => $row['postID']));
$catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$links = array();
foreach ($catRow as $cat)
{
$links = "<a href='c-".$cat['catSlug']."'>".$cat['catTitle']."</a>";
}
echo implode(", ", $links);
echo '</p>';
echo '<p>'.$row['postDesc'].'</p>';
echo '<p><a href="'.$row['postSlug'].'">Read More</a></p>';
echo '</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Thanks in advance. P.s. I'm new to this community, but have been using it for years. Usually I can find an answer through the search function, but not this time.
javascript php json ajax
I'm trying to build a "read later"(favorites) function for my blog website.
I want to use localstorage to save the postID of my blog posts (often very short posts) as json and then through simple AJAX (no jquery) POST and php GET, show the save post on one page
I write the postID list to the localstorage the following way save.php:
<html>
<head>
<style>
.list li {
cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
content: ' 2605';
color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
content: ' 2606';
}
</style>
</head>
<body>
<ul class="list">
<li id="1">PostID1</li>
<li id="2">PostID2</li>
<li id="3">PostID3</li>
<li id="4">PostID4</li>
<li id="5">PostID5</li>
<li id="6">PostID6</li>
</ul>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || ;
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
</script>
</body>
</html>
It returns the following localstorage input (if I add postID 1 and 2):
favorites ["1","2"]
What I'm struggling with is how to the pass the data (Guess some AJAX, but I have no knowledge on how to do that) to my query that shows the posts.
If I manually paste the values (see variable $q, it works, but I do not know how to do this with simple ajax.
The post list, where I want the data that get's passed to be on is see-saved-posts.php
<?php require('includes/config.php'); ?>
<?php
$q = ("1,2");
try {
$stmt = $db->query('SELECT postID, postTitle, postSlug, postDesc, postDate FROM blog_posts_seo WHERE postID IN ('.$q.') ');
while($row = $stmt->fetch()){
echo '<div>';
echo '<h1><a href="'.$row['postSlug'].'">'.$row['postTitle'].'</a></h1>';
echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).' in ';
$stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID');
$stmt2->execute(array(':postID' => $row['postID']));
$catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC);
$links = array();
foreach ($catRow as $cat)
{
$links = "<a href='c-".$cat['catSlug']."'>".$cat['catTitle']."</a>";
}
echo implode(", ", $links);
echo '</p>';
echo '<p>'.$row['postDesc'].'</p>';
echo '<p><a href="'.$row['postSlug'].'">Read More</a></p>';
echo '</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Thanks in advance. P.s. I'm new to this community, but have been using it for years. Usually I can find an answer through the search function, but not this time.
javascript php json ajax
javascript php json ajax
asked Nov 17 '18 at 19:54
Dennis NielsenDennis Nielsen
31
31
You are right you will need AJAX. Localstorage can only be accessed through js as its client side service. PHP is a server side language. You will need to make an AJAX call to posts page and passing the favourites ids and then retrieve the post and display it. I shall a solution once i get on the computer.
– Mohammad C
Nov 17 '18 at 20:21
add a comment |
You are right you will need AJAX. Localstorage can only be accessed through js as its client side service. PHP is a server side language. You will need to make an AJAX call to posts page and passing the favourites ids and then retrieve the post and display it. I shall a solution once i get on the computer.
– Mohammad C
Nov 17 '18 at 20:21
You are right you will need AJAX. Localstorage can only be accessed through js as its client side service. PHP is a server side language. You will need to make an AJAX call to posts page and passing the favourites ids and then retrieve the post and display it. I shall a solution once i get on the computer.
– Mohammad C
Nov 17 '18 at 20:21
You are right you will need AJAX. Localstorage can only be accessed through js as its client side service. PHP is a server side language. You will need to make an AJAX call to posts page and passing the favourites ids and then retrieve the post and display it. I shall a solution once i get on the computer.
– Mohammad C
Nov 17 '18 at 20:21
add a comment |
1 Answer
1
active
oldest
votes
So i have created a div with id saved-posts. This is where will print the saved posts we get from the AJAX call. I have created a function called getPosts()
, this performs an AJAX call to the see-saved-posts.php page passing a query string called q with the favourite ids. I called the getPosts function twice, once when the page is loading and again once you update the favourites. One chane you will have to make in the see-saved-posts.php
page is to make is to get the favourites ID from the querystring by do this: $q = $_GET['q'];
Update
I have updated the function so that i will only do AJAX call in there are any favourites. If all favourites are removed then it will remove from the remaining one from the page.
<html>
<head>
<style>
.list li {
cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
content: ' 2605';
color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
content: ' 2606';
}
</style>
</head>
<body>
<ul class="list">
<li id="1">PostID1</li>
<li id="2">PostID2</li>
<li id="3">PostID3</li>
<li id="4">PostID4</li>
<li id="5">PostID5</li>
<li id="6">PostID6</li>
</ul>
<div id="saved-posts"></div>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || ;
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
getPosts(); // calls AJAX to populate with saved posts
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
getPosts(); // Call AJAX to repopulate with saved post
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
function getPosts() {
if (favorites.length) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("saved-posts").innerHTML = this.responseText;
}
};
xhttp.open("GET", "see-saved-posts.php?q=" + favorites, true);
xhttp.send();
} else {
document.getElementById("saved-posts").innerHTML = "";
}
}
</script>
</body>
</html>
Thanks. I have worked my way in to the script and done a lot of searches to understand how it functions. Is there anything I should be aware of with the Ajax GET function. I mean, the Localstorage is very easy to change and manipulate. Would there be a possible vulnerability in terms of people trying to inject different values in to it?
– Dennis Nielsen
Nov 17 '18 at 22:02
Well as you said injection is one. I am not sure of any others. But to counter this I would suggest checking whether q is what it i supposed to be. Q is supposed to be a number followed by 0 or more comma and number. You would test in php using regex like/^d+(,d+)*$/
– Mohammad C
Nov 18 '18 at 0:25
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53354979%2fpass-localstorage-json-data-into-php-sql-query-through-ajax-a-read-posts-later%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
So i have created a div with id saved-posts. This is where will print the saved posts we get from the AJAX call. I have created a function called getPosts()
, this performs an AJAX call to the see-saved-posts.php page passing a query string called q with the favourite ids. I called the getPosts function twice, once when the page is loading and again once you update the favourites. One chane you will have to make in the see-saved-posts.php
page is to make is to get the favourites ID from the querystring by do this: $q = $_GET['q'];
Update
I have updated the function so that i will only do AJAX call in there are any favourites. If all favourites are removed then it will remove from the remaining one from the page.
<html>
<head>
<style>
.list li {
cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
content: ' 2605';
color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
content: ' 2606';
}
</style>
</head>
<body>
<ul class="list">
<li id="1">PostID1</li>
<li id="2">PostID2</li>
<li id="3">PostID3</li>
<li id="4">PostID4</li>
<li id="5">PostID5</li>
<li id="6">PostID6</li>
</ul>
<div id="saved-posts"></div>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || ;
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
getPosts(); // calls AJAX to populate with saved posts
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
getPosts(); // Call AJAX to repopulate with saved post
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
function getPosts() {
if (favorites.length) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("saved-posts").innerHTML = this.responseText;
}
};
xhttp.open("GET", "see-saved-posts.php?q=" + favorites, true);
xhttp.send();
} else {
document.getElementById("saved-posts").innerHTML = "";
}
}
</script>
</body>
</html>
Thanks. I have worked my way in to the script and done a lot of searches to understand how it functions. Is there anything I should be aware of with the Ajax GET function. I mean, the Localstorage is very easy to change and manipulate. Would there be a possible vulnerability in terms of people trying to inject different values in to it?
– Dennis Nielsen
Nov 17 '18 at 22:02
Well as you said injection is one. I am not sure of any others. But to counter this I would suggest checking whether q is what it i supposed to be. Q is supposed to be a number followed by 0 or more comma and number. You would test in php using regex like/^d+(,d+)*$/
– Mohammad C
Nov 18 '18 at 0:25
add a comment |
So i have created a div with id saved-posts. This is where will print the saved posts we get from the AJAX call. I have created a function called getPosts()
, this performs an AJAX call to the see-saved-posts.php page passing a query string called q with the favourite ids. I called the getPosts function twice, once when the page is loading and again once you update the favourites. One chane you will have to make in the see-saved-posts.php
page is to make is to get the favourites ID from the querystring by do this: $q = $_GET['q'];
Update
I have updated the function so that i will only do AJAX call in there are any favourites. If all favourites are removed then it will remove from the remaining one from the page.
<html>
<head>
<style>
.list li {
cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
content: ' 2605';
color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
content: ' 2606';
}
</style>
</head>
<body>
<ul class="list">
<li id="1">PostID1</li>
<li id="2">PostID2</li>
<li id="3">PostID3</li>
<li id="4">PostID4</li>
<li id="5">PostID5</li>
<li id="6">PostID6</li>
</ul>
<div id="saved-posts"></div>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || ;
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
getPosts(); // calls AJAX to populate with saved posts
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
getPosts(); // Call AJAX to repopulate with saved post
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
function getPosts() {
if (favorites.length) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("saved-posts").innerHTML = this.responseText;
}
};
xhttp.open("GET", "see-saved-posts.php?q=" + favorites, true);
xhttp.send();
} else {
document.getElementById("saved-posts").innerHTML = "";
}
}
</script>
</body>
</html>
Thanks. I have worked my way in to the script and done a lot of searches to understand how it functions. Is there anything I should be aware of with the Ajax GET function. I mean, the Localstorage is very easy to change and manipulate. Would there be a possible vulnerability in terms of people trying to inject different values in to it?
– Dennis Nielsen
Nov 17 '18 at 22:02
Well as you said injection is one. I am not sure of any others. But to counter this I would suggest checking whether q is what it i supposed to be. Q is supposed to be a number followed by 0 or more comma and number. You would test in php using regex like/^d+(,d+)*$/
– Mohammad C
Nov 18 '18 at 0:25
add a comment |
So i have created a div with id saved-posts. This is where will print the saved posts we get from the AJAX call. I have created a function called getPosts()
, this performs an AJAX call to the see-saved-posts.php page passing a query string called q with the favourite ids. I called the getPosts function twice, once when the page is loading and again once you update the favourites. One chane you will have to make in the see-saved-posts.php
page is to make is to get the favourites ID from the querystring by do this: $q = $_GET['q'];
Update
I have updated the function so that i will only do AJAX call in there are any favourites. If all favourites are removed then it will remove from the remaining one from the page.
<html>
<head>
<style>
.list li {
cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
content: ' 2605';
color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
content: ' 2606';
}
</style>
</head>
<body>
<ul class="list">
<li id="1">PostID1</li>
<li id="2">PostID2</li>
<li id="3">PostID3</li>
<li id="4">PostID4</li>
<li id="5">PostID5</li>
<li id="6">PostID6</li>
</ul>
<div id="saved-posts"></div>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || ;
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
getPosts(); // calls AJAX to populate with saved posts
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
getPosts(); // Call AJAX to repopulate with saved post
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
function getPosts() {
if (favorites.length) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("saved-posts").innerHTML = this.responseText;
}
};
xhttp.open("GET", "see-saved-posts.php?q=" + favorites, true);
xhttp.send();
} else {
document.getElementById("saved-posts").innerHTML = "";
}
}
</script>
</body>
</html>
So i have created a div with id saved-posts. This is where will print the saved posts we get from the AJAX call. I have created a function called getPosts()
, this performs an AJAX call to the see-saved-posts.php page passing a query string called q with the favourite ids. I called the getPosts function twice, once when the page is loading and again once you update the favourites. One chane you will have to make in the see-saved-posts.php
page is to make is to get the favourites ID from the querystring by do this: $q = $_GET['q'];
Update
I have updated the function so that i will only do AJAX call in there are any favourites. If all favourites are removed then it will remove from the remaining one from the page.
<html>
<head>
<style>
.list li {
cursor: pointer;
}
.list li:hover:after,
.list li.fav:after {
content: ' 2605';
color: rgb(255, 203, 0);
}
.list li.fav:hover:after {
content: ' 2606';
}
</style>
</head>
<body>
<ul class="list">
<li id="1">PostID1</li>
<li id="2">PostID2</li>
<li id="3">PostID3</li>
<li id="4">PostID4</li>
<li id="5">PostID5</li>
<li id="6">PostID6</li>
</ul>
<div id="saved-posts"></div>
<script>
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || ;
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
getPosts(); // calls AJAX to populate with saved posts
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
getPosts(); // Call AJAX to repopulate with saved post
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
function getPosts() {
if (favorites.length) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("saved-posts").innerHTML = this.responseText;
}
};
xhttp.open("GET", "see-saved-posts.php?q=" + favorites, true);
xhttp.send();
} else {
document.getElementById("saved-posts").innerHTML = "";
}
}
</script>
</body>
</html>
edited Nov 17 '18 at 20:56
answered Nov 17 '18 at 20:50
Mohammad CMohammad C
1,1851312
1,1851312
Thanks. I have worked my way in to the script and done a lot of searches to understand how it functions. Is there anything I should be aware of with the Ajax GET function. I mean, the Localstorage is very easy to change and manipulate. Would there be a possible vulnerability in terms of people trying to inject different values in to it?
– Dennis Nielsen
Nov 17 '18 at 22:02
Well as you said injection is one. I am not sure of any others. But to counter this I would suggest checking whether q is what it i supposed to be. Q is supposed to be a number followed by 0 or more comma and number. You would test in php using regex like/^d+(,d+)*$/
– Mohammad C
Nov 18 '18 at 0:25
add a comment |
Thanks. I have worked my way in to the script and done a lot of searches to understand how it functions. Is there anything I should be aware of with the Ajax GET function. I mean, the Localstorage is very easy to change and manipulate. Would there be a possible vulnerability in terms of people trying to inject different values in to it?
– Dennis Nielsen
Nov 17 '18 at 22:02
Well as you said injection is one. I am not sure of any others. But to counter this I would suggest checking whether q is what it i supposed to be. Q is supposed to be a number followed by 0 or more comma and number. You would test in php using regex like/^d+(,d+)*$/
– Mohammad C
Nov 18 '18 at 0:25
Thanks. I have worked my way in to the script and done a lot of searches to understand how it functions. Is there anything I should be aware of with the Ajax GET function. I mean, the Localstorage is very easy to change and manipulate. Would there be a possible vulnerability in terms of people trying to inject different values in to it?
– Dennis Nielsen
Nov 17 '18 at 22:02
Thanks. I have worked my way in to the script and done a lot of searches to understand how it functions. Is there anything I should be aware of with the Ajax GET function. I mean, the Localstorage is very easy to change and manipulate. Would there be a possible vulnerability in terms of people trying to inject different values in to it?
– Dennis Nielsen
Nov 17 '18 at 22:02
Well as you said injection is one. I am not sure of any others. But to counter this I would suggest checking whether q is what it i supposed to be. Q is supposed to be a number followed by 0 or more comma and number. You would test in php using regex like
/^d+(,d+)*$/
– Mohammad C
Nov 18 '18 at 0:25
Well as you said injection is one. I am not sure of any others. But to counter this I would suggest checking whether q is what it i supposed to be. Q is supposed to be a number followed by 0 or more comma and number. You would test in php using regex like
/^d+(,d+)*$/
– Mohammad C
Nov 18 '18 at 0:25
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53354979%2fpass-localstorage-json-data-into-php-sql-query-through-ajax-a-read-posts-later%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You are right you will need AJAX. Localstorage can only be accessed through js as its client side service. PHP is a server side language. You will need to make an AJAX call to posts page and passing the favourites ids and then retrieve the post and display it. I shall a solution once i get on the computer.
– Mohammad C
Nov 17 '18 at 20:21