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.
Related
I'm writing a system in HTML5 and Javascript, using a webservice to get data in database.
I have just one page, the index.html, the other pages i load in a <div>
The thing is, i have one page to edit and add new users.
When a load this page for add new user, i do this:
$("#box-content").load("views/motorista_add.html");
But, i want send a parameter or something else, to tell to 'motorista_add.html' load data from webservice to edit an user. I've tried this:
$("#box-content").load("views/motorista_add.html?id=1");
And i try to get using this:
function getUrlVar(key) {
var re = new RegExp('(?:\\?|&)' + key + '=(.*?)(?=&|$)', 'gi');
var r = [], m;
while ((m = re.exec(document.location.search)) != null)
r.push(m[1]);
return r;
}
But don't work.
Have i an way to do this without use PHP?
This won't work. Suppose your are loading the motorista_add.html in a page index.html. Then the JS code, the function getUrlVar(), will execute on the page index.html. So document.location that the function will get won't be motorista_add.html but index.html.
So Yes. To do the stuff you are intending, you need server side language, like PHP. Now, on the server side, you get the id parameter via GET variable and use it to build up your motorista_add.php.
You can pass data this way:
$("#box-content").load("views/motorista_add.html", { id : 1 });
Note: The POST method is used if data is provided as an object (like the example above); otherwise, GET is assumed. More info: https://api.jquery.com/load/
Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.
I am trying to pass value to another page and read the value in the another page. I use only JavaScript and jQuery. Not use others language as PHP. I don't want to be as like (http://www.example.com/?value=test). I am trying to use POST or GET method.
On first page:
$.post("second_page.html",{q:"test"});
window.location.replace("second_page.html");
On second page:
var location_query = window.location.search.substring(1);
var vars = location_query.split("&");
for (var i in vars) {
var param = vars[i].split("=");
params[param[0].toString()] = param[1];
}
If I pass value as like http://www.example.com/?q=test , the second page script is read the value, but I use this line: $.post("second.html",{q:"test"}); not read.
How to pass value from first page to another static page via JavaScript or jQuery or ajax?
See this post says:
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
but you can use cookies to read and store values:
<script src="/path/to/jquery.cookie.js"></script>
you can get it from here
Try with reading the documentation and see if this works for you.
Without using GET or POST you can transfer the content using HTML5 Local Storage or
Web SQL
$.post and $.get send AJAX request and waiting response on current page, you cant send params for next window.location.replace by this.
Use url get-params window.location.replace("404.html?q=404"); and look this for get params on second page.
I am using ajax from JQuery. I am doing in a page that I see the results of a POST/GET having provided specific parameters as filters to the server.
Assume I have provided parameters a&b&c to the user so that I see in the page the subset of the data that these parameters hold true.
In a specific case I do an ajax call to pass a value to the server that modifies this set that I am seeing.
What I need is a way to do a refresh of the page but that will only display the new version of the current subset of data I.e. somehow refreshing passing back to the server a&b&c
Right now I am doing: window.location.reload(true); which reloads all the data and it is time-consuming to re-apply the filters manually.
How can I solve this?
Essentially what I need is not full refresh?
If you are using Ajax from jQuery and want to do a partial reload but have chosen window.location.reload, then you are doing it wrong.
Use the format
$("#someDiv").load("someUrl?a=x&b=y")
or
$.get("someUrl?a=x&b=y",function(data) { $("#someDiv").html(data)});
for example this code in the head where .parameters could be checkboxes
$(function() {
$(".parameters").on("click",function() {
var url = "someUrl.php?"+$("#myForm").serialize();
$.get(url,function(data) {
$("#someContainer").html(data);
});
});
});
You would have to return something from the server which will contain th einformation needed to update
And then update the content based on the returned data.
I want to load data into a checkout page using .load() to load the pages in a modal window. The data that needs to be loaded is a shipping price value, that needs to be usable on the loaded page.
JS
function totalCalc() {
var shipping = ($('#shippingform input[name="shipping"]').val());
$('#cartdialog').load("/ash/shop/checkout.php",[$('#shippingform input[name="shipping"]')]);
alert(shipping);
}
CHECKOUT.PHP
$myTotal = ($subtotal + $_POST['shipping']);
I need the value which is shown through the "alert(shipping);" to be a usable value on checkout.php. You'll see I try to $_POST[] it in a php variable, but it wont work. I must be sending the data wrong...
Per the jQuery API, data sent as a query-string format string through .load() is treated as GET. Data sent as a JSON object is treated as POST. Basically, send it like this:
.load("/ash/show/checkout.php", {shipping: shipping});
As it seems you're using jQuery: http://api.jquery.com/jQuery.post/
or if you want proper control over it, use the ajax method: http://api.jquery.com/jQuery.ajax/
Alternatively, you could add the shipping cost to the URL and use $_GET