I'm developing userscript for one webpage (aka browser plugin). I need to update one global Javascript variable (lets call it gVariable (it is an array)) with the one I get with ajax request.
In ajax request I'm requesting for the same page I'm on. But just want to "extract" that one global variable and replace current one with the one downloaded.
This is something I have now (not working).
function LoadNewItemList() {
$.get(window.location, function (data) {
var $data = $(data);
unsafeWindow.gVariable = data.gVariable; //I'm getting 'undefined'
});
}
JS test:
http://jsfiddle.net/ywVKT/15/
Looking at your fiddle, there are mainly 4 tags. i.e.
"title" , "link" , "ul" , "script". That's why you need to use index as 3, since the script tag contains the variable name and value.
Try this and it would work.
$('#variableHere').text(data2[3].innerText);
it will return you following o/p: var gVariable = 0; gVariable = 5
Now you can use regex/substring function to extract the vairable name and value..
I found solution:
unsafeWindow.gVariable = 0;
var $script = $data.filter('script:contains("var gVariable")').first();
eval($script.text());
unsafeWindow.gVariable = gVariable;
Related
I am trying to pass a variable through an HTML page, and I got it working, but when I changed to a server, the HTML pages go from 'page1.html' to 'page1#' After this change I can no longer send parameters to my second page as they come out as 'undefined'. The passing of the variable works, it's just retrieving it.
The URL looks like this: http://localhost:1337/page1#?34
Here is the old working code on that no longer works:
// Takes parameters from HTML address and passes it through
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(0);
var queries = queryString.split("&");
var placeHolder = queries[0];
var Final = parseFloat(placeHolder)
I want to extract the number 34 from the URL and store it in a JS variable.
Thanks in advance for any advice
I'm not getting your point if you want some data from one page to another, so you can use localstorage for example
//index1.html
<script>
localStorage.setItem("item1", 34)
</script>
//index2.html
localStorage.getItem("item1")
var item = localStorage.getItem("item1");
</script>
I got a code that replaces a string. Here is my HTML created by my PHP code.
...
foreach ($notes as $note) {
echo '<li><input name="noteTypeID" type="radio" class="noteTypeID" value="'.$note['NOTETYPEID'].'"></li>';
}
...
foreach (...) {
...
echo '<li class="getshrtcode">[srms_more_info id="'.$cnt.'" instanceID="'.$val_id.'" type="'.$val_type.'" noteCodeID="" planID=""]</li>';
...
}
my script is like this:
jQuery(document).ready(function(){
var noteTypeID = null;
var planID = null;
jQuery('.noteTypeID').click(function() {
noteTypeID = jQuery(this).val();
planID = prompt("Enter a Template planID value from axcelerate");
jQuery('.getshrtcode').each(function(){
jQuery(this).text(jQuery(this).text().replace('noteCodeID=""', 'noteCodeID="'+ noteTypeID +'"'));
jQuery(this).text(jQuery(this).text().replace('planID=""', 'planID="'+ planID +'"'));
});
});
});
the 1st change is fine but the next is not. I see that it can't re assign the .getshrtcode text because the planID and noteCodeID string have value. Is it possible to turn it noteCodeID="" planID="" again?
You are trying to set a non-DOM entity with jquery which is not possible. When you have a template engine to generate HTML, the template code gets executed and gives results before any javascript loads, so you cannot set template properties unless the template engine itself provides you a mechanism to do this.
If you really want the customer to specify a certain template plan ID to present him with something specific, you need to load your page through an AJAX call where you send a request to the server passing noteCodeID & planID and respond with the desired HTML that comes as a result of the custom template engine execution.
If you have custom attributes in your HTML that you want to set using jquery, then you can simply use attr function :
$('#foobar').attr('foo','bar');
CONTEXT:-
This question is about some basic concepts about AJAX. I have been following this tutorial and this example for the JS part, and this (the last one on this page) for the PHP part.
So suppose the scenerio is that the JS is invoked on the click of a button. Now when the button is clicked and the JS function is invoked, the entire web page is already loaded. So if I pass a variable from JS in the URL passed from the XMLHTTPRequest.open() function (and using the GET method), the variable is sent to the $_REQUEST array on the server-side.
1. Now since the page has already been loaded, so how can I make changes to, say the value of an element's attribute, while the element is already displayed.
SCENERIO:-
I have a PHP array with HTML for three div's, and they are echoed/displayed. Initially all the divs except the first one have a display:none; style property. Now on the click of a button in the first div, I want to call a JS function where I set display:none to the first div, and display:block; to the second div. Now that is easy. But I want this change in the display property in the HTML for the respective div in the aforementioned array on the server side as well.
So I figured I need AJAX. Following this example, I tried sending a variable in URL, and then tried to get the variable from $_REQUEST, but $_REQUEST does not seem to contain it. Although I asked this question here, but I feel it might be because the part of the page where I am writing the code to get the variable from $_REQUEST is already executed, I am wondering where should I write the code to execute only after the click of the mentioned button?
2. Basically where do we write the AJAX script since the code for the page is already executed?
NOTE:- Don't suggest JQuery. I can't use JQuery, I can use YUI though. I searched SO and found solutions using some JQuery method.
JS CODE:-
function xyz(var divIdOne, var divIdTwo) {
document.getElementById(params.divIdOne).style.display = "none";
document.getElementById(params.divIdTwo).style.display = "block";
document.getElementById(params.divIdTwo).style.border = "5px solid red";
var xmlhttp;
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();}
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
Where in the server side PHP script do I write the code which receives the variable from the URL so that it is executed after the button is clicked (the button whose click event invoked this JS fucntion).
I was trying to do something like this at a random place in the server file but it does not work out:
foreach($_REQUEST as $requestkey => $requestvalue) { //loop for just checking the elements of $_REQUEST
echo $requestkey.': '.$requestvalue;
}
if (array_key_exists('pass_back', $_REQUEST)) {
foreach ($array_of_divs as $div) {
if ($div->id=$divIdOne) {
$div->style='display:none';
} else if ($div->id=$divIdTwo) {
$div->style='display:block';
}
}
} else {echo 'FALSE!';}
Let me see if i understand correctly:
You set the display property on some div with js.
You want to update some flag on your server so next time a request is made you get the same display properties as the client.
AJAX is asynchronous, so you can call it wherever you want (your button click, document ready, etc).
Make an AJAX request to some url in server that can answer it and update your flags with the values you want. You may need some kind of persistence to keep those for the next time you reload your page or you won't notice any change.
Make sure you understand what AJAX is.
Here's an example of an AJAX function:
function ajax(url, method, send, success){
var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP'), ec = [], s, sl;
if(send){
for(var i in send){
ec.push(encodeURIComponent(i)+'='+encodeURIComponent(send[i]));
}
s = ec.join('&').replace(/%20/g, '+'); sl = s.length;
}
else{
s = null; sl = 0;
}
if(method.match(/^get$/i)){
s = s === null ? '' : '?'+s;
x.open('GET', url+s); x.send();
}
else{
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.setRequestHeader('Content-length', sl);
x.setRequestHeader('Connection', 'close');
x.open('POST', url); x.send(s);
}
if(success){
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200){
/* when PHP has processed what you send through `.send()` or a $_GET URL
your function will fire with the evaluated responseText passed to it
*/
success(eval('('+x.responseText+')'));
}
}
}
}
ajax('page.php', 'GET', {property:'value', property2:'value2'}, function(data){
/* when PHP has processed what you send through `.send()` or a $_GET URL
the anonymous function here executes sending what should be JSON
(if you `echo json_encode($associativeArrayYouMake);`on your PHP page)
through the data argument here - so data is JSON containing your PHP
Associative Array properties
*/
// affect the DOM
// document.getElementById('someId').innerHTML = data.some_property;
// or document.getElementById('someId').innerHTML = data['some_property'];
});
My code works, I can upload a file.
But how do I set typeNavn to something else runtime, so the value depends on witch tap is selected on the page.?
I want to either set typeNavn as either "billeder" or "dokumenter". Now it's always "billeder" from ViewBag.typeNavn, is that possible and how?
Is the action so static, that I can't change any of it's parameters runtime? I have tryed messing around with a callback, a JavaScript variable and a Razor variable. And it either doesn't work for me, or doesn't change it's first value.
var upload = $('#upload').wijupload(
{
// Note: the next two lines must be on one line for it to work.
// It's only two on SO so we don't have the x-scrollbar.
action: '#CleanHtml.Clean(Html,#Url.Action( "UploadFiles", "Dokument",
new { typeNavn = ViewBag.typeNavn } ))'
});
You need a JavaScript variable that can be changed dynamically, and then used as part of the action url.
var typeNavn = ''; // Declare this somewhere. This is updated by some means.
var cleanHtml = '#CleanHtml.Clean(Html)'; // I don't know what Clean() does.
var upload = $('#upload').wijupload(
{
// Note: the next two lines must be on one line for it to work.
// It's only two on SO so we don't have the x-scrollbar.
action: '/UploadFiles/Dokument?typeNavn=' + typeNavn)'
});
OK the layout of the above code may not be what you need (I don't know what cleanHtml is supposed to be), but the core idea of using a variable typeNavn is key here. You need some means of updating that variable to reflect the type selected i.e. a dropdownlist of something.
It's a bit unclear...do you have a radio/checkbox/etc where you want to change typeNavn or do you want to set that in the controller? Url.Action will render a string which you could certainly change using javascript. However in what context you are using this is a bit unclear.
Just going to guess that you want something like this:
$(".list").change(function(){
var list = $(this);
var url = baseUrl + "?typeNavn=" + list.val(); // How you get baseUrl variable is up to you
var upload = $('#upload').wijupload(
{
action: url
});
});
One thing you can do is pass the TabName in the action of controller as a parameter when loading view. And set the viewbag's value accordingly. So this will not be static and work perfectly.
second way, you can update querystring paramter name by jquery
You can use a placeholder value which can be replace with any desired value using the .replace() method. Here is pseudo-code. In example I have used -1 as placeholder value
Code
var typeNavn = '#ViewBag.typeNavn';
var action = '#CleanHtml.Clean(Html, #Url.Action( "UploadFiles", "Dokument",
new { typeNavn = -1} ))'; //Really have no idean
//Here you can use -1 as place holder which you can replace using JavaScript like
action = action.replace('-1', typeNavn);
var upload = $('#upload').wijupload(
{
action: action
});
Note: I have no idea about CleanHtml.Clean
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/