Ajax and PHP

After reading and experimenting, I wrote a snippet of coding. I am beginning to understand and get the 'gist' of it but still newbie. I have it pretty clean except that when it returns my result, the form displays again and it goes downhill from there...what am I doing wrong??
Should I place the data validation in a separate page and just return the error message? I haven't inserted the coding to display a pop-up error message to user but that's something I would like to do too.  What would that look like?
I have attached screen shots and have inserted the coding. Any advice would be much appreciated... I am really trying to learn this technique.

<?php
if (isset($_POST))
{
    $begdate = isset($_POST['txtdepartdate']) ? $_POST['txtdepartdate'] : 'No Departure Date passed through<br>';
    $enddate = isset($_POST['txtreturndate']) ? $_POST['txtreturndate'] : 'No Return Date passed through<br>';
        // display them
        $result = 'Departure Date:' . $begdate  . '  Return Date: ' . $enddate; 
        echo $result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<meta charset="UTF-8"> 
<link rel="stylesheet" href="jquery-ui-1.12.1.custom/jquery-ui.min.css">
<script type="text/javascript" src="jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script>
<script type="text/javascript" src="jquery-ui-1.12.1.custom/jquery-ui.min.js"></script>
<script>
$(document).ready
     (function() 
{
    $("#search").click
	(function(e) 
	{
        e.preventDefault();

        $.ajax
		({
            url: 'testajax.php',
            type: 'POST',
            data:{
                'txtdepartdate' : $('#txtdepartdate').val(),
                'txtreturndate' : $('#txtreturndate').val()
            },
            success: function(data, status){
                $('#result').html(data)
            }
        });
    });
});
</script>
<script>
  $(function() {
   $('input').filter('.datepicker').datepicker({
    changeMonth: true,
    changeYear: true,
    showOn: 'button',
	showButtonPanel: true,
    buttonImage: 'jquery-ui-1.12.1.custom/images/calendar.gif',
    buttonImageOnly: true,
	dateFormat: 'mm-dd-yy'
	
   });
  });
</script>
</head>
<body>
<div id="result">Dates should Display here</div>
<form>
	<table style="margin: auto;">
		<tr>
        	<div name="txtdepartdate">
                <td style="text-align:right">Depart Date:
				</td>
				<td>
                    <input type="text" id="txtdepartdate" name="txtdepartdate" class="datepicker" />
	            </td>
	        </div>	
	        <div name="txtreturndate">
                <td style="text-align:right">Returning Date:
				</td>
				<td>
     	            <input type="text" id="txtreturndate" name="txtreturndate" class="datepicker" />
	            </td>
	        </div>	
        </tr>
    </table>
	<br>
    <table style="margin: auto;">	
        <tr>
              <td style="text-align:center" colspan="4"><input type="submit" id="search" name="search" />
			  </td>
		</tr>
	</table>				
</form>
</div>
</body>
</html> 

Open in new window

first-time-page-loads.JPG
after-submitting.JPG
datepicker-display-error.JPG
OverthereAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brian TaoSenior Business Solutions ConsultantCommented:
Try adding exit() after your line#8
<?php
if (isset($_POST))
{
    $begdate = isset($_POST['txtdepartdate']) ? $_POST['txtdepartdate'] : 'No Departure Date passed through<br>';
    $enddate = isset($_POST['txtreturndate']) ? $_POST['txtreturndate'] : 'No Return Date passed through<br>';
        // display them
        $result = 'Departure Date:' . $begdate  . '  Return Date: ' . $enddate; 
        echo $result;
        exit();
}
?>
<!DOCTYPE html>
// the rest of your code ...

Open in new window

0
Julian HansenCommented:
I would split the code into two

1. Your view that displays the page
2. Your model / controller that handles the logic of the data

Mixing them is just going to complicate things

Some notes on your JavaScript / jQuery

*Although it is legal it is not necessary to create different $(function blocks - you can put all your code in one.
*The following
$(document).ready(function () {

Open in new window

Can be simplified to
$(function() {

Open in new window

As you have it in your code blocks.
* Just a matter of preference but I put my script at the bottom of the page.
* $.ajax - .success is being deprecated - rather use promise functions .done()

Now, as to why your script is doing what it is doing.

Let's look at what is happening when you AJAX back

Code gets to line 2 and tests $_POST which is found to exist
Code tests POST variables - finds those
Code outputs result string
Code CONTINUES to LINE 11 - which is the rest of the page.
So what is sent back to the browser is the result string followed by the rest of the page.

This is one of the reasons why a separate script is a good idea.

In you script you could fix it by putting the following between line 8 and 9
die()

Open in new window


But that is not a good idea.

Here is what the code would look like with a separate validation
HTML
<div id="result">Dates should Display here</div>
<form>
  <table style="margin: auto;">
    <tr>
          <div name="txtdepartdate">
                <td style="text-align:right">Depart Date:
        </td>
        <td>
                    <input type="text" id="txtdepartdate" name="txtdepartdate" class="datepicker" />
              </td>
          </div>  
          <div name="txtreturndate">
                <td style="text-align:right">Returning Date:
        </td>
        <td>
                   <input type="text" id="txtreturndate" name="txtreturndate" class="datepicker" />
              </td>
          </div>  
        </tr>
    </table>
  <br>
    <table style="margin: auto;">  
        <tr>
              <td style="text-align:center" colspan="4"><input type="submit" id="search" name="search" />
        </td>
    </tr>
  </table>        
</form>
</div>

Open in new window

jQuery
<script>
$(function() {
    $("#search").click(function(e) {
        e.preventDefault();
        $.ajax ({
            url: 't2202.validate.php',
            type: 'POST',
            data:{
                'txtdepartdate' : $('#txtdepartdate').val(),
                'txtreturndate' : $('#txtreturndate').val()
            }
    }).done(function(data, status){
      $('#result').html(data)
        });
    });
  
  $('input.datepicker').datepicker({
    changeMonth: true,
    changeYear: true,
    showOn: 'button',
    showButtonPanel: true,
    buttonImage: 'http://jqueryui.com/resources/demos/datepicker/images/calendar.gif',
    buttonImageOnly: true,
    dateFormat: 'mm-dd-yy'
  });
});
</script>

Open in new window

PHP
<?php
$begdate = isset($_POST['txtdepartdate']) ? $_POST['txtdepartdate'] : 'No Departure Date passed through<br>';
$enddate = isset($_POST['txtreturndate']) ? $_POST['txtreturndate'] : 'No Return Date passed through<br>';

$result = 'Departure Date:' . $begdate  . '  Return Date: ' . $enddate; 

echo $result;

Open in new window


Working sample here
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
Update on the previous post.

You have some illegal markup in your table.

The <div name="txtdepartdate"> inside the <tr> - what is that for? And why the name attribute?

This is not valid markup and should be removed as per below.
<div id="result">Dates should Display here</div>
<form>
  <table style="margin: auto;">
    <tr>
      <td style="text-align:right">Depart Date:
      </td>
      <td>
        <input type="text" id="txtdepartdate" name="txtdepartdate" class="datepicker" />
      </td>
      <td style="text-align:right">Returning Date:
      </td>
      <td>
        <input type="text" id="txtreturndate" name="txtreturndate" class="datepicker" />
      </td>
    </tr>
  </table>
  <br>
  <table style="margin: auto;">  
    <tr>
      <td style="text-align:center" colspan="4"><input type="submit" id="search" name="search" /></td>
    </tr>
  </table>        
</form>

Open in new window

0
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

OverthereAuthor Commented:
I have no idea why I put the <div lines in for the dates - I think it was because this page originally was a rewrite for tabs. Bad oversight on my part.  And the location of the scripts - you are right, bad habit of mine to put where I have - a habit from asp I think and javascipt and afew other things - you know like window.open scripts etc. I am going back, separate coding and revise it.
I noticed you use  container and wrapper - why?
 And you use "<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />"  - why?
I am just trying to understand and been busy re-writing two pages to separate coding - I always did that in other languages but I have no clue why I fail to do it when using PHP etc. Stupid I guess.
0
OverthereAuthor Commented:
Thank you - you cleared the fog up....
0
Julian HansenCommented:
noticed you use  container and wrapper - why?

The template I use for my samples is constructed that way. I use Bootstrap as the CSS theme because it has out of the box styles I can use to make the page look reasonable without having to do anything.

I wouldn't worry too much about the code that exists outside of the following
<!-- START HTML -->

<!-- END -->

Open in new window

This is what appears in the HTML tab of the source listing at the bottom of the page - and is the meat of the sample - the rest is just a wrapper.

If you are going to use the sample then only look at the CSS / jQuery / HTML tabs in the source - don't worry about the full listing.
0
OverthereAuthor Commented:
I see, I was wondering....
0
Ray PaseurCommented:
why I fail ... when using PHP
Ha! Everyone fails in PHP because it's a terrible language, especially if you are used to the formal structures of Java or Python, or the helpful conventions of Ruby.  It's not just you, believe me.  You can't go online and look for a PHP example and find the same code twice.  At the high end of PHP, in the FIG, we are trying to bring some discipline and order to the chaotic language.  At the low end of PHP, people are hacking away at WordPress sites, copying snippets from shady resources on the internet, and writing scripts that are time-bombs.  

If you have some time and want a laugh, read this rant, which is both funny and smart.
https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/
0
OverthereAuthor Commented:
As you know Ray, I have had my struggles with it and not whining but whew! And I am trying hard to learn how new methods and new ways.
I guess I like torturing myself - ha ha! But getting there - maybe - lol!  I cracked up at the link - reminded when I was coding in assembler on mainframes!!
Thanks for comment.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Coding

From novice to tech pro — start learning today.