I'm using an to call a javascript function, like so:
<a onClick="AddCookie();">Click Here</a>
This is my javascript function, very basic:
function AddCookie(){
Alert ("test"):
}
Whenever the user clicks on "Click Here" I want a cookie created, now I am using ASP in Umbraco which means I can use C# code through HTML so I am creating a cookie like this:
HttpCookie IsDesktopCookie = new HttpCookie("IsDesktopVersion");
IsDesktopCookie.Value = "true";
IsDesktopCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(IsDesktopCookie);
Adding that to my function:
function AddCookie(){
alert("test");
HttpCookie IsDesktopCookie = new HttpCookie("IsDesktopVersion");
IsDesktopCookie.Value = "true";
IsDesktopCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(IsDesktopCookie);
}
However that doesn't work! I also tried adding <% %> around the C# code but it seems to break every time saying function "AddCookie" is not defined.
How do I get this to work?
Even though you can write C# Razor code inside a html page (or rather a cshtml page), you cannot execute C# in the browser just in the same way that you can't execute PHP in the browser even though you can use it within your html pages (or rather .php pages).
Any C# you write within your html template will be executed by the server when the request is made. You cannot interchangeably put C# in a javascript function and expect it to compile to javascript.
If you want to create a cookie on a button click, you can do so with javascript entirely:
function addCookie() {
document.cookie = "name=mycookie; expires=Fri, 23 Feb 2018 09:45:00 UTC; path=/";
}
You're then free to retrieve that cookie via javascript or use your C# code to check for the cookie at request time and render your page content differently on page load if that's what you're hoping to do.
If you need to create cookie in your javascript code then I will suggest you to look at jquery library
https://github.com/carhartl/jquery-cookie
In which you can easily create a cookie
$.cookie('name', 'value');
To read cookie value
$.cookie('name');
function AddCookie()
{
alert("test");
$.post(
{
type: 'POST',
url: '#Url.Action("CreateCookie")',
success: function(result)
{
//cokiee created
},
complete: function() {}
});
You can create or edit cookie like that. In 'CreateCookie' action, write your cookie creation codes
Related
I am trying to overwrite custom value to HTTP REFERRER. I got success with javascript but my client want in PHP and i need help in rewriting Javascript to PHP.
JS code :
var reff = ["http://example.com", "http://example.net", "http://example.org"];
var randomreff = reff[Math.floor(Math.random() * reff.length)];
delete window.document.referrer;
window.document.__defineGetter__("referrer", function () {
return randomreff;
});
document.write(document.referrer);
I am trying to rewrite this code in PHP or maybe finding a similar solution with PHP. i tried multiple way to do in PHP. these are some example.
PHP Try 1 :
$reff = new Arr("http://example.com", "http://example.net", "http://example.org");
$randomreff = get($reff, call_method($Math, "floor", to_number(call_method($Math, "random")) * to_number(get($reff, "length"))));
_delete(get($window, "document"), "referrer");
call_method(get($window, "document"), "__defineGetter__", "referrer", new Func(function() use (&$randomreff) {
return $randomreff;
}));
PHP with variable :
$var = 'var reff = ["http://example.com", "http://example.net", "http://example.org"];
var randomreff = reff[Math.floor(Math.random() * reff.length)];
delete window.document.referrer;
window.document.__defineGetter__("referrer", function () {
return randomreff;
});
';
PHP with header referer :
header("Referer: https://www.example.com/");
None of them worked. Help me to rewrite Javascript code or alternative solution with PHP.
You won't be able to do this with PHP exclusively. document.referrer is a DOM property that is set by the browser when the page loads by reading the referrer header on the request. Since the request is generated by the browser you can't really touch it with PHP since that is executed on the server and not in the browser, if you want to execute something in the browser you will need javascript.
In your examples you are just trying to run javascript-code from PHP it seems, and that just won't work. The last sample that sets the referrer-header will set it on the response back from the server, but as I said, referrer is a request variable so it will just be ignored.
The only thing you could do from PHP is to tell the browser to redirect to the page again (by setting the location-header), but as far as I know these days this won't reset the referral-header (if so then redirects from http to https for example would loose it all the time).
I'm not exactly sure are you trying to acomplish here. Setting document.referrer is only valid for the current page and won't affect what the next page sees. If executed early it might fool some tracking scripts at most.
I have simplified my Code to breakdown the Problem and to have a simple Example with a Timestamp for whats actually going wrong.
So please not be suprised why i do a AJAX call, this is for the real functionality of the Servlet.
Its a Servlet and the follwing code is part of a JSP page, im Working on JAVA 1.7 and a Tomcat 7. I run it in Firefox and Chrome.
My goal is to retrieve a value from a Java method and write it on the servlet page into the DIV "ContentCharts".
The Problem is that Javascript does not update the vaule of "zeit" and always writes the same Timestamp into the DIV-Container and on the Console
$(document).ready(function()
{
function ausgabe()
{
<%
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
String JZeit = df.format(now.getTime());
System.out.println("FKT ausgabe zeit:"+ JZeit);
%>
var zeit='<%=JZeit %>';
console.info('Zeit:', zeit);
document.getElementById('ContentCharts').innerHTML = zeit;
}
$("#subtab2").click(function()
{
$.ajax
(
{
url:'overview',
data:{dbname:this.className},
type:'get',
cache:false,
success:function(){ausgabe();},
error:function(){alert('error');}
}
);
}
}
To test this I write the value of the JAVA varible "Jzeit" into the Serverlogs and get this (Click to see the Picture) results when I click the buttons three times. As you can see in the Picture here I get the right Timestamps.
Now I have also post the Value of the JS varialbe "zeit" into the Firebug Console. And now i get the Wrong time Stamps (Click to see the Picture)
The Content in the DIV is refreshing but here is the same Problem like in the Console, its always the same Timestamp.
These are my thoughts and Questions:
Why has the JS variable the wrong value when its right in JAVA?
Is there any option to say JS that it has to update the variable?
Could it be that JS saves the answers of the JAVA code and does not run it anymore, but runs the upper JAVA Code Snippet because there is no direct connection betwen JS and JAVA, like a value allocation?
How can i fix my Problem?
If you need more Informations to help me please ask for it.
You're a bit confused about the ajax pattern.
Note that anything you write in <%= jsp tags %> will be rendered on the server, then sent to the client where it will never change. Therefore your ausgabe function will always return the same result when it is called. Subsequent calls to the function will not make repeated server requests, which is the behavior you're observing.
To fix this, the success function in your ajax call should take an argument which will be instantiated with the response from the server. The java code you've written in the jsp tags in the ausgabe function should be moved to the server and any variables you need should be returned from the overview endpoint. Then, the ausgabe function should be refactored to take an argument containing the server-calculated values, and update your page as desired.
Here is some reading on ajax requests:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://api.jquery.com/jquery.ajax/
How do I call a function from a component from a view? (ctp file)
I am using something like this:
App::import('Component', 'YourComponent');
$theComponent = new YourComponent();
$theComponent->yourMethod();
I want the line $theComponent->yourMethod(); to be executed on a button click but instead it is executed upon page load...
here is a part of the code:
<script type="text/javascript">
function assign()
{
var links_list = [];
var links =document.getElementById('unassignedUsers').getElementsByTagName('a');
for(var a in links) {
if(typeof links[a] == undefined) continue;
links_list.push(links[a].innerHTML);} var str =links_list.toString();
var array = str.split(',');
alert(array);
}
<?php App::import('Model', 'Account');
$account = new Account();
$account->insertPos();?>
}
<button id="button" name="button" onClick="assign();"> Save Changes </button>
//this is the button i need the function to be executed when i click....
Please tell me what to do make the php code inside the javascript to be executed only when the button is clicked?
echo $form->create('Account', array('action' => 'insertPos'));
echo $form->button('Save Changes', array('type' => 'submit'));
echo $form->end();
Both cakephp and the internet work on specific architectures. Granted with Cakephp, it is easier to "break" the architecture and create work arounds, it is very difficult on the internet. The internet uses a client-server architecture where HTML, Javascript, and CSS work on the client-side, also known as the browser and php (along with other languages) operate on the server side. The server only interacts with the client-side after loading with an HTTPRequests (the easiest being AJAX). Only an HTTPRequest will trigger the server side run and that will always be done through an URL. Hence, the following is a rough model in which you should be following.
Client-side <---- HTTPRequest ----> Server-side
Given this and working with Cakephp, in order to follow best practices and gain the most from Cakephp, your request to save should be sent to a controller with the following URL:
www.yoursite.com/controller-name/save
From here, assuming all values are in a form elements, your controller will only be sent the values in the form elements. Then within the controller the following should happen
$this->Account->insertPos();
Best advice, if you want to make your website dynamic. Familiarize yourself with AJAX.
I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});
How can I access an JavaScript variable from within an JSP page ?
My guess is that you're probably running Javascript on the client (in the browser), and Java in your JSP pages on the server. You can't access a client-side variable on the server. You can send a client-side variable's value from the client to the server for server-side processing. You'd probably do that via an Ajax call, or just by submitting a form.
Edit For example, this Javascript code sends the value of the foo variable to the server side page 'test.jsp' using the field name "foofield" (slightly different name to be clear). This uses Prototype, but jQuery, Closure, and all the other libs can do much the same thing, just with slightly different syntax:
Server-side Java (in the JSP) — this is just like getting fields from a form that's been submitted:
String foo;
foo = request.getParameter("foofield");
Client-side Javascript (using Prototype's Ajax.Request):
// Our client-side `foo` variable
var foo = "Hi there";
// Send it to the server via Ajax (Prototype version)
new Ajax.Request('test.jsp', {
parameters: {foofield: foo},
onSuccess: handleSuccess, // Function to call on success; not shown
onFailure: handleFailure // Function to call on failure; not shown
});
If you prefer jQuery for the client-side, here's that Prototype code rewritten for jQuery's ajax function:
// Our client-side `foo` variable
var foo = "Hi there";
// Send it to the server via Ajax (jQuery version)
$.ajax({
url: 'test.jsp',
data: {foofield: foo},
success: handleSuccess, // Function to call on success; not shown
error: handleFailure // Function to call on failure; not shown
});
You can't access it directly. That's because this is how a page is rendered:
1. On the server, the JSP code runs and generates HTML/JavaScript.
2. The HTML/JavaScript is sent to the client's browser.
3. The browser then renders the HTML and runs the JavaScript.
As you can see, the JavaScript is run way after the JSP runs, so they can't directly access each other's variables.
What you could do is output JavaScript code which initializes a variable based on a value in the JSP code. For example, if you generate code like this (excuse my syntax, I don't know JSP):
<script>
var JSPValue = /*jsp code that prints the value of a variable*/;
//rest of JavaScript code...
</script>
Then the JavaScript can accss JSPValue, just because it will have been put there by the server. For example, when sent to the browser, it might look like:
<script>
var JSPValue = 42;
//rest of JavaScript code...
</script>
Not possible. You can access a JSP variable in javascript but the javascript variable can not be accessed in JSP.
As the javascript is running on the client side and the JSp is running at the server side,it is not possible to access the javascript variable in jsp code,but u can acess that javascript variable in the server side by passing that variable along with the request as request parameters,As the request parameters are there in the request object which is available to jsp code ,u can access them.