jQuery autocomplete - Hide php request page contents - php

I have an input field that autocompletes using text taken from a PHP page. It works well but is it possible to hide the text on the PHP page if it's accessed directly? I realize that the way it works it's as if the user actually visited that page but is there a trick that would allow that?

This should work, place it at the top of the page
if($_SERVER['HTTP_X_REQUESTED_WITH'] !='XMLHttpRequest'){
die();
}
jQuery automatically sends headers with AJAX reqeusts

No, you can't: as you say it's the user who's requesting the content (well, the user's browser), so the content must be accessible by the user, every "cloaking" technique can be easily defeated by a slightly skilled user.

The first trick I can think of is to use http headers.
On the code to load data for your autocomplete set a custom data that your php page reads to write his content otherwise you show nothing.
When a user try to access the page directly (put the url on the browser) it show nothing because browser do not put your custom header
$.ajax({
url: "data.php",
type: "GET",
dataType: "html",
headers: {custom:'showdata'},
success:function(){}
});
I use this trick to let my page knows what kind of content type to return because some times it should be json and other time it should be html
Obviously it's not perfect but many users won't see the data your trying to hide

Here's a simple way to make it a --little-- more well hidden. On the autocomplete data source page, check for a variable of any name you choose. For example:
if ($_GET['ninja'] != 'chop') {
return 'Sorry, this page is not directly accessible';
} else {
//data generated and returned here
}
Yes, it can be defeated. But take into consideration, "what's the point?" Are you storing mission critical data? Is it really not to be seen? This is the reason that many small websites contain horribly unsecure and XSS vulnerable code and yet never get hacked...it's just not worth it for a hacker to spend the time developing a custom hack to get to the data that's there. Hacking Windows, on the other hand, provides millions (billions?) of targets to do all sorts of nefarious things. I'm certainly not saying that your site's not important, but it doesn't seem like a case where triple redundant security is necessarily required.

Related

randomise image only on "revisit"

Current Situation
I've currently got three divs. Let's call them LeftDiv, CenterDiv and RightDiv. LeftDiv and RightDiv both contain an image that randomises every time the page gets "reloaded", ie when you press F5, or visit a different page on my website. This is done using javascript.
Visiting different pages on my site is done with page IDs, like:
Homepage is website.com/index.php
About page is website.com/index.php?page=about
etc
etc
Visiting different pages basically only changes the content on my CenterDiv (which is obviously located in between the LeftDiv and the RightDiv). However, the background images also once again randomise. Which is probably because the page refreshes.
Desired Situation
What I basically want is those images to only randomise (again) when the visitor either refreshes or revisits the website all together (like entering the web-address in the browser again). What this most likely would require I believe is to not have the entire page refresh when a new page ID gets visisted, but rather only refresh the CenterDiv. So now we get to...
The Question
Is there a way to accomplish this? If so, how? What methods are recommended to use?
Thanks in advance for your help.
jQuery makes AJAX calls so much easier. Might want to check it out here
http://api.jquery.com/jQuery.ajax/
For your problem, I think something like this might work:
function changeDivContents(page)
{
$.ajax({
type: "GET",
data: "page="+page,
}
});
}
And then, in the link give an onclick= "changeDivContents('page_you_want_to_load')"
You need to change only content of your CenterDiv. This can be achieved with AJAX calls.
http://en.wikipedia.org/wiki/AJAX

Is my logic correct? Ajax and/or PHP with Mysql

