Create objects dynamically with php - php

I have form with some objects. In case of a dropdown box, when the user clicks the button next to it, a new dropdown box appears under the previous one. The user selects an item, and if he wants, clicks the button again, a new dropdown box appears, he selects an item, an so on.
This is my code for the dropdown box and the button. I have no idea how to make such a thing.
<td>
<?php
echo "<select name=\"dropdown_docs_remove\" id=\"dropdown_docs_remove\">";
for ($i=0; $i<count($regulationsarr); $i++){
echo "<option value=\"$i+1\">$regulationsarr[$i]</option>\n";
}
echo "</select>";
?>
<INPUT TYPE=BUTTON NAME=btn_removedoc VALUE="+" ONCLICK="add_newdoc_to_remove()">
</td>

The problem is that you need to do this client-side with JavaScript.
PHP runs on the server. Your code is no longer running, long before the browser renders the page.
I recommend you learn to use jQuery. http://docs.jquery.com/Tutorials

This functionality is called AJAX (Asynchronous JavaScript and XML).
In other words it allows a javascript .. script to make a request to the server with some data (just a normal request like a browser does), then process the result and update just a part of your page without refreshing the whole.
This is not that simple task, there are many things to be considered. If you think you will need it and work with this method in the future, spend some time and learn AJAX. jQuery is an awesome javascript library with perfect ajax support, should be alot easier than learning plain Javascript.
Just a hint, you can make a POST (more secure) request with jQuery like this:
$.post('/url/to/your/script.php', {'key1': 'value1', 'key2': 'value2'}, function(result) {
// This function is called after the server responds, and result holds either RAW response (html or whatever), or you can parse it as JSON by supplying a fourth argument to $.post with value 'JSON'. Here is where you update your HTML page.
});
As for the server side, everything is as it would be for a normal request, except you don't need (and you shouldn't) return the whole HTML page, but just a fraction - in your case, the dropdown box HTML you need to be inserted.

Related

retrive from DB without click any button using onfocus

hi I have some problem with my code!
I have a textbox when the user write in this text box I want to retrieve from DB directly without clicking any button.
then some of my form will completed after writing in this textbox.
my JS code :
function centerIDfocus()
{
var id = document.getElementById("centerID").value;
var data = <?php $center_ID = echo mysql_num_rows(mysql_query("SELECT * FROM 'examcenter' WHERE 'id' = '".id."'")); ?> ;
}
window.onload = addEventsToHTML;
in my form:
<input name="centerID" id="centerID" onfocus="centerIDfocus();">
and that’s not working!
any ideas red face
You mixed 2 languages - javascript is run on client side and php on server side.
What You need to do is:
var data = function_to_get_data(); // in javascript
in that function call ajax request to the address of your php script - and only in that php script call your database to return desired data
You're PHP code will only run once, when the pages is loaded, after that it won't run again because there's nothing happening on the server side. If you want to run it each time you get the focus then you should be using AJAX.
Take a look at AJAX gets, I'm pretty sure that's what you want:
http://api.jquery.com/jQuery.get/
It is rather hard to know what you are intending to do, but...
My guess is that you are confused about when things happen and when "onfocus" is fired.
PHP is run on the server when the page is being constructed. In contrast, javascript is run in the browser, either after the constructed page has arrived (onload) or in response to a user click or other event such as onfocus.
Thus there is no way for the javascript (in the browser) to drop into PHP (on the server). For the same reason (and security) it is impossible for javascript to talk directly to the database.
There are two approaches you might take to do what (I think) you are attempting to do.
You could create a javascript array in PHP, indexed by ID, and containing all possible IDs and their data. Use PHP to read the database, and then echo the javascript to define the array. This would become part of the page sent. Then, in response to the event that means you want to fill the field, you extract the data from the array, and put it where you want it. This would be slow for the page to load, but very quick response to the click that triggered the change.
An alternative is to use ajax. The easiest way is to use jquery to send a GET request to the the server requesting the data related to the ID. The server must respond to that URL by extractign the ID, reading the database and generating the reply. I recommend using JSON. Then, when the jquery request returns, the javascript code can move the data from the JSON into your field. This would make the initial page lighter, but would have a fetch delay to the triggering click.
However I think you may also have an issue with the on-focus event. This fires when the user moves the cursor into the field, before they have entered any data. At that point it will contain the data that was set in the HTML. If you can set the ID at that point, you can also set it to the data from the database.
I think you want two fields - one for the ID and another for the looked up data. Then you run the javascript on the onblur event on the ID field.
Hope that helps.
use something like:
$('.centerID').keyup(function(){
var val = this.val();
var url = '/do.php'; // url to a php script
var val = 'action=checkValue&value='+val; // send it the value
$.getJSON(url, val, function(data){
// Something to do when you get the data back
});
});
then just create a php script that checks the database and returns a JSON answer and then do as you please with it.
BTW - I'm assuming you are ok using jQuery. You can apply this to your JavaScript too.
I used keyup() as one example but you can appy this to keydown(), click(), focus(), focusout() etc...
I have a do.php script that contains a switch statement with the possible value of action= and returns JSON. Everything from logging in, registering, activity monitor, to updating a database field without leaving the page.

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.

Change Form Elements Depending On Selected Option

