Reload Methods: responseText vs. window.location.href (1 trip vs 2) - php

After an Ajax call I reload a web page. I have two options..
I can send the page as responseText and have it write to the screen using document.write().
I can send a control to Javascript telling it to reload the web page using window.location.href.
Option 1 is good because it takes only one round trip instead of two. However the onload Event was not triggered as it would with a normal reload.
Option 2 is good because it triggers the onload Event.
Is there any way to to get the best of both worlds...i.e. I would like to send the page using responseText but also have it loaded like a new page, once it is recevied.
I simply does not make sense to make 1.5 trips instead of .5 trips when you are on the server (control is on the server) and need to reload the page. Is this a weakness of Ajax or do I just not know hot to do it?
Related:
Caching Issues
*
Similar Post

Ok from what I see you want to load a new page when an user registers. The best way to do this is without ajax. As the page gets loaded and the onLoad event gets fired.
But you also want to check if the email the user used is already in use. The way I like to do this is to make a variable and set it to false. The use the onchange event of the email input field to run an ajax validation. And if the email is available and valid I set the variable to true. And I add a function to the button's onsubmit event and return the variable. This way the user gets redirected only if the email is available.
Or:
You can move all of your code from the onLoad event into a function. And simply call it when you get set the page using response text. And rather than using 'document.write()' I'd recommend using document.body.innerHTML and document.head.innerHTML.

Don't use AJAX for this, or even JavaScript at all for that matter (except for form validation, of course). You can use plain old HTML 2.0.
<form action="processSignup.php" method="post" onsubmit="return isFormValid();">
<!-- input fields here -->
<input type="submit" value="sign up" />
</form>
I'm no PHP expert, but the server code should not be complex. Make your database call, then redirect to the next page. It could be exactly the same code as from your AJAX example.
Don't try to over-complicate this. This is the basic pattern that's been used from the early 1990s. (Or earlier, I'm not sure, I didn't have internet access before then.) You don't gain anything by using AJAX patterns here.

Related

Writing PHP output into textfield

I've tried looking around for the answer to this but I can't seem to find it.
I have a database which takes in two pieces of information and returns it either as successful or unsuccessful.
I would like to be able to press a button "Submit" and then run my PHP query(which is fine) to print out an echo into a textbox once it has been completed.
echo '<form name="enrolled" method="post" action="<MY FUNCTION HERE>"><select name="course">';
Once my function is complete, it will echo something out. I would like for a textbox display that echo.
The problem I have been having is that it wasn't working in realtime, I could easily get an echo to display on a textbox but I cant get it to stay blank and then once the function has completed, populate the box.
Thanks for taking the time to read.
As nathan says you seem tobe a bit confused about php works. It writes HTML (or other stuff) which is sent to the browser where it is rendered. Until you send another request back to the server, PHP sits idle. If you don't want to transition from the current page but update it's contents then you need to create javascript that, when triggered makes a request to the server (and takes appropriate action when the server responds.
If you Google for PHP Ajax tutorial you'll find lots of examples.
Not elegant at all but just echo the whole field...
echo "<input type='text' name='something' value='the value you want to echo'>";
Not really sure what you are trying to do in your PHP.
The html form action attribute it is supposed to be a URI, not a javascript function.
For update in realtime a form, or just a input, you can use javascript and perform ajax request. If you want make it fast and quickly I recommend you use Mootools Request class for make a ajax update in your form.
You can see a full demo example of ajax real time updates (HTML, PHP, Javascript) in Mootools site.
Two ways of doing it:
Via Post and refresh:
your form you be something like
script.php
<?php
$result = "Hello world!"; //Do your logic anywhere but be sure to set the result here
?>
<form method="post" action="script.php">
....
<input type="text" value="<?= $result?>" readOnly>
<input type="submit">
</form>
the other way is via AJAX
that will take a lot more research. Try this one, it's much simpler!
You need to post your form using AJAX and then display results in the box. It's easy done with jQuery library. To include jQuery library just add this to your html head
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
Then you can submit your form using this script
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'post.php',
$(this).serialize(),
function(data){
$("#result").html(data)
}
);
return false;
});
});
post.php in the name of the script you are calling that will receive the form and return the answer. myform is id of the form and result is id of the box you want to display results to.
You are thinking about PHP the wrong way; PHP doesn't interact with the web browser directly. What you need is AJAX. Here's why:
The client (web browser) sends a request to the web server (apache, lighttpd, etc.)
The web server interprets that request, and (in this case) hands it over to PHP
PHP echoes the result based on the input given to it by the web server
The web server sends that result back to the web browser
The web browser determines what to do with that information
Now, if this is you navigating to a web page, the web browser renders the content generated by your web server (which used PHP to generate it). If the web server has already responded, that's it - you've got your response. To get more information, you'll have to make a new request, which means you have to do one of these two things (typically):
Navigate in your browser by submitting a form, reloading, navigating to a new page, etc.
Use Javascript (which is executed by the client, not the server) to make a "background" request
The technique of using Javascript to make a request "in the background" and update the page without reloading is called AJAX, and there are many ways to accomplish the task, but by far the easiest and most popular method is to use the JQuery library, which is a wonderful kit of useful functions and additions to Javascript that make it less painful (even enjoyable!) to work with - including a simple function for making AJAX requests using the POST method.
There is a lot to learn on the subject, but hopefully this will give you a solid enough understanding of what you need to know to accomplish this task.

