Link to home
Start Free TrialLog in
Avatar of David Schure
David Schure

asked on

Opening a MODAL in PHP

Not sure how to open a Modal...from up here?
<?php
include_once('includes/config.php');
if(isset($_POST['submit']))
{
$full_name=$_POST['client_name'];
$address=$_POST['client_address'];
$city=$_POST['client_city'];
$state=$_POST['client_state'];
$country=$_POST['client_country'];
$email=$_POST['client_email'];
$password=$_POST['client_password'];
$sqlquery="insert into tbl_client(client_name,client_address,client_city,client_state,client_country,client_email,client_password) values('$full_name','$address','$city','$state','$country','$email','$password')";
$query=mysqli_query($con, $sqlquery);

if($query)
{
//Code here to open modal????   
   
}
}
?>

Open in new window

and if so how?
or from the button on the form?
<button type="submit" class="btn btn-primary pull-right" id="submit" name="submit" data-toggle="modal" data-target="#demo">Join <i class="fa fa-arrow-circle-right"></i></button>

Open in new window

which is not opening the modal.  But it is inserting the data into the table.
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Hey David,

Just to clarify, when working with webpages, there are 2 parts - the client side (what people see in your browser) and the server-side (the code you write behind the scenes using something like PHP). The Modal is a client-side part, so you can't do that with PHP - it needs to be done with client-side code, such as HTML, Javascript and CSS.

The HTML button you've shown is a submit button, so when clicking on it, the form it belongs to will be sent to the server for processing (and in your case that processing is inserting a record into a DB)

There are a few ways to do modals, but it's not entirely clear how you want to use one. Can you clarify what you're trying to do.

Also, from your previous questions, it does look like you're using the Bootstrap library in your application. If that's the case, then Modals are pretty straight forward as the behaviours and styling you need are built-in.
Avatar of David Schure
David Schure

ASKER

Hi Chris.  After the data is inserted into the table I want the MODAL demo to pop up.  So PHP I can forget that. Correct.  It should be done from the button.

<button type="submit" class="btn btn-primary pull-right" id="submit" name="submit" data-toggle="modal" data-target="#demo">Join <i class="fa fa-arrow-circle-right"></i></button>

Open in new window

does not open the modal
Right,

