How to pass value from html file to php file - php

I am new to jQuery,Ajax and all, I don't know to pass a value of html file to php file.
For Eg:
my html file as
<html>
<script>
$(document).ready(function(){
$(".teachers_but").click(function(){
//alert('teacher');
var id=0;
alert(id);
});
$(".students_but").click(function(){
//alert('student');
var id=1;
});
});
</script>
<div class="teachers_but">TEACHER SIGNUP</div>
<div class="students_but" style="text-align: center; margin-top: 8px;">STUDENT SIGNUP</div>
</html>
How to pass id value in html file to php file and set cookie for that value.

I think this question comes up somewhat often, and the comment answers are correct; but you also have to understand what's happening during the request. I'll try to keep it kind of simple.
On the SERVER, PHP processes all the PHP tags of your file, and turns it into a file consisting of pure HTML, Javascript, and CSS. The server sends this to the CLIENT (the person with the web browser hundreds of miles away). That client doesn't even know what PHP is, and the server will actually then shut down that little PHP environment it had created; all variables are destroyed, and it waits for the next client request to process a page again.
Using a specially-coded in-page request, often referred to as AJAX (Asynchronous Javascript and XML, the XML part being a misnomer) you can start new requests against the PHP server to save information, request new information, etc, without loading a new webpage.
HOWEVER, your specific question has a unique aspect to it; you want to set a cookie. Although you normally only see cookies when working in PHP, the cookies are actually stored on the client's computer, and are sent to the server on each request. Javascript is able to access them on its own, and some libraries can help with that.
I haven't followed this tutorial myself, but a quick Bing search found this, which might help you: http://www.electrictoolbox.com/jquery-cookies/

Related

