Confused on the basics of AJAX - php

So right now, I'm just using a basic form to check a password. I want it to check the password and basically remain on page.html so I can use JavaScript to alert incorrect password or something. I'm not really sure how to do that. It seems it would bring me to check.php. I'm not too sure on the whole process, any help appreciated! Thanks!
Page.html
<form action="check.php" method="post">
<input type="password" name="password" />
<input type="submit" value="Submit" />
</form>
check.php
<?php
$password = $_POST['password'];
if ( $password != "testing" ) {
die();
}
?>

PHP runs at the webserver which usually runs at a physically different machine (the server side) than where the webbrowser runs (the client side). The machines are usually connected by a network. HTTP is a network protocol. The webbrowser sends a HTTP request. The webserver retrieves a HTTP request whose URL indicates that it should be forwarded to PHP for further processing. PHP retrieves the HTTP request and does the processing and returns a HTTP response. Usually in flavor of a plain vanilla HTML page. The webserver sends HTTP response back to the webbrowser.
JavaScript runs at the webbrowser and knows nothing about PHP since it runs at the webserver. PHP in turn also knows nothing about JavaScript (although it can produce some JS code which is in turn to be sent to the webbrowser over HTTP). The only way to communicate between JS and PHP is HTTP. One of the ways to let JS fire a HTTP request and retrieve a HTTP response is using XMLHttpRequest. This is the core technique behind Ajax.
I see in your question history that you're already familiar with jQuery. It's a JS library with a lot of convenient functions to fire ajaxical requests. In this specific case you would like to use $.post. E.g.
$('#formId').submit(function() {
$.post('check.php', $(this).serialize(), function(valid) {
if (valid) {
alert('Valid!');
} else {
alert('Invalid!');
}
});
return false; // Important! This blocks form's default action.
});
With in check.php:
<?php
echo $_POST['password'] != "testing";
?>
This is however not unobtrusive. If the user has JS disabled, then all will fail. Your best bet is to check in PHP if an ajaxical request is been fired by jQuery or not and handle accordingly:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
// Ajax.
} else {
// No ajax.
}
Alternatively you can let jQuery also reach a different URL or append an extra parameter.
Update: here is how the JavaScript would look like when not using jQuery:
document.getElementById('formId').onsubmit = function() {
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
alert('Valid!');
} else {
alert('Invalid!');
}
}
}
xhr.open('POST', 'check.php', true);
xhr.send(serialize(this));
return false; // Important! This blocks form's default action.
}
function serialize(form) {
var query = '';
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if (!e.disabled && e.name
&& ((e.type != 'checkbox' && e.type != 'radio') || e.checked)
&& (e.type != 'submit' || e == document.lastClicked))
{
if (query.length) query += '&';
query += e.name + '=' + encodeURIComponent(e.value);
}
}
return query;
}
document.onclick = function(e) {
e = e || event;
document.lastClicked = e.target || e.srcElement;
}
Bloated and verbose, yes ;)

You'll have to use ajax if you want to remain on the same page. I recommend using jquery and jquery's post function.
Basically you create a javascript function that gets called when the login button is clicked. The function will send a request to check.php. Check.php will output a status message (maybe 1 for succes, 0 for fail) that will be returned to the original script. From there you can output a message saying invalid password, or set a cookie if it was correct.

The simple solution to what you're trying to do (essentially AJAX) is:
Modify your php script to output something unique on success or failure.
Use JavaScript to submit the data to the php script, instead of the normal form POST.
Have the JavaScript alert the user if the password is invalid, or direct to an appropriate page if the password is valid.
Of course those are the broad strokes. In reality you'll need your php script to give one kind of response when an AJAX request (a request made by JavaScript) is made, and another response when the page is requested by a regular form POST - you do want it to work without JavaScript - right? You'll probably want the JavaScript to update the page contents instead of an alert box. You'll want your php script to set session variables so the next page they access knows they are logged in.
Broad strokes.
Reading the jQuery AJAX documentation may help.

When designing a web site, always add JavaScript after everything works fine without it. The reason for this is twofold. For one, some people browse without it turned on. The other reason is that JavaScript is always viewable and editable by the crackers out there.
This approach requires that you have a separate PHP file that validates the success of the password. Everything on the original page (HTML and JS) should only send the password and perhaps wait for the request. To keep things on the same page, you can use AJAX to send the input password and print out the response that it receives. jQuery makes AJAX easy if you don't want mind the overhead.
Using POST over HTTPS is better than using GET and HTTP. Of course, keep track of session variables and you might also want to limit the amount of time from when one first receives the form and when they actually submit it.

