PHP AJAX dynamic updating confusion.

Hi,
I want to dynamically load an image into an HTML

element and name into a element using AJAX and PHP. Here is my code for all three coded elements so far. I’m using the GET method as there is no sensitive data and the database is fixed to only 5 records. I have run into a few problems with the coding and need help.

The HTML5 page:

[code]

Ct

Ny

Ha

Az

Ts

Image chosen from form 1

You have chosen

nothing.

[/code]

The PHP script:
[php]<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open(‘mydb.db’);
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {}

$sql =<<<EOF
CREATE TABLE MYTABLE
(ID INT PRIMARY KEY,
NAME TEXT,
VS VARCHAR,
VB VARCHAR,
DENIED BOOL DEFAULT n,
USING BOOL DEFAULT n);

  INSERT INTO MYTABLE (ID,NAME,VS,VB,DENIED,USING)
  VALUES(1,'CT','soo1.jpg','boo1.jpg','n','n');

  INSERT INTO SUMMON (ID,NAME,VIDEOS,VIDEOB,DENIED,USING)
  VALUES(2,'NY','soo2.jpg','boo2.jpg','n','n');

// Other values for more records

EOF;

$ret = $db->exec($sql);
if(!$ret){
echo $db->lastErrorMsg();
} else {}

$ret = $db->exec($sql);
if(!$ret){
echo $db->lastErrorMsg();
} else {}
// Check if there is an active record
$sql = (“SELECT * FROM MYTABLE WHERE USING=‘y’”);

if(num_rows($result)>0)
{
// Select record where USING=‘y’. This should be only 1 record.
// Using Javascript load image: “boo1.jpg” to

element.
echo // None for this yet.
}
 else
 {
     if(isset($_POST[choices])) {
		 
        if($_POST['choice'] == 'CT') {
$sql = ("UPDATE MYTABLE SET USING='y' WHERE ID='1'");
// Using Javascript load image: "soo1.jpg" to <div class="choiceS"></div> element.
echo '<script type="text/javascript">getImage()</script>
     // Using Javascript load 'name' of record into <span> of form2
    echo <script type="text/javascript">
        } 
		
// Other values for other records in database.
		
    }
}

 }

$db->close();
?>
[/php]

And the AJAX script:

[code]function getImage(str) {
if (str == “”) {
document.getElementById(“choiceS”).innerHTML = “”;
return;
} else {
if (window.XMLHttpRequest) {
// code for browser
xmlhttp = new XMLHttpRequest();
} else {
// code for IE
xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(“choiceS”).innerHTML = xmlhttp.responseImage;
}
};
xmlhttp.open(“GET”,“somescript.php?q=”+str,true);
xmlhttp.send();
}
}

// for in form2
document.getElementById(‘name’).innerHTML = ‘newtext’;
[/code]

So, you have a form. You have a submit and you could just load the picture with the action of the form.
Otherwise, you need to not have an “action” so the page does not get posted. If you want to create a
“dynamic” load of something like a picture, you would need to call the routine using JS not PHP. So, you
would use an ONCLICK function in the input to call the JS code to use the AJAX to load the output of a
php page and stick it into the correct DIV. Hope that makes sense…

If you use an ACTION clause in your form, then, you might at well use the posted info to redisplay the page.

If you only have five options, you can just preload all the pictures and use JS to hide/show them. That is a
very simple JQuery code. I use it all the time for help areas. (If a user presses on a small blue question
mark, it shows a new DIV below it explaining what that entry is for.)

I guess it depends on your needs. Do you really need to load it from an external PHP script? If so, we can
help you. Or, if you just want five pictures to show depending on clicks, that is very easy…

Lastly, you said you run into a few problems. What are they so we can solve them…

I take what you said about the multiple hidden layers for an image. Although I also want to (1) add the name from the selected option to show up in form2 which would be linked to the dtabase record and (2) prevent another choice being made in form1 until the choice in form2 has been selected. This is why I also included (in the HTML) both forms. The process is basically 2-step before another selection can be allowed to take place and this is why I thought of the solution to include PHP (and also that AJAX could be useful with regard to dynamically updating the HTML page).

I’m not sure what to do but if using PHP to process the request from the forms and then letting AJAX dynamically update the page then I don’t know what other option there is. I really do think it has to be this way with regard to preventing a user from missing the 2-step process - this is really important. (I promise to post a link to what I’ve created when I’ve got half way through and then all will become clear - in fact that is when I will publicly unveil this project).