Javascript Which Uses XMLHTTP Request To PHP File On Same Host Violates Same-Origin Policy? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Please explain JSONP
On page 'www.foo.com', can a script loaded from 'www.example.com' send ajax requests to 'www.example.com'?
I need to make a request from a javascript to a php file.The php file then pulls data from a database, and then sends the information back to the javascript.I figured the best way to do this would be to make a javascript which uses XMLHTTP to ask the PHP script for the information. Both the Javascript file and PHP file are on the same host.
The catch is that I'm calling the javascript on a different domain. This means I can't set the XMLHTTP.open to a different domain because of the Same-Origin-Policy.
Am I out of luck even though technically both the javascript and php files are on the same host? What is the best way around this? I saw some mentions of using JSON.
The other catch is that I CAN NOT use jQuery. I know things would be easier if I could use jQuery -- but I can't.
This is a pretty close approximation of what I'm trying to do, with the exception being that my request has to be cross-domain:
http://www.w3schools.com/php/php_ajax_database.asp
Any ideas? I'm open to alternative solutions. Thanks!
I think the focal point of your investigation should be the "domain mess":
For the client side, it is of no importance, whether the 2 domains are on the same host: Only the domain counts
For the server side, this ofcourse is different.
You might be trying to create some sort of interop between two applications on the same server - this might be achievable by some self-proxying or by simply creating an interop domain, loading the relevant parts from there.
self-proxying: Use rewrite rules or a proxy setup to make http://domain2.tld/ajax.php map to the content of http://domain1.tld/ajax-domain2.php
interop domain: have http://domain3.tld/domain1/ map to http://domain1.tld and http://domain3.tld/domain2 map to http://domain2.tld and load everything from domain3.tld
I suggest you to use JSONP (http://en.wikipedia.org/wiki/JSONP) if HTTP GET is enough. (You don't need to send binary files to you server).
It's pretty simple idea. First you create a callback to process data from the server.
var callback = function(data) { alert('My name is ' + data.user) };
Then you add script element in the DOM:
<script src='http://external-domain.com/api.php'></script>
which returns json result wrapped with your callback function
callback({ user : Aaren });

Can I check whether Java is enabled from PHP

I would like to detect whether java is enabled in the user's browser when they use my website(php).
If java is enabled a certain div loads on the website if not another div loads.
I do the following:
in the PHP header file: (so whatever loads it checks whether java is enabled)
<?php $no_java=0;?>
<noscript><input type="image" src="whatever.jpg" id="java_checker" value="1"></noscript>
This a 1px by 1px transparent image which can't be seen but it's better than a text box which can be seen.
if(java_checker==1){
$no_java=1;
}else{
$no_java=1
}
I've been programming in PHP for a few months now. I know that the if(java_checker==1) is not right but I don't know how to check the value without submitting a form etc...
Anyone could tell me how to do it? the value="<?php $no_java=1;?>" is not good because the php part seems to load regardless to the <noscript> tags :(
Any idea? Or any other idea how I could "tell" php that there is no java so do whatever...
PHP is a server-side language whereas Java applets run inside the browser.
That means PHP can't directly detect whether the useragent has a Java plugin installed or not. In theory, it could, if there was a relevant HTTP request header but there isn't.
At best, PHP can emit JavaScript which then runs some tests inside the browser and reports back to server via AJAX.
See How can I detect the Java runtime installed on a client from an ASP .NET website? for details.
You are taking it wrong way.
It's not in PHP you have to detect if Javascript enabled, but in JS itself.
Just make your PHP always enabled, but if JS is present too, let it take some job. Easy
First, I think you are confused between Java and JavaScript. Lack of JavaScript is dealt with the <noscript> tag, but I guess this approach will work fine for "Java applets" as well.
The key idea here, is that the only information PHP has about the browser is the "User Agent" string. This specifies which browser this is. The process of making a website work well with or without Javascript is called "Graceful Degradation". You can read about it elsewhere.
There is no way for the PHP to tell whether JavaScript is enabled or not. The least complicated workaround is to create a test page, which looks like this:
<html>
<script type="text/javascript">
window.location.href = "myapp.php?js=enabled";
</script>
<noscript>Click here to continue</noscript>
this would allow you to say $javascript_enabled = $_GET['js'] === 'enabled'; and determine whether JS is enabled or not.
Note that this is a very wrong method of building applications. You need to account for both cases.

How to parse content loaded by javascript after the dom is complete

I have been working on parsing some of the data from the wow armory and have come into a bit of a snag. When it comes to the site serving up the achievements that players have received, it uses javascript to intemperate a string such as #73:1283 to display the requested information. (I made this number up but the data for the requests are formated like this).
Is it possible to pull data from a page that requires javascript to display its data with php?
How do you parse data from a site that has been loaded after the dom is ready or complete using php?
By using Firebug, I was able to look at the HTTP headers to see what AJAX calls were being made to generate the content on these pages: http://us.battle.net/wow/en/character/black-dragonflight/glitchshot/achievement#96:14861 and http://us.battle.net/wow/en/character/black-dragonflight/glitchshot/achievement#96
It looks the page is making an asynchronous call to load this page: http://us.battle.net/wow/en/character/black-dragonflight/glitchshot/achievement/14861 when the part after the hash is 96:14861, and a call to http://us.battle.net/wow/en/character/black-dragonflight/glitchshot/achievement/96 when the part after the hash is just 96. Both of those pages return XML that can be parsed to render HTML.
So generally speaking, if there's just one number after the hash, just put http://.../achievement/<number here> as the URL. If there are two numbers, put the second number at the end of the URL instead.
What you'll need to do, rather than pulling the Javascript and interpreting it, is make HTTP requests to those URLs by yourself in PHP (using cURL, for example) and parse the data on your own.
I would really recommend learning JavaScript and jQuery, since it will be very hard for you to really build a good site that pulls information from the WoW Armory without understanding all the AJAX loads that are going on in the background.
I would recommend seeing if you can replicate the query sent by JavaScript in PHP. While I don't believe there is a way to process JavaScript in PHP, there definitely isn't a simple or scalable way.
I would attempt to scan the first page's source that you downloaded with PHP for strings of that format you mention. Then if the JS on their site is querying something like http://www.wow.com/armory.php?id=#72:1284 you can just download the source of that next. You can find out how the JS is querying the server with something like FireBug or the Inspector in Chrome or Safari.
So in summary:
Check to find the JS URL format and if you can replicate it.
Create PHP to get main page and extract all strings.
Create PHP to loop through these strings and get these pages (with URL that JS requests).
Do whatever you wanted to with that information.
You can try jquery's $(document).onready function which helps
to run java script code when the web page loads up.
ex
<div id="wowoData">#4325325</div>
<script>
$(document).ready(
function(){
$("#wowoData").css("border","1px solid red");
}
)
</script>

Caching data by using hidden divs

I'm trying to speed up response times in my ajax web application by doing the following:
Say the user requests a page whose contents don't change (e.g a web form). When the user makes a different request, I 'cache' the form by putting it in a hidden div. Before displaying the new information. So the form is basically still loaded in the browser but not visible to the user. If the user requests the same form again, it gets loaded from the hidden div. That's notably faster than doing a round-trip to the server for the form.
I do realise doing so with lots of data will probably degrade performance as the browser gets to keep a lot in memory. But I will place a limit on how much gets "cached" this way.
Now, I came up with this on my own which is why I'd like to know if there is a better/established way of doing this. It works as expected but I don't know what the possible drawbacks are (security-related perhaps?).
I would appreciate any suggestions.
Many thanks.
I've done this before. It can be a useful technique. Just make sure the data is accurate and that you support JS disabled user agents.
EDIT: And that there is no better solution.
Storing the HTML code for your form in a JS variable is probably more efficient than having a hidden div with the interpretation of this HTML code (form + form fields + various markup).
If your form code is generated at the same time as the page, simply print it in a JS variable :
<script language="javascript">
var myFormCode = '<? echo $myFormCode; ?>';
</script>
(That's if you use PHP...other languages shouldn't be far from that)
If your form code is generated later, you can send it as text via JSON :
<?php
echo json_encode($myFormCode);
?>
...and then build your form when needed, with something like that on the client side :
<script language="javascript">
myRealFormDiv.innerHTML = eval(myJSONEncodedTextIGotViaAJAX);
</script>
JS code is obviously not exactly what you need to type in, but you probably see my point.
This should work and is the best solution I can think of. Whether there are any security implications really depends on your forms and how they work - nobody will be able to diagnose this without actual code.
What about use APC or Memcached ?
They'll allow you to keep the html markup clean, with not 'hidden tricks' that could potentially create problems (user dont have css enabled? use IE6? what about accessibility?)
Depends on your needs, but in general way the page must contain just what it must containt, nothing else.
Another way of doing this is to set the "Expires" or "Cache-Control" HTTP headers for the form.
If you set an "Expires" header 1 hour in the future for url http://example.com/form.html, then the next time within an hour that the user navigates to that form the HTML will be loaded without touching the server.
If you properly version your images/CSS/JS and give them far-future "Expires" headers as well, then there will be no server roundtrip, plus you'll help the performance the rest of your pages.

Page changed in JQUERY

I am trying to found out how to see if a php file has changed and then show a div with saying Page changed in JQUERY
You'd better do that in PHP using filemtime, no need for JQuery here.
You only need jQuery for this task if you're trying to detect the page change without waiting for the user to request a new page. If not, do as the other responder suggests and use PHP.
But if you need to do it without a page reload, use one of the $.ajax() methods in jQuery in combination with a JavaScript timer. You'll have to poll the server periodically (thus the timer) to ask if the page has been altered.
You would also need to set up something on the server that can tell your page about changes. Perhaps a very simple service that provides the timestamp of the last edit in JSON format. Use $.ajax() to poll for the timestamp, then compare it with the last edit the page knows about. If the timestamp from JSON is more recent, display your div.
Javascript cannot access the server, you will have to use some sort of server side technology. Like PHP that was suggested by Pekka.
In short, javascript is client side, which means it interacts with the user on their side, while php is server side, meaning it interacts with the server. Checking the file modified date is a server side issue, your client isn't serving the pages (unless you're on freenet)
Or you could output a <meta> tag for when the page was updated with PHP or whatever framework or language you are using. Then create a cookie with your JS and compare the cookie with the meta tags content.
Ugly solution but it would work. I wouldn't want to resort that this however.

Categories