Load JSON before anything else - javascript

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){ });

Related

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.

Sync view/data load

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.
});
}

Javascript function not changing <pre> innerHTML?

So I have a simple setup going here where I load up a file (A blender .obj file) and display it. Then I call this function:
function parseFile(){
var fileText = $('#file').html();
var fileLine = fileText.split("\r\n");
$('#file').html(fileLine[5]);
}
Which should make it so it displays the 6th line of the file, but it still displays the whole file. How do I make it split the lines like they are in the actual file?
Edit: Just so everyone know's I'm loading the file like this: $('#file').load('model.obj');
The call to .load() is asynchronous. The method will return, but the content will be available somewhen in the future. You'll need to use a callback:
$('#file').load('model.obj', function(response, status) {
alert("Now the file is loaded");
parseFile();
});
alert("Loading the file just began, nothing available by now");
Or more narrative, using the deferred interface:
$('#file').load('model.obj').then(parseFile);
If you need/want to parse the server response anyway, it might be a better to use $.ajax() directly instead of loading it into a innerHTML and reading from there... You even could use a dedicated dataFilter for the blender.obj file type.
Maybe it is only a problem with '\n'
Try this :
var fileLine = fileText.split("\n");
Try wrapping your call like this $(parseFile()); and make sure your HTML actually contains an element with the id of file.

How to make JS execute in HTML response received using Ajax?

I have following workflow
div on the page is used
on users operation request is done
to server side page whose html is
retrived using ajax and dumped into
the div
With html markup some JavaScript is
also dumped however that is not
getting executed.
Why is so ? What could be the possible fix ?
Though i avoid doing things like this but in some old code implementations like these are very common.
Scripts added using .innerHTML will not be executed, so you will have to handle this your self.
One easy way is to extract the scripts and execute them
var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html";
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = response.replace(reScript, function(m,m1) {
eval(m1); //will run alert("foo");
return "";
});
alert(response); // will alert "htmlhtml"
​
This will extract the scripts, execute them and replace them with "" in the original data.

Categories

Resources