How to store/remember the data fetched from ajax call? - javascript

I'm retrieving some data into a JSON array, then display it into an HTML table which contains some data enclosed within hyper links. i.e. a couple of the columns' data are clickable, once clicked it displays another JSP page (say page #2) with some more data which was kept on the JSON array itself.
Now this page 2 has a 'Back' button functionality - the expected behavior is when user clicks the 'Back' button it should go back to page 1 where the HTML table data was displayed and user should be able to see the data which they first fetched too. i.e. there should be some way to remember the data fetched from my initial AJAX request and retrieve the same data which user fetched in page 1 when they go back to that page from the child page#2.
Th AJAX call is triggered when user enters an account# and the type of account - I fetch data accordingly and get the result in the 'response' object and neatly display it on html table, but after user moves from that page and again hits the back button I see the page#1 without the table. Now again I cannot ask the user to re-enter the details to see the data that they retrieved earlier. It's pretty annoying.
Please give me a solution to this problem. Thanks All.
Appreciate for taking time to read this.
Here's a part of the code:
$(document).ready(function () {
var flag = "1";
$('#accountType').bind('change', function (event) {
var accountType = $('#accountTypeSelect').val();
var account = $('#accountText').val();
jQuery.ajax({
type: 'POST',
url: '${pageContext.request.contextPath}' + "/Page1.spr", //request page
cache: false,
dataType: "json",
data: {
"accountType": accountType,
"account": account,
"flag": flag
}, //data sent to request page
success: function (response) {
// code to display the data into the html table
},
error: (function (message) {
console.log("error message : " + message);
}),
statusCode: {
404: function () {
alert("page not found");
}
}
});
});

You can save the data in HTML5 sessionStorage or localStorage using the setItem method as follows:
success: function(response) {
sessionStorage.setItem("result", response)
// code to display the data into the html table
}
And access it later using the getItem() When you come back to the page like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// code to be executed when old dats is found
}
else{
}
Ideally you code in first pages load will be something like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// data exists : code to be executed when old dats is found
}
else{
jQuery.ajax({}) // send the AJAX request to fetch data
}
You can read more about session and local Storage here
Browser support for web storage API.
Update
If you don't have HTML5 support, you could use jQuery cookie plugin (There are plenty of others as well) for storing data at client side.
You can store data into a cookie as follows:
$.cookie("result", response);
Then to get it from the cookie like:
$.cookie("result");

You maybe can use cookie via jquery. But user have to enable the browser's cookie. It usually enabled by default setting.
To add:
$.cookie("key1", data1);
$.cookie("key2", data2);
To read:
$.cookie("key1");
To delete:
$.removeCookie("key1");
So, you can try to read cookie to load table data, if no data, call ajax:)

Another way is to save it in a hidden input:
success: function(response){
$("#hiddenInput").val(JSON.stringify(response));
}

Related

how to fetch data from url using javascript

I have link generated from rest Api console
this is the link:
https://SomeThing/rest1/order2/getOrders
and i have token generated from the same rest Api console
now i can make post by ajax ang get the data but i want to fetch this data
this is my code
$(document).ready(function() {
$("button").click(function() {
$.post(
"https://SomeThing/rest1/order2/getOrders",
{ token: "Token" },
function(a, b) {
<----what i should use --->
}
);
});
});
Good news is that you are very close, bad news is that you leaked your token and will have to regenerate it now.
I would replace function(a,b,) just with function(data) and accessed data retrieved from called REST endpoint through the variable data
$(document).ready(function() {
$("button").click(function() {
$.post(
"https://www.tesetturpazari.com/rest1/order2/getOrders",
{ token: "<token>" },
function(data) {
console.log(data);
}
);
});
});
When you then press F12 (or other hotkey used to open developer console in your browser), you can go through data retrieved from remote server and figure out how to further process your data based on its structure. It comes back in JSON format, which is very easy to process in Javascript.
OP further explained the need to render data to div that already exists on site (in the comment on the answer that was deleted), solution is to update callback function:
$(document).ready(function() {
$("button").click(function() {
$.post(
"https://www.tesetturpazari.com/rest1/order2/getOrders",
{ token: "<token>" },
function(data) {
// Possibly before displaying it all, do some preprocessing here over the data variable
// Replace 'mydiv' with ID of an element where you want to show data
$("#mydiv").html(data)
}
);
});
});
Note: Please regenerate and replace your token.
Note 2: I repost this answer so I can remove the original one where I managed to duplicate access token, sadly.

window.location.reload(true) not reloading the page correctly