I have seen several sites where there is a form, starting with a dropdown box, and depending on the box chosen there is different form elements, for example, let's say I wanted to make an uploader script, the dropdown box might hold:
Upload
Delete
And is Upload is selected I would want a browse file element, while with Delete selcted maybe only the name should be imputted into a text field. How can I make it do so? I plan on using php for it and using the echo syntax to create the html for the forms, but is ther a way to have, for example an if statment, that changes the other form elements that show based on the option selected.
I have seen people use jQuery for it, but I can ONLY use PHP ad HTML for my project.
This isn't a direct solution but if you intend on carrying out this task exclusively with php/html then you should consider setting up a system such as this in the php file which serves the page.
<?php
/*Check to see if the user has submitted the form*/
if(isset($_POST['action']))
$action = $_POST['action'];
/*If no action has been sent from the client side, generate form*/
if(!isset($action)){ ?>
<form name="test" action="example.php" method="POST">
<select name="action">
<option value="update">Update</option>
<option value="delete">delete</option>
</select>
</form>
<?}
/* if update action, load file dialog*/
elseif($action == "update"){?>
<!-- relevant HTML or action for file load -->
<?}
/*Default to delete*/
else{?>
<!-- some action to place the input field -->
<input name="fileName" value="<? echo $FILE_NAME; ?>" />
<?}
?>
Essentially you're going to have to handle both page serving and form processing within the one page, using the value from the form select element to determine which blocks of HTML need to be loaded. Note that you will still have to provide a submit button for the form in order to trigger the action since there's no javascript events.
I want to distance myself from this solution as I know of it only through experiencing the Dunning Kruger effect and I'm sure the lack of client side involvement will be frowned upon by most.
You can't do what you want in purely server-side code without some sort of submission from the browser to trigger the check. PHP code runs on the server and returns the page to the browser. Once the page has left the server there's nothing PHP can do to it.
Sites I've seen that do this kind of thing on the server-side reload usually have an initial page where you choose the action you want, and then load the form for the chosen action. That's really all you can do without some kind of javascript on the client side.
If you can use javascript then you have many more options:
Trigger a reload of the form when the drop-down box is changed.
Send an ajax request when the drop-down box is changed and dynamically add the HTML returned by the server to the form.
Send fields for all options in the original page, and use the change event on the drop-down to show/hide the relevant fields.
Based on your comments to other answers there seems to be some confusion as to the role of javascript in the application. The server doesn't need to know about Javascript, or even JQuery. The server runs your PHP code to build the HTML for your page. The HTML can reference CSS stylesheets, images, Javascript files, etc, which, as far as the server is concerned, are just static files requested by the browser. Once the client browser gets the javascript file from the server it can execute it and enable whatever dynmiac page behaviour is intended. There is no Javascript code in your server-side application. The application is just a bunch of PHP files, with a collection of other static files to support the generated HTML.
Im no expert, but i guess since PHP is a Server-Side Scripting Language, there is no way to do this purely in php, other than to reload the page evertime you switch the dropdown option. Maybe you could accomplish it with frames (but who wants to use those?).
jQuery is just a pre-written javascript subset, are you not allowed to use javascript? if you can not use it, then your ability for dynamic pages diminishes greatly.
AJAX uses javascript as well and is the solution I use to load dynamic content. do you need examples or a way to do this without javascript.

Populating a Dropdown list in PHP dynamically

I have a small PHP page which contains two drop down lists
I need to populate the second one according to the result selected in the first drop down list .... is this possible? In other words I need to use the value selected from the first drop down list and use it in the dB query used to populate the second drop down list (but this should be populated upon selection of the first drop down list.
If this is possible any hints please? (you can assume that I am able to populate the first drop down list from the dB)
Option 1: embed the data for the second select in the document as hidden elements or JS objects. A change event handler on the first select will populate the second select. A List Apart has an example dynamic select page.
Option 2: use AJAX. When the first select changes, make a request to the server for the contents of the second select, then populate it. With a JS library (such as jQuery), this becomes quite easy.
$('select#one').change(
function (evt) {
$('select#two').load('/thing/'+this.value);
}
);
"/thing/<val>" identifies your server side script to generate a list of items based on "<val>" (use the rewrite facilities of your webserver to resolve the URL path to the actual script). You could simply have it always generate <option> elements, but a better design would be to include a way to specify the result format, so it could output the list as <li>, using JSON or some other format.
$('select#one').change(
function (evt) {
$('select#two').load('/thing/'+this.value, {fmt: 'option'});
}
);
You will have to use AJAX to send the selection of the first dropdown to the server. You can then query the database and generate the second dropdown and send it back to the user.
You'll need an asynchronous call back to the server, without a page reload. (I doubt that you actually want to have a button that posts back to the server) So AJAX is something that can do exactly that. Add an AJAX call to your first dropdown's onchange event handler that posts the selection back to the server and returns the contents of the second dropdown. When the AJAX call returns the new values, you will use it to build your content for the second dropdown. Most of this is done in Javascript, of course, besides the actual server part, which will remain in PHP.
There's two ways of doing it. The old-school "select an option and submit to rebuild the page" method, which works pretty much universally, and the newfangled AJAX methods, to load the second dropdown's contents without refreshing the page.
Both have advantages/disadvantages, so it boils down to what's best for your purposes. The oldschool method doesn't require any javascript at all, but since it does round-trip the form through the server, you'll get the "clear the window and then redraw the page" flickering.
The AJAX method bypasses the refresh flicker, but also would no work on Javascript-disabled browsers. It does require a little bit more code, client-side, to handle the AJAX calls and population of the dropdown, but the server-side code would be pretty much the same for both methods: same queries, same retrieval loops, just different output methods.
#outis has good point use .change in jquery otherwise use onchange event in select code.
like
<select id='my_select' onchange='javascript:myfunc()'>
<option value='a'>a</option>
.
.
<option value='z'>z</option>
function myfunc(){
//write code to populate another dropdown based on selected value
}
You can see this Dynamically Populating Dropdown Based On Other Dropdown Value

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