Sync view/data load - javascript

I'm going to perform 2 AJAX calls:
Load HTML partial template.
Load JSON data for template and render it into loaded template.
JSON should be loaded separate from template because user can trigger some kind of "refresh" action. Template can't be loaded on the first page load because there is tab control on the page and every tab should be loaded "on demand".
So let's say some function loadData was called. So I need to do the following:
If template is already loaded then GOTO step 3.
Send AJAX for template using $().load and AJAX for JSON data using $.getJSON at the same time. The fact is we can send both them together without waiting for template is loaded, am I right?
If JSON is loaded then check if template is already here. If so then render data into template. Else wait for template is loaded and then render data on success.
So I wonder what is the best practice for such activity? Is there any complete solution for it?
Thank you in advance.

Yes. You can use jQuery Deferreds (http://api.jquery.com/category/deferred-object/) to coordinate all this.
JS Code:
var templatePromise = null;
function loadData() {
if (!templatePromise) {
templatePromise = $.get('templateUrl');
}
var dataPromise = $.getJSON('dataUrl');
$.when(templatePromise, dataPromise)
.done(function (template, data) {
// you have both template and data.
})
.fail(function () {
// either the template or the data failed to be fetched properly.
});
}

Related

Load JSON before anything else

I'm trying to load the JSON before anything else loads, because I need to access the JSON immediately when a browser connects to the server.
This is how I load my json
$.getJSON('icons.txt', function(iconData) {
icons = iconData;
});
How can I make it so javascript loads the json first before anything else? or at least makes it so that it's loaded before the user connects.
Just put all your other code inside function(iconData) {icons = iconData;}); callback function, it will be executed after the JSON will be fetched.
If you put your tag in the head of your HTML, it should be executed at first.
Maybe duplicate of: Load javascript before rendering page?
The code loaded on the head, and then set to synchronize loading
$.ajaxSettings.async = false;
$.getJSON(url, data, function(data){ });

Partial View - Get html that would be render

Context:
I've created a GET request in my route folder that sends html. It will be used for a ajax request:
router.get(url, function(){
res.send("<p>Some Text</p>");
})
My idea/doubt/problem is the following, is it possible to use a partial view in order to generate the html that I want and send it?
I have a partial view with the code i need, that's used in the main rendering, and it's frustrating to edit the code in two different sections.
I've found the way:
res.render(view, function(err, html){
if(!err){
res.send(html);
}
});
If the callback function is used, the default behaviour of rendering the page is canceled.

Load data with AJAX only if it has not already been loaded?

I need to load data for my JavaScript app to use. I would like to load the following:
userlist JSON
milestones JSON
Tags JSON
user ACL permissions JSON
These 4 items of data from the server as JSON should be loaded using AJAX but only loaded once.
So I need code that will check to see if the data is loaded already and if it is, use it. If it is not loaded yet, it would make an AJAX request and load the data, and then use it.
I have multiple JavaScript files which need access to this data so I want to make sure that any of them can access it, and whichever once calls for it first will load it using AJAX and make it available for the other scripts to call it without making multiple repeat AJAX requests.
How could I go about this using JavaScript and jQuery?
A basic example would be super appreciated and useful. Thank you
If any of these are not set, load them using AJAX. After loading with AJAX, set these vars for the next caller to access them without a new AJAX request being made...
var userList = userJsonData;
var milestoneList = milestoneJsonData;
var tagList = tagJsonData;
var useAclPermissions = useAclPermissionsJsonData;
Just store the data in a global javascript variable, which is set to null, when your page loads. The first script which loads the data, stores it in the variable, all the other scripts try to access the content of the variable, and if not set, load it:
var milestoneData = null;
function getMilestoneData() {
if (milestoneData === null) {
//make the ajax request, and populate milestoneData variable
} else return milestoneData;
}
According to can i use you can check out localstorage aka webstorage. If you can use it, it might solve your issues. There is a jQuery plugin available. jstorage is an alternative, and has a really simple example at the bottom of the page. Hope this helps.

How to load blade or php content into a view via ajax/jquery in laravel?

As the title says, I am trying to dynamically load content in a view using ajax requests. I know this can be done if you are using html elements e.g. ("#div_place").html(<p>...). The problem lies when I would like to load some php/blade objects into a div for instance. Is this possible or is there a different way to go about achieving the result I want.
This is pretty straightforward. Assuming you're using jQuery...
create a route that will respond to the AJAX call and return an HTML fragment
Route::get('test', function(){
// this returns the contents of the rendered template to the client as a string
return View::make("mytemplate")
->with("value", "something")
->render();
});
in your javascript:
$.get(
"test",
function (data) {
$("#my-content-div").html(data);
}
);
After some digging some more I found this which helped me to solve the problem.
You have to use the .load("url/page/...") via jquery and then set a route in the routes.php file that displays a view with the data that needs to be loaded e.g.
Route::get('/url/page/...', function(){
return View::make('test');
});
This returns the necessary php code which needed to be loaded dynamically, cheers.

Refresh Part of Page (div)

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

Categories

Resources