I am a little bit new to the PHP/MYSQL arena, and had an idea to be able to interact with my Database by using a hidden Iframe to run PHP pages in the background(iframe) on events without having to leave the current page?
Good? Bad? Common Practice? Opinions?
This is most of the time bad, but sometimes inevitable.
The common practice to do it is to use AJAX, it's so common that even W3School has an article about it.
The advantages of using AJAX over IFrame is that AJAX can be multi-threaded. You can send several requests in a row, which is more troublesome to implement with IFrames. Moreover, AJAX supports status code so you can detect errors, where with IFrames you'd have to rely on scraping the page's HTML and hope you've determined the correct status by looking at the error page's HTML code.
AJAX is more JavaScript idiomatic and event driven, which means your callback will get notified automatically when there is a response. With IFrame you'd have to setTimeout() and keep polling the IFrame for a response, which may break easily.
IFrame is sometimes inevitable in cases like where you want to upload a file without leaving the current page. But that's probably not your scope since you mentioned only database interactions.
Learn to use XMLHttpRequest, which is the foundation of AJAX. After you've become familiar with that, try making it fun by using a JavaScript framework such as jQuery, Dojo, etc.
I'd guess something is supposed to happen when your database does something, right? I.e. your page should give some sort of feedback, maybe update a number or some text.
So you're going to use Javascript anyway. In that case, skip the iframe and just send off AJAX requests.
This is commonly accomplished using AJAX. The jQuery javascript library makes this easy
I don't think using iframes is a good way to accomplish this. You would still need javascript enabled to change the location of the iframe, and if javascript is available, why not just use AJAX?
If you use the iframe, you wouldn't be able to receive a response from the server in any meaningful way without doing a lot of workarounds. For example -- using jQuery, you could submit some information to the server with a single function call, and then when that request completes, a callback function can be invoked with response information from the server:
$.post("ajax.php", { var1: "data", var2: "moredata" },
function(data){
alert("Server says: " + data);
});
In this example, when the request completes, an alert box appears with the output of ajax.php.
With an iframe, you might do something like change the location of the iframe to server.com/iframe.php?var=data&var2=moredata&var3=moredata, then wait for a bit, and grab the contents of the iframe (if this is even possible) and do something with that.
Not to mention, when you run into problems doing this, you'll probably ask for advice on SO. and each time, people will probably say "drop that and use jQuery!" :) may as well skip all the pain and suffering and do it the Right Way to begin with
The hidden iframe method was used before the adoption of XMLHttpRequest api (Maybe you have heard of it as Ajax).
Years ago I was using a former implementation using rslite but nowadays this technique has, to me, just an historical value.
You can get directions on using Ajax techniques in plain javascript at http://www.xul.fr/en-xml-ajax.html or, better, you can choose to use a common library, jquery or mootools among others, to deal with the different implementations in different browser.
Related
I have a form which i'm sending with jQuery post function to a php script.
The in the php script i do some checkings and send back a response with a formate like so:
$output = json_encode(array('type'=>'error', 'text' => 'your id is wrong!'));
die($output);
in the page where i have the form i can use a simple way to fire some functions based on the response. for example:
if(response.type == 'error'){
output = '<div class="clienConError">'+response.text+'</div>';
$(".results").hide().html(output).slideDown();
}
which means if it is the response is set as error type one do this and that...
My question is:
Is it possible to send back a jQuery function? so instead of saying: if it's a response set as error type do this. i say never mind what response is it, just do what the response tell you (for example hide some element, inject some html some where and so on... all kinds of jQuery functions).
If it is possible it will give me a few advantages. one of them is the ability to actually hide some jQuery functions (in the php script).
Although this is generally not recommended, it is possible to return JavaScript code from a PHP script, preferably with the appropriate Content-Type: text/javascript header.
At client side, you may execute the generated code using eval or injecting it in the page via a newly created <script> tag.
Dynamic scripts are discouraged for several reasons:
Harder to maintain: the generated code is –by essence– not static, and thus you can never see and edit the whole code as with a static file.
At best sloppy from the security point of view: allowing execution of arbitrary code is never a good idea, and attackers will more than certainly try to leverage this to perform client side attacks such as XSS.
Not friendly towards optimizers: contrary to a whole static script which can be parsed and optimized as soon as the file has finished loading, multiple fragmented bits of script cannot benefit from optimization.
Moreover, attempting to hide client code is a battle already lost. If the code is executed client side, then it is visible client side, period. Any user, and I insist, any user, can open the F12 debugger of their browser and place breakpoints or use step-by-step mode. More savvy users might overwrite the eval function or hook the beforescriptexecute event to inspect what’s going on. And there are even more ways.
The best you can do is obfuscate your code, with possible loss in performance and complexification of your workflow.
The only way you could really do this is by returning a javascript expression in text (wrapped in double quotes) in a JSON object. You would then need to eval() the response which isn't great for a variety of reasons - injection, performance, debugging.
I'd suggest against this approach anyway as you are overlapping the boundaries of what a client and server should be doing - tightly coupling both layers.
It is possible using eval() but it is not recommended due to performance and security reason. eval() executes the argument passed to it. So you can send the jquery function as a string and pass it to eval() to execute it on client side.
Sample Code:
var command= 'var output = \'<div class="clienConError">Here is the response</div>\';$(".results").hide().html(output).slideDown();'
eval(command);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='results'></div>
I have a PHP page with a simple form. One input text field & a button. Input text field accepts user queries & on button click an HTTP GET request is made to the server & the result has to be shown back in the same page containing the form. That's too simple to do. I can do this in two ways. One is AJAX & other one is the good old sodding form-submit method.
My question is simple- Which method should I use? Since both of the roads lead us to the same place, which one should I choose to travel?
First of all, let me talk about form submit method. I can use <?php echo $_SERVER['PHP_SELF'] ; ?> as the action of the form for submitting the values of my form to the same page. Once I store those values into some random variables, I can make a GET request & obtain the result & show it to the world. This method is easy to use. Happy Down Voting to all of you.
Or I can make a GET request using AJAX and jQuery or JavaScript or whatever you wish to use & obtain the same result as in the previous case. Output is same. Only the mode of execution is different.
So which one is better? Which one fetches result faster? And why should I use that? Is there any difference? GET, POST, PUT or whatever- it doesn't really matter. AJAX or form-submit?
There shouldn't be any significant, genuine speed difference between them.
The Ajax approach will load a smaller amount of data (since you aren't loading an entire HTML document), but by the time you take into account HTTP compression and the fact that (if your system is sensibly configured) your dependancies (images, scripts, stylesheets, etc) will be cached, it won't be significantly smaller.
By using JavaScript to create a loading indicator and not refreshing the entire window in front of the user, you can create the illusion of a faster load time though. So if feeling faster was the only concern, then Ajax is the way forward.
Using JavaScript, however, is more complicated and slightly more prone to failure. The consequences of failure states are more severe because, unless your code detects and does something with them, the user will (not) see it fail silently. For example, if a normal page load times out because the user is on a train and went through a tunnel, they'll see an error page provided by their browser suggesting that they refresh and try again. With Ajax, you need to write the error handling code yourself. This does give you more flexibility (such as allowing you to simply try again a few times) but the work isn't done for you.
The other consequence of using Ajax is that the address bar will not update automatically. This means that the results won't be bookmarkable or sharable unless you do something explicit the make that possible. The usual way to do that is pushState and friends, but again, it is more work.
You should also make the site work without JavaScript so that if the JS doesn't run for any reason then the site won't break completely. If you use pushState then you have to do this for the URLs you are setting the address bar to point to to be useful.
The short answer: Use a regular form submission, then consider layering JavaScript over the top if you think it will give your visitors a worthwhile benefit.
I Should stick to an Ajax request when possible.
This because you then don't really have to load every single item on the page again ( like all the images, menu and so on ). You can just give the relevant HTML back and JQuery can place it inside the relevant holder.
But that is just my humble opinion...
If you have to retrive simple data from server without reload the page my advice is use jquery .get o .post
also it provides you a very large API that allows you to reduce your programming time.
http://api.jquery.com/
obviously the execution time increase but in my experience the user cant fell the differce with a simple ajax request.
so in my opinion if jquery allow you to obtain the results, this is the best solution because halves your work time!
See the edited one it may help you.
I think that AJAX should be used for displays updates and form submissions should be done via a page reload. Reasoning?
When submitting forms, you are telling the application to do something. Users tend to want to feel that it was done. When a page doesn't reload, users are often left wondering "Did that work?". Then they have to check to make sure what they did was right.
but when you are displaying a table or something, and the user says to "display x data....now x1 data" for instance, they aren't "doing" something (creating new entities, sending emails, etc). So AJAX can provide a nice user interface in this case. Page reloads would be annoying here.
In conclusion, I think form submission should be done via page reloads (let the user see it working), whereas display updates should use AJAX (prevent annoying page reloads).
Of course, this is a preference thing. Some of my company's applications use AJAX all over. But those are the applications that are the most difficult to maintain and debug. ;)``
I am thinking of developing a website in PHP and I was thinking of using AJAX in order to send data to, and retrieve data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.
So my question: would it be better to use AJAX to GET or POST to php pages or any other options are possible?
There are not that many options when it comes to submiting data, either you use AJAX or use the normal http message like GET or POST. If you would like to determin witch is better i would say: it depends.
Ajax seems to me like a great way of making more dynamic a part of your site, but i dont think its always practical to use in all your site. Ajax is generally used when you need to show some context change on one page, like posting a commner, faving a question, or things like that. Another great thing about it is not to bound user to a form (you can save info with a link like when you vote a question here)
Using GET or POST its usefull to let the user now here's moving along a process or when things that happen after or before are different, or context change a lot when submitting.
Rule of thumb (regardless of AJAX).
If you're going to send large amounts of data, or sensitive data... POST.
Otherwise, GET works just as fine.
I recommend use JQuery.
with $.ajax of Jquery, you can use it with multiple options depending that you need.
So you can work with POST, GET, receive data like text, json...
Here you can get more info:
http://api.jquery.com/jQuery.ajax/
I always use $_POST. I wish I could give a reason why I think it's better, but I can't. I guess it's because I've always preferred sending data via POST rather than GET so the user doesn't see it, and it just carried over to my ajax.
I would use $_POST just for the fact that it can store more data.
I'm having to interact with the Facebook API for this project, which I find to be actually a bit slower than I expected. Because of this, I'm having to do something which I find rather unorthodox: I need to load the content Facebook provides back in my PHP script AS IT LOADS from Facebook. Traditionally I've loaded content into a div tag at the success of the script; however, I need to load the content as it appears. It would be absolutely unacceptable to have a client wait nearly a minute for Facebook to load an album and all respective comments before displaying anything. Hopefully I'm not being to vague; I'm not here to ask for code, but I've tried just about everything I can think of. Is this a simple concept I'm missing?... I feel as though this is easier than I'm making it.
I'm using jQuery AJAX as I find this easiest to work with. Any comments and/or help would be greatly appreciated.
The root of your problem is that jQuery's AJAX methods hook into the onreadystatechange event and readyState variable. readyState is only set to 4 when the file is completely transferred, and therefore your events will only fire after the download is complete.
Accessing the data as it is being sent is not consistent across different browser families. Doing it this way is going to be incredibly complex and time-consuming. I would recommend first doing this a little differently, perhaps by preloading the relevant facebook data on your own server predictively. This can be compiled to a static page, and that can in turn be served to your users very quickly.
To get the data to your users faster, you'll need to work outside the box as well. There's a jQuery plugin discussed here ( Does PHP flush work with jQuerys ajax? ) that makes jQuery ajax methods compatible with streamed output. Good luck.
The problem seems to stem from the fact that you're getting too much data at once. I suppose you are talking about receiving content from ajax as it is printed out immediately, but it is possible this content is built and sent at once and you won't have access to the data until the entire parse is complete. If this is untrue, look into COMET. If it is true, the solution is to put a limit on how much data you retrieve at once in an effort to reduce the parse time. For example, retrieve 5 photos in each request. Add those 5 photos to the DOM while you retrieve the next 5.
Instead of putting whatever code you want inside of the callback, just put it after the callback
for example
$("#div").load("facebook...", function() {
//do stuff
});
//put the stuff you want to load at the same time, here
Are ajax requests more resource-intensive than a normal page load?
For example, I have a simple menu with normal links (when you click on the link you get on a page).
With ajax, I can prevent this behaviour on click and request the link's href with ajax (GET), then get the html I want from the results and insert it in the current page. Does this use more resources than the normal link behaviour?
I would use ajax requests only if you want to add enhanced value to the page, by changing the look/functionality after the user has interacted with the page.
It probably doesn't necessarily use more resources than just clicking on the link, but it is definitely faster for the user because it doesn't need to reload all the other content on the page as well.
Most of it has to do with the type of experience you are trying to deliver.
I would try both as an experiment and see which feels better to you!
No, it doesn't use any more resources on the server. On the client, it's possible to write inefficient code but that would be a fault of how you load pages, not the actual downloading of the page itself.
No extra server resources are required to deliver the content. Take a look in firebug / fiddler / charles. From the server's POV, the requests are identical.
If implemented right AJAX can cause less server load than normal page requests. If you just serve a data request (a little JSON array incoming and outgoing) you do not typically need to instantiate the whole CMS. Simpler handler scripts often suffice.
In your case it sounds like you are just using $("#link").load("frompage.php #link") or something. In which case it makes no difference.
(Request limiting is sometimes advisable for security reasons, or preventing complete database scraping. Not applicable in your case.)