Related

how can i use php codes in javascript file while php is including the javascript variable?

cuIzgaraKay is a javascript code I want to use it in sql command as cuIzgaraKay.id(it gets the value correctly I checked it). However, I could not it. I googled it but I can't find what I search . How can i do it ? sorry for asking syntax error but I can't find it maybe ı have logical error
if(cuIzgaraKay){
<?php
include_once('../phps/kutuphane/inc.php');
$result = mysql_query("select id from bolge_db where parent_id="?>+ cuIzgaraKay.id + <?);
As far as I can tell, you're trying to execute an SQL query from the PHP page, using data from the Javascript code you're generating.
The Javascript is only evaluated on the client side of your page. That means that the server-side cannot know anything about the Javascript code.
What you need to do, is to generate the ID, and communicate it to the PHP backend, for example with a HTTP POST/GET request or something.
EDIT:
If you're new to Javascript, I'd suggest you look into the native JS object XMLHttpRequest. You use it like this:
/*
params:
url: relative URL on host, e.g. '/users/morten/data'
method: GET, POST, PUT, DELETE, HEAD or OPTIONS
data: data to send with request, e.g. POST form-data
ok_cb: function to call on success
fail_db: function to call on failure
*/
function http_req(url, method, data, ok_cb, fail_cb) {
var client = new XMLHttpRequest();
client.onreadystatechange = function () {
if(client.readyState == this.DONE) {
if(client.status == 200 || client.status == 302 || client.status == 304)
ok_cb(...);
else
fail_cb(...);
}
};
client.open(method, url, true);
client.send(data);
}
Or you can use jQuery or a ton of other frameworks to do the same thing.
EDIT:
what is method in there how can i write there and how can i get data from php – user1702486
The method is whatever HTTP request method you want to use. See the wikipedia page for more info: http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods
This code will POST to /page.php sending a data-string along.
If the request returns a successful code, the ok-callback will be called.
// handle HTTP OK
var ok = function(meth, res, url) {
console.log("OK: got " + res);
}
// handle all else
var fail = function(meth, res, url) {
console.log("UTTER UTTER FAILURE!\n" + res);
}
// make a HTTP POST to server/page.php sending the data along
// you can serialize the data and use XML or JSON or whatever instead
http_req("/page.php", "POST", "username=usr&password=passw&userid=12345", ok, fail);
On the PHP page, you will need to handle the POST by checking the data and returning an answer if appropriate. Something like this:
<?php
if (empty($_POST))
{
print_r($_POST);
...
// do something with the data and print something back
}
?>
If you've posted "data1=1234&data2=5678&str=hello%20mum" the $_POST array will look like this:
(
[data1] => 1234
[data2] => 5678
[str] => "hello%20mum"
)
You can't, javascript is client side and php is server side. So the php code gets executed before the javascript.

How do i get the response back from server after issuing a request object(AJAX)

I was studying about AJAX and it was about form validation where as soon as the person fills in the username for signing up, it is checked using AJAX while he still can enter all the other fields. so i issued a request and on readystatechange i called a callback function. now i have studied PHP before this, but i never came across returning information from the server. I mean to say that what all goes in my PHP script, and how does i make sure that the request issued is responded as desired. i dont want the exact code, if just bits of it,or the algorithm can be improved,
For example, i know i passed the username along with the url to the php script, and then i checked if it matched any of the existing usernames in my database(MYSQL and queries) , and normally i would just print the form again if there's a match, else i will exit();
but what do i do when i want to respond back to the object request?
It's really quite easy when you get the hang of it. It's even easier if you use jQuery's AJAX, http://api.jquery.com/jQuery.ajax/ - though don't bloat your site with this unless you intend on using loads of javascript (and use google's cdn for it)
In javascript, you make an XHR request either GET or POST to your PHP script. Usually you'll need to create a separate file for the view to any AJAX requests, because AJAX requests shouldn't bring the webpage's template back as well (i.e. if you wanted to return '1', it should only return '1', not <html><body>1</body></html>. ... etc.
Example:
blah.com/index.php needs some AJAX requests.
blah.com has javascript that creates the ajax request by sending a datastring/url (e.g. ajax.php?act=verify_email&email=a#c
blah.com/ajax.php would then have some PHP code that could switch($_GET['act'] or $_POST['act']) with a 'case' statement of 'verify_email'. That code would run some regex or something, and return 1 or 0 to say 1(valid), 0 (invalid). The 'onreadystatechange' holds the status of the request, so I think its usually a function i.e.:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
You access the returned '0' or '1' through the xmlhttp.responseText, where xmlhttp is var xmlhttp =new XMLHttpRequest();
Then you just run the request
xmlhttp.open("GET","ajax.php?act=verify_email&email="+document.getElementById('email').value,true);
xmlhttp.send();
Update: In your case with the form, onblur (when they move out of focus of an element), you could run the AJAX request sending the value of the input, and then in the ajax.php script as a GET or POST request, you could run your validation query to check if the user exists already, or if the username isn't valid or whatever. Once the request has completed, it will return the results in the responseText value. Use firebug's console to check the result of an AJAX request if you can, its very useful.
This might not be what you mean but can't you:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
// do something with "xmlhttp.responseText"
var x = xmlhttp.responseText
}
And in the php just:
echo $x;
That works fine for transmitting strings and other info...

How to make PHP function run after javascript ends?

I have two PHP functions - one that builds a html form and another that handles it when it's submitted.
I want to add to the html a javascript onClick function that sends one of the form's fields to an external API (Google Maps) and saves the reply in a hidden field in the form so that the handling PHP function will get that data as well.
My question is - how do I make sure the handling PHP function only fires after the onClick function has finished?
Or maybe I can't and I have to use ajax?
You'll need 2 events to accomplish this.
the onClick event for your button that executes the google map request and saves the data into the local form
an onSubmit event for your form. You will use this event to see if the form is submittable. Basically, check to make sure that your google map request has been run and has completed before allowing the form to submit.
Example:
<script>
var googleMapsDone = false;
$('#gmap_button').click(function(event)
{
doGoogleMapThing(function()//callback from googlemaps
{
//save data to local form for processing by script once posted
googleMapsDone = true;
});
});
$('#form').submit(function(event)
{
//check to see if we did our google maps stuff, and that its done
if (false == googleMapsDone)
{
event.preventDefault();
return false;
}
});
</script>
With that code, any time the user is waiting for google maps and clicks submit, nothing will happen. They would have to wait on the response from GMaps, THEN click submit. This is okay for some things, but if you're trying to do background requests to GMaps that require no user input/interaction/feedback (maybe getting Long/Lat of their address when they submit a form), then you can modify the code a bit to post when you get the response. An example of that would be:
<script>
var googleMapsDone = false, submitWaiting = false;
$('#gmap_button').click(function(event)
{
doGoogleMapThing(function()//callback from googlemaps
{
//save data to local form for processing by script once posted
googleMapsDone = true;
/* check to see if submitWaiting is TRUE. If it is, automatically
post the form when we get the response.
*/
if (submitWaiting)
{
$('#form').submit();
}
});
});
$('#form').submit(function(event)
{
//check to see if we did our google maps stuff, and that its done
if (false == googleMapsDone)
{
event.preventDefault();
/* set our submitWaiting flag which we will use in our clalback
so when we get our google maps response, we post our form right
away
*/
submitWaiting = true;
/* You might want to display a modal or some other kind of notification
that the form post is 'working' or 'processing' so when the user
clicks it and doesn't see anything happening, they don't bail
or click it 800 times out of frustration
*/
return false;
}
});
</script>
edit: I realize my comment below on how this works are...hard to understand, so let me explain here, then show an alternative.
User fills out form
User clicks button to do stuff on google maps (example was written before I knew the scope/context of the GMaps request, so that's why it's done this way)
If user then clicks 'submit' before the GMap request is complete, we CANCEL the submit and set a flag submitWaiting
GMaps request returns, and executes our callback. Our callback knows how to look for submitWaiting and if it is set to true it submits the form
An alternative to this, instead of requiring user interaction for the GMaps request you could change the event to an onChange event for the input box of the address, or you can do it all via the submit button/event, like so:
<script>
$('#form').submit(function(event)
{
//lets look up our user's address!
doGoogleMapThing(function()//callback from googlemaps
{
//do stuff with your inputs, or whatever
$('#form').submit();
});
event.preventDefault();
return false;
});
</script>
edit note: the examples above assumes you're using jquery, and that your google map API request is done via javascript
If your google map api request is not using the google maps javascript library, this is STILL possible, just requires you to make a "proxy" script to the API via a php script on your local domain. (Browser restrictions). It'd be something like THIS:
<script>
function doGoogleMapThing(callback_when_done)
{
$.post("/path/to/proxy/script.php", { data: to, post: to_server }, function(response)
{
//check & parse response
callback_when_done(/* Data needed to populate form */);
});
}
</script>
note: both of these examples assume jquery usage. because...well..why wouldn't you.
Below is an implementation of your exact script. I changed it a bit to use jquery, because it makes things a bit less painful.
<script type=”text/javascript”
src=”http://maps.google.com/maps/api/js?sensor=false”></script>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type=”text/javascript”>
function codeAddress(callback)
{
var address = $('#address').val();
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
$('#latitude').val( results[0].geometry.location.latitude );
$('#longitude').val( results[0].geometry.location.longitude );
if (typeof callback != 'undefined') //call the callback.
{
callback(true);
}
}
});
/* Just in case google returns a bad response or doesn't return at all
we need to add a timeout that will call the callback after 10 seconds
just so we make sure our user doesn't hang.
*/
setTimeout(function(){
callback(false); //pass false indicating no/invalid response
}, 10000); //10000ms = 10s
}
/* We are using the reallySubmit variable as a flag here, to know when we finish
our call to google maps and that we want to really submit our form.
we have to do this because the form.submit() call fires the form's submit event
again, and we end up going into an infinite loop.
an alternative to this would be to bind your form processing to the form's submit
button's click event. that should also pick up any presses of the enter key, also.
the solution below also works.
*/
var reallySubmit = false;
$('#form').submit(function(event)
{
if (false == reallySubmit)
{
//lets look up our user's address!
codeAddress(function(success)//callback from googlemaps
{
reallySubmit = true;
$('#form').submit();
});
event.preventDefault();
return false;
}
});
</script>
This is fundamentally impossible - PHP runs on the server, JavaScript runs on the client. You will indeed need to use Ajax.
You can have a hidden IFRAME element where you load a php document as soon as your javascript ends. Simple, but effective (as long as your php document comes from the same URL).
AJAX is a must I am afraid. You need to redirect the user to a page with the script.
Once the server has run the PHP to generate the HTML, then sent it to the browser, there is no way to run it again, or indeed run anything from the server, without making a request to the server. That is the nature of a server side scripting language, of which PHP is.