I have a page which shows a list of items. Page coded with html, css, php and using mysql db.
On that page a user can request to add one of the items to their special list.
I want to do this within the page without having to do a complete page refresh. So user clicks button to add, item is added to their list and button changed so they can't add it again.
Do I use ajax calls to run code behind the page and then refresh the div?
Or is there a better more efficient way to do it.
I'd prefer a php option of possible in case user has js turned off, but don't know if it can be done with using js.
Any help appreciated.
If you want dynamic content (changing the page without refreshing) you are going to have to use Javascript. To do what you are asking, you could call a PHP script via Ajax that outputs the contents of the div with the new item, and then change the div based on that response.
Dagon is exactly right. Create a form which handles the request and set the action of the form to the PHP script you want to handle the request. Note that although this can be the same php script that you use to process your ajax request, it does not necessarily have to be.
Many times when I implement such functionality, I'll set the PHP to send variables as POST (in the event of JS disabled) and have my ajax request as a GET so I can use a single PHP page to handle the 'same' request. When using AJAX, I'll have the script echo a specific code then have the ajax response handle that return.
if(val == 'OK') {
//in event of success, perhaps you want to hide the original form and show a success message
} else {
//do something like unhide a hidden div to display an error
}
If JavaScript is turned off, the page has to be reloaded. In your case jQuery could be very handy and simply rewrite the element you need to rewrite. The server send's a simple json. Using a PHP Framework might also be a good idea, since the way you ask it seems (with respect, and not wanting to offend), that you are not using any framework and might run into falls making your script vulnerable (sql injections for example)
If your visitor doesn't have JavaScript enabled and you want to serve anyways, then you have to do a page reload. First check if that is worth to do, who is your client/visitor, what browser do they use, ... questions like that help you to design your page/app.

Loading new content on the page via a link without changing the URL

I am working on a social network website similar to facebook. But, I am facing a rather confusing stage in the programming.
I am done with the register/login/logout pages/scripts, and you can view profiles with the www.mywebsite.com/profile.php.
Now, I want to do what facebook does and allow users to click links while on their profile page (info, notes, photos) but never actually leave www.mywebsite.com/profile.php — just the appropriate content is printed to the screen.
How is this done? I am not asking anyone to code this for me, just point me in the right direction!
You can use Ajax for this purpose.
Put the content that you want to replace in a div and using ajax replace that div and only send that content.
Are you trying to do something like this?
http://www.99points.info/2010/05/how-to-create-dynamic-content-loading-using-ajax-jquery/
That will have to be done via Javascript and Ajax.
A javascript function will fire when the link is clicked. An ajax request is sent to the corresponding php script which sends back a response to your javascript function. You then parse this response and place it on the screen.
If you go that way, have a fallback option that does not rely on javascript as well in case a user has JS turned off.
You Can use this reference...
function showdiv(id)
{
if(id)
{
var selected_offer="yourpagename.php"
HTML_AJAX.replace('divname',selected_offer);
}
}
call showdiv on onChange() function of your link..
For this, you need the technique known as Ajax, which is short for asynchronous JavaScript and XML. The basic idea is that when the user does something - in your case clicks on a link or button - instead of loading a page, a script runs that calls on a server side script to send back some data. This is sometime XML, but you can get other types of data back as well. The asynchronous part is that the user and the page can go on doing other things while waiting on your script to return the data you asked for.
There's a good book for beginners in Ajax that I read myself: Head First Ajax. Looks like you can pick up a used copy for about $10. It's a nice intro, has a quirky style that appeals to some, and the authors do whatever they can to keep your attention. Hardcore programmers probably won't like this one, but I sense you're a little newer to the game and this may be a good read. Otherwise, Google "learning Ajax" and there are a bajillion resources.
Good luck!
To respond to your comment, you can set up a "router" script that takes input and runs a specific function in response. This "router" function looks at the $_GET[] superglobal for a parameter like "action" and then calls a corresponding function. If not action parameter is sent over, the router calls a default function.
Now for a little more detail. Your page script would have 3 basic parts: The router, the various action functions, and the page template function. The router just calls the appropriate function from the action functions and passes the output into the template function. Here are a few examples.
The user arrives on the page, index.php. No action is specified, so the router finds $_GET['action'] == '' and it calls default_action(). This returns a welcome message, status, whatever, and the router passes this output to the function that displays your page, output included.
Now the user clicks a link/button for updates and arrives at index.php?action=update. $_GET['action'] == 'update', so the router calls update_action(). The output goes on to the template function for display.
Does this help you envision how you might accomplish this?

