Sending and getting data via $.load jquery - javascript

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/

Related

passing js value to another php page using java script and receiving value

I want to to pass a js variable to another page ..what to do..code is given bellow..
Code
`
$('#disInfo').on('click','tr',function(){
var obj = $(this);
var result= obj.find('td').eq(1).html();
window.location.href='http://localhost/Trying/search_cus.php';
});
`
I want to send the value of result variable with page link and how to receive the value in another page
You could pass it via an url parameter. If result contains html or characters that cannot be used in an url then you need to encode it first.
$('#disInfo').on('click','tr',function(){
var obj = $(this);
var result = encodeURIComponent( obj.find('td').eq(1).html() );
window.location.href='http://localhost/Trying/search_cus.php?result=' + result;
});
On the target page you can get url parameters via window.location.search ... there's plenty of examples on stackoverflow on how to do that.
NOTE: be aware that the server will also get the request for ?result=whatever. If the server side code processes this (eg PHP: $_GET['result']) you must ensure it sanitizes the value to prevent malicious code injection.
BTW, other ways of passing data is via cookies, sessionStorage, localStorage, etc.

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.

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

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.

How to pass value to another static page via javascript?

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.

hide variables passed in URL

We've been working on a web application and we've just about got it finished up, but there's one thing that bothering us (although by no means is it going to stop production.)
When we call one of the pages (index.html), we sometimes have to pass it a variable in the URL (searchid). So we get a page like http://domain.com/index.html?searchid=string.
We'd ideally like to not show the ?searchid=string, but I'm not sure how we'd do that.
My group doesn't own the index.html page (but we are working with the group that does), so I don't know how much we'd be able to do with anything like .htaccess or similar.
I was thinking about POSTing the variable, but I don't know how to receive it with just HTML and jQuery. Another person in my group thought that after the page loaded we could remove it from the URL, but I assume we would need a page refresh which would then lose the data anyway.
I'm trying to avoid XY problem where the problem is X and I ask about Y, so what's the right way to remove the variable from the URL?
You can use the History API, but it does require a modern browser
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
More information here:
Manipulated the browser history
Your question seems to indicate that the target page is not and will not be powered by some server-side script. If that's the case, I'd suggest changing the querystring to a hash, which has the advantage of being directly editable without triggering a page-load:
http://yourdomain.com/page.html#search=value
<script type='text/javascript'>
// grab the raw "querystring"
var query = document.location.hash.substring(1);
// immediately change the hash
document.location.hash = '';
// parse it in some reasonable manner ...
var params = {};
var parts = query.split(/&/);
for (var i in parts) {
var t = part[i].split(/=/);
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
}
// and do whatever you need to with the parsed params
doSearch(params.search);
</script>
Though, it would be better to get some server-side scripting involved here.
It's possible to rewrite the URL using JavaScript's history API. History.js is a library that does this very well.
That being said, I don't think there's any need for removing the query-string from the URL, unless you're dynamically changing the contents of the page to make the current query-string irrelevant.
You could post the data, then let the server include the posted data in the page, e.g.:
echo "<script> post_data = ".json_encode($_POST)." </script>";
This works cross-browser.

Categories

Resources