Well, yes and no. There are hundreds of ways to solve any programming project. About five ways jump
into my mind to make this work for you. If you want to keep your way, it is fine. It is just very hard to
import a form and then use it to post from it. I have had it fail a lot because all of the form is not loaded
when the page it is loaded and sometime it gets lost. But, we can help you with it.

Another way is to just use PHP. Save a $_SESSION variable that stores the current page and selection and
when they post the page, just show the second form. That is extremely simple to do and keeps everything
inside just one page. Only a few lines needed to make that happen.

The third way that I was thinking about is just make to separate pages and have the first one call the 2nd
one with the second form on it and have that one call back to the first form, etc…

All three of these would work for your project, but, the first, your way is a bit trickier and uses extra code.

Once you get your version working or not working let us know. Would like to see the results and if you
have a question we are here to help you… Good luck!

Hi ErnieAlex. I’ll take the unprecedented move of posting the project in a few hours then you’ll see what is needed. I really don’t mind extra coding but for both of us to be on the same page we both have to understand the project. Anyway, when I’ve posted it you’ll be able to understand fully what it is I’m trying to achieve and we can hopefully work from there. :slight_smile:

http://hafh-drn.sourceforge.net (Windows OS unfortunately).

Hopefully you’ve been able to download, install and run the app as it is now.

Although, I’ve considered an alternative to my original idea which is:
updates the database, adds the name to form2, prevents any more choices in form1 and then a new window opens to show the image.
opens a window to show the second image and then resets the database.

If this ^ is easier to do I’m very much prepared to go for this.

Well, I do not see any file downloads on that link… You can email it directly if you send me a private
message, I will give you an email account for you to send it to…

Sorry about the link however I have considered seriously your previous list of suggestions and actually one of your suggestions makes more sense than the way I wanted to initially to proceed with this app project.
[hr]
OK, so form1:
updates the database (persistence is a requirement of this app project) with which option has been chosen and then opens a new page to show the content.
PHP can do this - excellent so far. :slight_smile:
There are 2 buttons at the bottom of this new page: one returns the user to the UI, the other displays the content (again another new page). PHP can do this also. :slight_smile:
If the user closes the app and returns to it on another day - well this is the reason for the persistence.
When the user makes any selection the second part of content is displayed, the database is reset (so any option can be chosen and the process can start again) and then they can return to the UI.

You see, I’m an idiot and should have looked closer at your suggestions.

Anyway, how would I alter ‘somescript.php’ not only to check/create and update the databasebut also to display the content? Should I put it inside an HTML page?

My apologies for being fuzzy on this but as you’ve already guessed I’m new to PHP (and I over-reached myself with my original plan).

Well, that returns me to what I said before. You can use Ajax and dynamic calls to outside PHP files, but,
I do not think it is needed for your project. So, let’s review a little…

You have a form. It shows whatever…
You have a selection that is handled by the user.
You have a second form that loads up conditional info that is displayed depending on the first form.
Then, that form does other code…

Well, for me, in my humble opinion, this would just be one simple page to do it all. You would have PHP code
at the start of the page that decides what needs to be display and then it does whatever… I think you are
overthinking the logic of this type of page. A few thoughts…

Form one has a submit button that can send the user’s selection from the first form. Once that is sent to
the server, the PHP code, sets a value that can be kept in a variable to tell the code it’s current status. In
most text this is called a “flag”. Also, any PHP code can access the database, store values or reset them.
So, using one page, all can be done simply enough without any tricky code…

Here is a loose idea how to handle it all…

<?PHP Code to read the two form's submit buttons if form1 is pressed, read it's options and update database, set variable to show form2 if form2 submit is pressed update database, etc... ?> <?PHP if form1 is supposed to be active... { ?> <?PHP } else if form2 { <?PHP } ?>

Now as you see, you can use PHP to block or display parts of the HTML based on PHP variables.
And, then, it would show or hide forms. All in one page…

What do you think about that? Is that what you were asking?

Yes, I was overthinking and the solution you have presented is clean and effective. It checks to see if a selection has already been made - persistence used in a very efficient way.