As you have it, when you click on that button, the form data is sent to the server by making a new POST request, so you effectively navigate away from that page (even if you're submitting to the same page). Because the client-side code and server-side code run independently, by the time your form has posted, inserted the data and then returned you back to your page, your button has no concept of what happened at the server - it's not aware of the PHP code in any way - it just sits there wating for you to click it so it can start the whole form POST process over again.

There are a few ways to handle this situation. The most common way is to hook an AJAX request up to your form. AJAX is a mechanism where you can make a request to the server in the background. Doing this means that your data is POSTed, but the user never leaves the page. The data is sent to the server, the server processes it and then sends a response back to your page. The page has a 'handler' in place that captures that response and acts accordingly - in your case, it would then open the modal.

It's a little trickier to implement than what you currently have, but it's a modern approach that gives web pages a more responsive feel.

If you want to go this route, it will mean that you'll probably have to break up your files a little more. For example, if the PHP code that handles your data is currently part of the HTML page that shows the form, it will need seperating out into it's own file.

There is a slightly different approach to this, although it's not as slick. Basically, when you submit your form to the server, after the server has done processing, it stores a flag, such as 'showModal = true' within the Javascript section of your page. Then when the page re-loads, it checks that flag to decide whether to show the modal or not. The reason I say it's not as slick is because you're still redirecting away from the page and you won't have a direct response from the server, so it's not actually the button click that triggers the modal - it's the page reload.

Let me know which route you want to take and I can get you going in the right direction.
Chris. Let's do the Ajax way. I love the way it stays on the page.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
done.  This is what I am getting.
User generated image
PS: NEVER call anything name="submit" or id="submit" if you are ever planning to submit the form using script.
The name will hide the submit event handler
Right,

500 is a server error, so it indicates a problem with the PHP script. Click on the Network tab of the WebDev tools, and select the data.php file. Select the Reponse tab from there and see what it says.

My guess is that it's probably the null coalesce code I've used on lines 5 & 6. You may need to change it to:

$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : null;
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : null;

Open in new window

"This request has no response data available".  Is what it says.
@Michel - not entirely sure what you mean by that. Could you explain.
I changed the two lines as prescribed.
OK David,

Lets temporarily remove the AJAX call and make a standard POST request. In your HTML, remove the submit handler (the full javascript block)  and change the html form to this:

<form id="myForm" method="post" action="data.php">

Try it again. It should just now submit directly to the script so you'll see any errors you've got.
If you have

<form>
<button type="submit" class="btn btn-primary pull-right" id="submit" name="submit">Submit</button>
</form>

Open in new window


and you later want to do

document.querySelector("form").submit()

Open in new window

or similar, it will fail
Ahh sorry David - we cross posted.

I keep writing code based on a newer version of PHP, forgetting that some people haven't upgraded yet. The null coalesce is s new feature. The error you're seeing in your first sreen grab is just the syntax checker of dreamweaver so you can ignore it.

Right - that looks like your scripts are now working, which is great.
Hi Chris... so the one button "Submit" will insert the data into the table then open the form by adding the javascript?  Do I move the entire PHP statement from atop the page new-slider.php to an external php file?
No worries David,

You've now got a basic setup that allows you to POST a form to the Server via AJAX, receive a response and fire a Modal. It's now just a case of building on that - adding in your own form fields to HTML and updating the echo test., adding in your DB connection and INSERT queries etc, Build it up piece by piece and it will be easier to debug.

If you get stuck, ask away :)
Thank you!
Okay...I tried putting this all together.  Here is what I have...not working.  (I'm something wrong.)
On the main page at the bottom I have the Javascript...
FormID is registration
ModalID is demo
<script>
        $(function() {

            $('#registration').submit(function(e) {
                e.preventDefault();

                $.ajax({
                    url : 'client-reg.php',
                    data : $(this).serialize(),
                    method : 'post',
                    dataType : 'json',
                }).done(function(response) {
                    console.log(response);
                    $('#demo').modal('show')
                });
            });
            
        });
</script> 

Open in new window

The file with the php has the following.  it is named client-reg.php
<?php
include_once('includes/config.php');
if(isset($_POST['submit']))
{
$full_name=$_POST['client_name'];
$address=$_POST['client_address'];
$city=$_POST['client_city'];
$state=$_POST['client_state'];
$country=$_POST['client_country'];
$email=$_POST['client_email'];
$password=$_POST['client_password'];
$sqlquery="insert into tbl_client(client_name,client_address,client_city,client_state,client_country,client_email,client_password) values('$full_name','$address','$city','$state','$country','$email','$password')";
$query=mysqli_query($con, $sqlquery);

//if($query)
//{
   
//}
}
?>

Open in new window

At the top of the NewSlider.php I have this...
<?php
include_once('includes/config.php');
//if(isset($_POST['submit']))
//{
//$full_name=$_POST['client_name'];
//$address=$_POST['client_address'];
//$city=$_POST['client_city'];
//$state=$_POST['client_state'];
//$country=$_POST['client_country'];
//$email=$_POST['client_email'];
//$password=$_POST['client_password'];
//$sqlquery="insert into tbl_client(client_name,client_address,client_city,client_state,client_country,client_email,client_password) values('$full_name','$address','$city','$state','$country','$email','$password')";
//$query=mysqli_query($con, $sqlquery);

////if($query)
////{
   
////}
//}
?>

Open in new window

The code at the top of the form...
<form name="registration" id="registration"  method="post" onSubmit="return valid();">

Open in new window

The button...I tried both. Neither one inserts the record nor opens the modal..
<button type="submit" class="btn btn-primary">Submit</button>
            <button type="submit" class="btn btn-primary pull-right" id="submit" name="submit">Join <i class="fa fa-arrow-circle-right"></i></button>

Open in new window

My guess is the php that I am not understanding...


I repeat: RENAME the buttons!!! Change id="submit" and name="submit" to id="subBut" and name="subBut"

and the php to if(isset($_POST['subBut']))
Changed....
 <button type="submit" class="btn btn-primary pull-right" id="subbut" name="subbut">Join <i class="fa fa-arrow-circle-right"></i></button>

Open in new window

if(isset($_POST['subbut']))

Open in new window

First off - you don't need to rename the buttons. It's an edge case where this may be a problem, and this isn't one of them (sorry Michel).

For testing purposes, change your php file to contain just the following:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo json_encode($_POST);

Open in new window

Run you page and check your console. This is the echo test I was talking about - it should just dump out the values of the form you submitted.

Get that working and we can move on.

** Not entirely sure of the relevance to NewSlider.php
Hi NewSlider.php is the page where the form, modal and javascript are located.

User generated image
Did this on NewSlider.php
<?php
include_once('includes/config.php');

$sqlquery="insert into tbl_client(client_name,client_address,client_city,client_state,client_country,client_email,client_password) values('$full_name','$address','$city','$state','$country','$email','$password')";
$query=mysqli_query($con, $sqlquery);
?>

Open in new window

and this on client-reg.php
<?php

include_once('includes/config.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

$full_name=$_POST['client_name'];
$address=$_POST['client_address'];
$city=$_POST['client_city'];
$state=$_POST['client_state'];
$country=$_POST['client_country'];
$email=$_POST['client_email'];
$password=$_POST['client_password'];
echo json_encode($_POST);
?>

Open in new window

The modal now opens but now input into the table.  not even a new record.
The Javascript at the bottom of the NewSlider.php page...
<script>
        $(function() {

            $('#registration').submit(function(e) {
                e.preventDefault();

                $.ajax({
                    url : 'client-reg.php',
                    data : $(this).serialize(),
                    method : 'post',
                    dataType : 'json',
                }).done(function(response) {
                    console.log(response);
                    $('#demo').modal('show')
                });
            });
            
        });
</script> 

Open in new window

OK David,

With AJAX, you're making a behind-the-scenes request to a totally different script. You're NOT making a request to the same page that you're on, so if the code for the database is on the same page, it will NEVER fire. The idea is that you have your HTML page. That contains the Form, the Javascript and the Modal. When you submit the Form - all the data is sent to another script. This script will receive the data, process it (add it to the database) and the generate a response (success / error / thank you ... whatever you want). The page that makes the AJAX call (i.e. your HTML page) will then receive this response back.

Your client_reg.php file is the file that you're sending the form to, so it's that file that needs to insert the record into the database and generate a response. As you have it, you're just echoing out the data - which is ideal for an echo test, but once you know it's receiving the data correctly, you'll need to edit it to add in the Database code as well.
So....I have the Javascript, Form and Modal on the NewSlider.php page.  All good.  I will put this on the client-reg.php page.

<?php

include_once('includes/config.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

include_once('includes/config.php');
if(isset($_POST['submit']))
{
$full_name=$_POST['client_name'];
$address=$_POST['client_address'];
$city=$_POST['client_city'];
$state=$_POST['client_state'];
$country=$_POST['client_country'];
$email=$_POST['client_email'];
$password=$_POST['client_password'];
$sqlquery="insert into tbl_client(client_name,client_address,client_city,client_state,client_country,client_email,client_password) values('$full_name','$address','$city','$state','$country','$email','$password')";
$query=mysqli_query($con, $sqlquery);


}
?>

Open in new window

Correct?
Pretty much spot on, although a few points.

   Put your error_reporting before your first include.

   You've got the include in there twice

   Remove the if (isset()) check.

   Send a response (echo some JSON out)

   With a PHP file, don't include the trailing ?>

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include_once 'includes/config.php';

$full_name=$_POST['client_name'];
$address=$_POST['client_address'];
$city=$_POST['client_city'];
$state=$_POST['client_state'];
$country=$_POST['client_country'];
$email=$_POST['client_email'];
$password=$_POST['client_password'];

$sqlquery="insert into tbl_client (client_name, client_address, client_city, client_state, client_country, client_email, client_password) values ('$full_name', '$address', '$city', '$state', '$country', '$email', '$password')";
$query=mysqli_query($con, $sqlquery);

echo json_encode([
    success => true,
]);

Open in new window

Nothing happens. No record.  No modal opening.. I'm missing something here.
<button type="submit" class="btn btn-primary pull-right" id="submit" name="submit">Join <i class="fa fa-arrow-circle-right"></i></button>

Open in new window

Right,

Check your console. Press F12 on your keyboard to open up the console, and then submit the form again. Click on the Network tab, select the client-reg.php file and check the response. Any errors reported by the PHP script will be shown there.
I will insist there are issues with the buttons too

https://jsfiddle.net/mplungjan/fgjpy3c0/

serialize does not take the buttons name and value so isset will fail

And for the future, as you can see, submitting the DOM form fails when the button is called submit
I agree it is not the issue here, but the serialize issue seems to be a genuine issue
OKay it put the record in but did not open the Modal
This is the error code...

NewSlider.php:583 Uncaught ReferenceError: valid is not defined    at HTMLFormElement.onsubmit (NewSlider.php:583)

onsubmit@NewSlider.php:583

Right David,

What did the console show when you submitted the form ? Any errors that the PHP script throws will be shown there.


@michel - Your code fails because it overrides the submit method. That's not what we're doing here.
Ahh, OK David - that's to do with your Javascript. On your form, you're calling a JS function caleld valid() and it can't find it:

<form name="registration" id="registration"  method="post" onSubmit="return valid();">

Remove that:

<form name="registration" id="registration"  method="post">
This everything that is kicked back.........
[DOM] Found 2 elements with non-unique id #fair: (More info: https://goo.gl/9p2vKq) <input type="radio" id="fair" name="finance" value="fair"> <input type="radio" id="fair" name="sleep" value="fair">
NewSlider.php:1 [DOM] Found 2 elements with non-unique id #good: (More info: https://goo.gl/9p2vKq) <input type="radio" id="good" name="finance" value="good"> <input type="radio" id="good" name="sleep" value="good">
NewSlider.php:1 [DOM] Found 7 elements with non-unique id #no: (More info: https://goo.gl/9p2vKq) <input type="radio" id="no" name="religious" value="no"> <input type="radio" id="no" name="spiritual" value="no"> <input type="radio" id="no" name="counsel" value="no"> <input type="radio" id="no" name="counsel" value="no"> <input type="radio" id="no" name="panic" value="no"> <input type="radio" id="no" name="medication" value="no"> <input type="radio" id="no" name="pain" value="no">
NewSlider.php:1 [DOM] Found 3 elements with non-unique id #other: (More info: https://goo.gl/9p2vKq) <input type="radio" id="other" name="sex" value="other"> <input type="radio" id="other" name="relationship" value="other"> <input type="radio" id="other" name="refer" value="other">
NewSlider.php:1 [DOM] Found 2 elements with non-unique id #poor: (More info: https://goo.gl/9p2vKq) <input type="radio" id="poor" name="finance" value="poor"> <input type="radio" id="poor" name="sleep" value="poor">
NewSlider.php:1 [DOM] Found 7 elements with non-unique id #yes: (More info: https://goo.gl/9p2vKq) <input type="radio" id="yes" name="religious" value="yes"> <input type="radio" id="yes" name="spiritual" value="yes"> <input type="radio" id="yes" name="counsel" value="yes"> <input type="radio" id="yes" name="counsel" value="yes"> <input type="radio" id="yes" name="panic" value="yes"> <input type="radio" id="yes" name="medication" value="yes"> <input type="radio" id="yes" name="pain" value="yes">
NewSlider.php:605 Uncaught ReferenceError: userAvailability is not defined
    at HTMLInputElement.onblur (NewSlider.php:605)
DevTools failed to load SourceMap: Could not load content for https://www.audiodigz.com/resources/js/jquery.flexslider.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for https://www.audiodigz.com/resources/js/bootstrap.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for https://www.audiodigz.com/resources/css/bootstrap.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
DevTools failed to load SourceMap: Could not load content for https://www.audiodigz.com/resources/js/popper.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
NewSlider.php:583 Uncaught ReferenceError: valid is not defined
    at HTMLFormElement.onsubmit (NewSlider.php:583)
onsubmit @ NewSlider.php:583

Open in new window


I have four Modals on the NewSlider.php page  
Login
registration
demo
admin
could that be the problem?
Removed.  Data being inserted but modal not opening.
No errors now.  data inserted.  No modal.
The code from the demo modal
<div class="modal fade" id="demo" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

Open in new window

In HTML, an ID on an element has to be Unique throughout the page. The error you're getting indicates that you're using the same ID on more than one element:

#fair, #good, #no, #yes, #other, #poor

You're also referring to a JS function called userAvailability() and you're still referring to the valid() function.

As for having 4 Modals being the problem - you can have as many as you like, but like I've said before - debugging is a whole lot easier if you start simple and build on it. We seem to have taken a massive jump from the simple demo, to a full blown application without any of the middle steps, which means it's now very difficult to track down problems. The idea of incremental development is that you code something, you debug it and fix it. you know it's working. You then add in the next bit and debug and fix that. By adding in 20 new items / features, any part of that could introduce problems - you then have 20 features to dig through to try and identify the problem. I get it - deadlines loom, so it's tempting to just throw everything at it - but trust me - it's actually the slowest way to develop anything useful.

I'm acutally lost as to where we are now. Do you have the data being inserted and the modal showing, or are we still stuck on that?
OK. Check your console - are you getting data being dumped to it ?
Thank you Chris...Yes data is being inserted, the only problem is the modal is not opening.
I meant to check the webdev console. In your Javascript, you have this:

}).done(function(response) {
    console.log(response);
    $('#demo').modal('show')
});

Open in new window

That's the code that fires after the AJAX call has completed, so by checking the console, you should see whatever response your PHP script has sent back (or any potential problems).
I made all of the ID's unique.  Modal still won't open.
Console coming back blank....Here is the link...
https://www.audiodigz.com/NewSlider.php 
renamed the modal to      severalquestions
I thought that would help.  Did not
Ahh. OK. The error you're getting back is this:

Notice: Use of undefined constant success - assumed 'success' in /home/audiodigz/public_html/client-reg.php on line 19
{"success":true}

That's a typo in my code. I missed the quotes from around 'success'. In your client-reg.php, it should be:

echo json_encode([
    'success' => true,
]);

Open in new window


FYI - you're still getting some errors about userAvailability not being defined, so you should sort that out as well. Finally, you seem to be loading up 3 different versions of jQuery !!
Hi.  I put the quotes around the success  still not working?  Should I remove some of the jQuery and just keep the newest one?
Yippity, doooooooo!  It works.  I moved the Javascript to the top of the page.  Record is inserting and the modal pops up!   Thank you.  Thank you! Thank you! Chris!
Perseverance pays :)

Good effort David. Glad you've got it working
Agreed!  Thank you for your patience,