How can I pass data from one page to another using PHP and Javascript?

I have 3 buttons (image links, eventually will evolve to javascript or something better though)
Each of these buttons should send a value to a handler script, which does choice 1 if button 1 is pressed, choice 2, so on and so forth.
I'm wondering what the best way to do this is. I DON'T WANT TO USE GET. I'd like to use POST if that's possible but I don't think it is. I thought about cookies too but the problem is even though you can call a JS function to create a cookie via a link, you can't go to the PHP page for processing, within the same click can you?
It would work like the user clicks the button img, then it takes them to the handler script, but the handler redirects them back before they even know they were there.
Again this isn't a form, I need to do this with a hyperlink. I suppose I could just have a different page for each choice, but I don't think that's efficient.
Thanks!
If you want the variables to be passed using POST, you could create a form on the page, and have your links execute some javascript code at onClick. They'd set the variable to the desired value, then submit the form. The key lines would be something like:
document.getElementById("user_choice").value = 2; // or whatever the value for this link is
document.getElementById("my_form").submit();
You could turn your image links into:
<form method="post" action="blah">
<input type="hidden" name="function" value="function1" />
<input type="image" scr="whatever" />
</form>
This way they still look like images, but are actually post forms with whatever you want inside of them. That's the easy way anyways. The harder way would be to use AJAX.
In case you want to use JavaScript, have a look at jQuery. Using jQuery's click-method, you can easily handle clicks on elements:
Suppose you have this HTML:
<div id="target">
Click here
</div>
<div id="other">
Trigger the handler
</div>
Using jQuery, you can easily track click on the element labeled target:
$("#target").click(function() {
alert("Handler for .click() called.");
});
In case you don't want to POST or GET clicks directly, I'd propose to register jQuery click-handlers, which set JavaScript variable based on the clicked element.
Note, that jQuery's click-handler can be registered with any element, not only forms. Furthermore note, that e.g. the above click-handler does not POST or GET the page to the server.
Additionally, have a look here, on how to prevent the browser from submitting forms: What's the effect of adding 'return false' to a click event listener?
Even better than JavaScript is CoffeScript, which compile to JavaScript but makes live much easier. Give it a try!
what about AJAX? it's the best choice for your problem and the bonus part is you can use post too.

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.

HTML toggle button for simple site using php possible?

I've got a simple website using plain HTML/CSS to display and PHP/MySQL for data storage.
Now I'd like to add a toggle button similar to facebooks "like" button.
How can I act on the user pressing the button (add database record for this item, change button text) without leaving the page?
I thought this question would have been asked and diskussied to no end, but all solutions I found require some other frameworks than plain PHP as background.
You'll need to do it with javascript. Read up on "AJAX form posting".
A high level view:
user clicks on button
you capture the click via an onclick handler in javascript, and use it to call a javascript function
said function does a remote url request via XmlHttpRequest to a target page
that target page takes in the parameters passed via POST or GET and performs actions with them (eg add database record), and prints out any response required
the javascript function reads the response and acts accordingly (eg change button text)
and all this happens without refreshing the page.
You can do all this with pure low level javascript code, but plenty of libraries already abstract it while solving various issues with browser compatibilities. I'd suggest the jQuery javascript library. It provides an easy way to do exactly what you require, and good documentation.

just php no javascript

Just using php, is it possible to
create a button via html that reacts to the user's input, for example, if the user clicks the button 4 times, something is suppose to happen, or do I need javascript.
Likewise if the user clicks the button twice or three times something different is suppose to happen, is this possible, if so, what do I need to read?
Yes it is possible with just PHP. You could carry the state of what has been inserted along with sessions or put it back into the form so that it’s submitted with the next insertion.
Do you mean as in real time? In that case, no, it is not possible.
You could use sessions to track submits, but without the use of of JavaScript (Ajax) the user would have to watch the page reload for 4 clicks. If your going to use Ajax you might as well just code some JavaScript to send data based on click sequences.
In reality you need JavaScript.
If the button is going to do an action without refreshing the webpage, then PHP can never do that for you.
Likewise, if you don't mind the page refreshing each time the button does an action. You can wrap the button in a form that posts GET/POST(to be secure) values for the PHP script to read.
<?
$times = $_GET['timesClicked'];
$times++;
?>
<form method="get" action="your script">
<input type="hidden" name="timesClicked" value="<?= $times; ?>">
<input type="submit" value="your button">
</form>
This is ideal use-case for using Javascript.
You will need to bind your custom function to elements onclick event.
Here is a sample code you can include into your html code. It assumes you've specified button id:
<script>
var clicks = 0;
function yourfunction() {
click++;
if (clicks == 4) alert ('Your clicked 4 times!')
}
document.getElementById('elementId').onchange = yourfunction;
</script>
If it's acceptable to you for the browser to load the page anew with each click, then, yes, this is quite possible with PHP alone, using either a cookie, a server-side session, the URI query string (i.e., ?num_clicks=2 at the end of the URL), or a hidden form field to track the number of clicks. If you really wanted to, you could even do it in plain HTML by creating a separate page for each stage/state and looping through them, advancing one step on each click.
If you want the page to react to the click immediately without contacting the server or if you want to refresh only a portion of the page without reloading the whole thing, then, no, that would require JavaScript.

Categories