With reference to the code posted at the start of this thread: I place the PHP code (somescript.php) directly before . The next step would be to clean up the check to see if a previous record has been selected and the coding for what to do if a new selection is made.

OK, I admit that I’m shaky on this checking part. Is there a way to do it properly?

Possible to get a recap of what you’re trying to achieve/make here? :slight_smile:

Well, hafhdrn, you just need to understand how posting back to PHP code works. To explain…

When you have a form showing, it is inside the browser on the CLIENT-SIDE of the system. This means it is
inside the browser on the user’s computer. When they press a submit button, it is “POSTED” to the server
and all of the fields they completed is sent to the SERVER-SIDE of the system. Then, the PHP takes all of the
fields that were sent to it and can process them. The OUTPUTS of the PHP code is combined with the HTML
on that page and sent out to the client again so the user sees the newest version.

Now in my sample layout of the page, all of your forms would have action="" and not send it to another
page. That makes the server send the data back to the same page. When the special variable says it
should show form one, it allows the HTML code for that form to show and it is sent to the browser. Users
never see form2 as it is not sent to the browser. When the special variable says it should show form2,
then the user see form2 and never sees form one. It is actually very simple and used on most PHP sites at
some point.

Just remember that PHP is server-side only and the user never sees that code. You can verify that by just
going to any website and right-click on it and view-source. You will see all of the HTML for that page and
any CLIENT-SIDE coding such as Javascript or JQuery that is included on that site’s page. ANY page in the
world will show you how they did parts of the pages. But, you never see their PHP behind the scenes.

So, how to handle the special variable. There are many many ways to do this. But, your simple project
does not need tricky code for that. Since you are only dealing with two forms and only one can be shown
at a time, just rename the submit buttons and have your PHP code handle each differently. No special
tricks needed for that. The PHP code for button one, named, maybe “button1” would get the data from
'the first form and the code for button2 would handle the second form. Easy… Also, since form1 does not
show form2’s button, the code never mixes up anything.

Well, I think that explains it. If not ask more… If you get your code ready to try, you can post it here and
we can help with errors…

JimL, hafhdrn was just trying to have two forms on a page and show them at different times once certain
options were selected. But, he was overthinking the project and trying to use Ajax, so I was helping him
do it in one page.

If I have two forms on one page I use a hidden field, for example

[php][/php]

that way you can simply use an if statement like such:

[php]if ( isset($_POST[‘action’]) && $_POST[‘action’] === ‘register’) {
/* Process registration code only */
}[/php]

That way you can have as many submit buttons as you want on that page just as long as you are using an unique hidden input field for each HTML form.

Yes, Strider64, I typed that and then removed it. He said he was a newbie and he has two distinct forms,
so two submit buttons work well for his needs. But, yes, that is a good way to handle multiple forms!

Hi ErnieAlex Strider64 and JimL, I’ve set up the page as you described ErnieAlex.

However, just to clarify:
the PHP code for form1 is to let it show if (using a sql statement) the value in a given column = x.
If the value =z then show the other from.

Could you provide a working example - I work better from practical stuff. Thanks.

Well, this is not a tested or working page. But, it should give you an idea how to handle the code.
I did not know your database table’s layout. ( Which is the image you want to show, etc. ) You will have
to alter the queries to fit your needs. Just wrote it off the top of my head to give you a start!

One page. Call it anything. I called it test.php … Good luck…
[php]

<?PHP // Check if user posted form. If so, handle both buttons... if (isset($_POST["button1"])) { // User pressed the Form1's submit button... $sql = "SELECT * FROM MYTABLE WHERE name=" . $_POST["choice"]; $db->exec($sql); // etc... // ****** Here you would load the name of the picture and place into a variable to insert into your HTML $image_name = $row["vs"]; $db->close(); } elseif (isset($_POST["button2"])) { // Button2 was pressed, so Form2 was showing. Handle whatever you want Form2 to do... } ?> Two Forms Test... <?PHP // Form1 is displayed first or if nothing is posted yet. Form2 is shown once Form1 has been posted... // Always show form1 unless it's submit button was pressed. In that case show form2. if (!isset($_POST["button1"])) { // Form1's submit button was not pressed, show form1... ?>

Ct

Ny

Ha

Az

Ts

<?PHP } else { // If Form1's submit button was not pressed show Form2 ?>

You have chosen

nothing.

<?PHP } ?>

[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service