AJAX VS PHP for dynamic web pages?

Why use AJAX for dynamic web pages when you can do it only with php?
The main reason to bother with AJAX is User Experience (UX).
Now AJAX won't necessarily improve UX in every single instance so in a lot of places sticking with pure PHP is perfectly okay.
But imagine the case where you have a text field on the site and a link to vote on something. Kinda like this site. When you add AJAX your users won't loose the text they entered in the textfield when they decide to vote on the link! How incredibly useful!
So if you care about your user's experience it is a good idea to use AJAX in situations like that.
PHP creates and outputs the Content to the Client Browser as it's a Server-Side Language and that's what it was built for, so on a request your code will access database, files etc. and then output the constructed html/text to the client.
Ajax just gives the User a more Desktop like feel. For example deleting a record and instead of the entire page reloading just letting the one element disappear from say a list and letting the server know that the record is to be deleted. But Remember to let the User know when you are busy sending data to the server (With a progress bar in .gif format for example). As lot's of user feel that if nothing happens on the screen to notify them, that the application is frozen which means they will either reload the page or just try to click the button again.
But you will need to provide some sort of compatibility with browsers that have Javascript disable and thus cannot use your AJAX functions, just something to keep in mind.
AJAX stands for Asynchronus Javascript and XML, meaning that a page can get new data, without having to reload a page.
PHP cannot send data without reloading the whole page. A user has to press a button, to send data.
An example of AJAX is for example google suggestions or the tag suggestions on this website.

Ajax search workaround when JavaScript is disabled

I have a search page on my site. The search pulls from a couple (eventually a few) API from external sources. Sometimes a search can take up to 5 seconds.
Because of this, I would like to load my search page at least with a loading gif, and let AJAX begin to pull the data, showing a bit at a time. (similar to http://gamespot.com although this is a bad example since the search doesn't work with JS disabled)
Of course I have to consider the users who have turned Javascript off, so for them I'd just let PHP do the search and they'll have to bear with the wait.
What is the best way to implement this? If I use <noscript>, then all users still have to wait for the 5 second PHP portion to load anyways.
Would I just have the search form send the user to different pages depending on their JS status?
Perhaps have the noscript part define an iframe that loads the results from the long-duration PHP query?
Would I just have the search form send the user to different pages depending on their JS status?
If you have the users coming to your page, and then sending the form, that's absolutely the best way to go. E.g.:
HTML:
<form id='theForm' action='long_search.php'>
....
JavaScript:
hookEvent(document.getElementById('theForm'), 'submit', function(event) {
event.preventDefault();
loadAjaxSearchResults();
return false;
});
...where hookEvent is a function that uses addEventListener or attachEvent (on IE).
Off-topic: The hookEvent thing, like a lot of this stuff, is easier if you use a library like jQuery, Prototype, YUI, Closure, or any of several others. For instance, with jQuery:
$("#theForm").submit(function() {
$("#resultsTarget").load("ajaxsearch.php", $(this).serialize());
return false;
});
Without JavaScript, you will need to post the data to the server and perform a full postback (refresh) on the page. Just like the good ol' days. ;)
no you apply your js code (autocomplete if i understoof right?) up to an input field. Think of Javascript like an extender. If js is disabled, no autocomplete is extended on the input field. You may put some text, where you say, dude, turn on js otherwise this will be a long search. And if js is on, hide the text
Progressive enhancement:
Build it so the PHP version works, first and foremost. This is accessible to all. Then, add javascript so that, if available, it performs ajax requests behind the scenes to grab the content and update the current page.
See this book as a simple, great read on the subject:
Bullet Proof Ajax

Categories