I have a PHP page which fetches data from a MYSQL database and generates HTML content based on rows returned from the database.
I am adding a new row in database on click of a button using AJAX, Jquery and PHP. After adding the new row, I am using window.location.reload(true); to reload the page. But the HTML elements corresponding to new row are not shown when I click the button. However, if I manually refresh the page using F5, the newly added content is shown.
Anyone knows why this could happen?
Below is the function which I call on click of a button. The page increaseCount.php updates database to increase the count of actors. But the HTML elements corresponding to new count are not shown until I refresh the page using F5.
function increaseCountOfNewActor(characterName) {
var actorName = document.getElementById("txt_actor_"+characterName).value;
var actorImage = document.getElementById("img_actor_"+characterName).src;
$.ajax( {
url: "increaseCount.php",
method: "POST",
data: {
name: actorName,
image: actorImage,
character: characterName
},
success: function( data ) {
alert("Vote received");
}
} );
window.location.reload(true);
}
The problem is that you are mixing ajax with a complete page reload.
The $.ajax call by default is asynchronous (the first a from ajax...). Therefore it sends a request to increasepostcount.php and then immediatelly reloads the page - not waiting for increasepostcount.php to process the request. By the time you manually refresh the page, increasepostcount.php will have completed the processing of the ajax call, therefore its result are reflected on the page.
If you use ajax, you should not use page reloading. Use javascript to update that part of the page where these records are displayed based on the results returned by the ajax call.
You need to be sure that the ajax call has done to do what you want, in your case "window.location.reload(true);" is running before the ajax response, due to asynchronous communication between Client and Server to avoid "freezing" on the screen and an unresponsive user experience.
You have to put your refresh code on Success ajax response or on done :
function increaseCountOfNewActor(characterName) {
var actorName = document.getElementById("txt_actor_"+characterName).value;
var actorImage = document.getElementById("img_actor_"+characterName).src;
$.ajax( {
url: "increaseCount.php",
method: "POST",
data: {
name: actorName,
image: actorImage,
character: characterName
},
success: function( data ) {
alert("Vote received");
// to do here
//window.location.reload(true);
}
} ).done(function () {
// or to do here
window.location.reload(true);
});
}
in your page increaseCount.php consider adding a header at the end.
For example:
if(isset($_POST['name'] &&
isset($_POST["image"] &&
isset($_POST["character"]) {
/* do your stuff here */
header("Location: /thePageYouWantToRefresh.php");
exit;
}

How do I reload a page without the user noticing?

I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!

jQuery alters page - but how/where do I "acquire" the changes?

This post by #BenjaminRH (How to change/edit the text of a paragraph/div using jQuery?) provides exactly the sort of functionality I'm trying to build on.
By clicking on a button, a new paragraph is created on the page, which can be edited and saved to the page.
I want to save it to a database. When I look at the page source after editing, I don't see the changes there, which doesn't surprise me... but I don't know where to "capture" the changed text so that I can validate and post to mySQL.
JQuery is a javascript library - which runs client side. If you wanted to save that data into the database - you would have to send it to the server (php/asp/mvc etc) using ajax and then insert the data into the database.
See the jquery Ajax function for details on how to accomplish sending data asynchronously.
Create the data in javascript that you want to show and save in database.
Wrap the data in JSON and use ajax to POST the data to the server side code
Server-side retrieve the posted data and parse it into something usable
Server-side write a script to insert the data into the database.
Handle any errors that may occur.
Pseudo-code:
// step 1
var someData = 'this is my data';
$("#myDiv").html(someData);
// step 2
$.ajax({
type: "POST",
dataType: 'json', // <-- if the data is complex and needs to be object-oriented
url: "some.php", // <-- that is the file that will handle the post server-side.
data: JSON.stringify({ someData }) // <-- just pass someData if your data is not complex
})
.always(function(jqXHR, textStatus) {
if (textStatus != "success") {
// step 5: handle error.
alert("Error: " + jqXHR.statusText); //error is always called .statusText
} else {
alert("Success: " + jqXHR.response); //might not always be named .response
}});
OK, I've managed to solve it for myself, without using ajax. I took the example from (How to change/edit the text of a paragraph/div using jQuery?) and modified it by placing the elements in an (html) form.
The second modification was to use <textarea> elements, not <p> elements, as <p> elements cannot be posted.
As #caspian pointed out (in the comments) those two steps do populate the $_POST array and away we go.

how to send asynchronous request to php page using jquery ajax

i am new to web development creating a kind of social networking website for college project. I want to include update the messages count in the message menu every time there is a new msg in the database for the user(like facebook message menu on homepage)
But it's frustrating learning ajax, however after searching on web and reading some topics from some books I came to the solution that i can make an $ajax call in my js file in the homepage and send data ('name'=>'user') stored in javascript cookie that i have created on loading of home page after the user login, to a php file which will search across the recent_msg table in database to fetch the recent message for the logged in user if any after fetching the php file will create the html file with code snippet and further another jquery code will append that snippet from file to the message list menu.
the PHP part is not the problem but how can i send the username to the php file using jquery ajax api, here is the code what i think i can apply but i am doubtful in that if this is the correct way
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
}
} );
},10);
});
what is the purpose of success function in the code?
data needs to be in the form of an object / key-value-pair (EDIT: or if a string, as a valid querystring). data: { name: usr }. However, since it's in a cookie, your PHP page will have direct access to that cookie. It's safer to let your session cookie tel the PHP page who the user is instead of relying on an AJAX call to tell the PHP page who it is.
http://php.net/manual/en/features.cookies.php
So I'd drop data from your AJAX call altogether, and in your PHP page, use $_COOKIE["name:"]
Then whatever HTML gets passed back from the PHP page will arrive in the data call. If it's HTML, then simply add it to your HTML to some message div, such as.
<div id="recent-messages"></div>
<script type="text/javascript">
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
$('#recent-messages').html(data);
}
} );
},10);
});
</script>
The success function executes whenever your ajax call completes successfully. This means that the page actually exists and no server-side errors occurred on the page. The variable data will contain whatever information is returned from the page on the sever /phpScripts/recent_msg.php. Generally this is either json or xml, but it entirely depends on your implementation of recent_msg.php.
If the user has to log in that means you have to have created a session. In that case you can store the logged in user's information such as their name in $_SESSION on the server and there is no need to store it as a cookie. Since $_SESSION is already on the server, there is no need to send that data via ajax in any case.

Categories

Resources