Is it possible with javascript to find file's last modified time?

Is it possible? Now, I have done live chat, where with jquery's help I connect to .php file and check last modified time and if it is not as before, I retrieve messages. If it were possible in javascript I probably would save a lot of resources.
Thanks.
It's definitely possible if the server is sending an accurate Last-Modified header for that particular file:
var getMTime = function(url, callback) {
var xhr = XMLHttpRequest();
xhr.open('HEAD', url, true); // use HEAD - we only need the headers
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var mtime = new Date(xhr.getResponseHeader('Last-Modified'));
if (mtime.toString() === 'Invalid Date') {
callback(); // dont want to return a bad date
} else {
callback(mtime);
}
}
}
xhr.send();
};
getMTime('url here', function(mtime) {
if (mtime) console.log('the mtime is:' + mtime.toISOString());
});
Short answer: there's no way but AJAX + a server-side script (in your case, jQuery + php)
Being a client-side script, javascript gets run on the client's computer, so if the file whose m-time you want to check is on the server, then you are correct to use AJAX and a server-side script. No other way will work.
If the file whose m-time you want to check is on the client's computer, then you're out of luck. Javascript is intentionally designed to be prevented from accessing the client's files. (It can only access cookies, which are on the client's computer, however, because the browser (not any javascript) loads those into its work environment.)
Maybe HTTP ETag headers could be used to check if the page has changed. The first response contains ETag and your client uses that for the following request. Your PHP server side code would then send 304 if the page has not been modified.
http://en.wikipedia.org/wiki/HTTP_ETag

[PHP/JavaScript]: Call PHP file through JavaScript code with argument

I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.
<script>
function SetRowInCookie(NewCookieValue)
{
try
{
alert(NewCookieValue);
document.cookie = 'row_id=' + NewCookieValue;
loadCookies();
}
catch(err)
{
alert(err.description);
}
}
function loadCookies() {
var cr = []; if (document.cookie != '') {
var ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
var cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
alert(cr['row_id']);
}
</script>
I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.
Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.
Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.
jQuery ajax example;
$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:
$.post(url, params, callback_function);
Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.
AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.

Categories