We help IT Professionals succeed at work.

Returning errors to display in a dialog box - Ajax, Json, Php

Overthere
Overthere asked
on
335 Views
Last Modified: 2017-03-17
I am stuck. My goal is to return the errors to display in a dialog box to the user. I can not figure out how to do this.  Can someone show me the way?? All 3 input values are required and may or may not have values. If they don't have values, I want to display to user.
I have posted both my validate page and my html.
I understand the error routine but I have not quite been able to fix out how to pass the errors to my html and to the dialog box..
Here is my validate page:
<?php 
/*getbookvalidate - validates user input  */

	//  data 
		$bookingid = isset($_POST['txtbookingid']) ? $_POST['txtbookingid'] : '';
		$txtusername = isset($_POST['txtuser']) ? $_POST['txtuser'] : '';
		$txtpassword = isset($_POST['txtpass']) ? $_POST['txtpass'] : ' ';
		$resp = new stdClass;
               $resp->success = true;
		
			
        	//check to see if the bookingid is an integer 	
			if (!is_int($bookingid))  
			    {
				    $resp -> false;
					$error = new stdClass;
					$error->id = 'txtbookingid';
					$error->msg = 'Booking Nbr Required';
			              $resp->error[] = $error;
                }
				
			if (strlen($txtusername) ==0) 
			    {
				   	$resp -> false;
					$error = new stdClass;
					$error->id = 'txtuser';
					$error->msg = 'Username Required';
			               $resp->error[] = $error;
				}
		
    		if (strlen($txtpassword) ==0) 
			    {
				   	$resp -> false;
					$error = new stdClass;
					$error->id = 'txtpass';
					$error->msg = 'Password Required';
			              $resp->error[] = $error;
				}
				
			die(json_encode($resp));
?>				

Open in new window

Here is my html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Booking</title>
<link href="Styles/OldTheme.css" rel="stylesheet" type="text/css" >
<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>
</head>
<body>
<br><br>
    <div>
        <form>
            <table style="margin: auto;">
                <tr>
                    <td style="text-align:center">Booking</td>
                </tr>
            </table>
            <br><br>
			<div id="result">Error Message here</div>
            <table style="margin:auto;">
				<tr>
				    <td style="text-align:right">Enter Booking Nbr: 
                        <input placeholder="Booking Nbr" type="number" id="txtbookingid" name="txtbookingid" >
					</td>
				</tr>
				<tr>
				    <td></td>
				</tr>
				<tr>
  				    <td style="text-align:right">UserName:
					<input placeholder="UserName" type="text" id="txtuser" name="txtuser">
					</td>
				</tr>
				<tr>
				     <td></td>
				</tr>
				<tr>
					<td style="text-align:right">Password:
				        <input placeholder="Password" type="password" name="txtpass" id="txtpass">
                    </td>
                </tr>				
			</table>
			<br><br>
	        <table style="margin: auto;">
                <tr>
                    <td><input type="submit" name="retreive" value="Retreive Booking" src="" alt="Retreive Booking" />
                    <td><input type="submit" name="cancel" value="Cancel" src="" alt="Cancel"></td>
                    <td><input type="reset" name="reset" value="Reset Form" src="" alt="Reset Form"></td>
			    </tr>
            </table>
        </form>
     </div>
<!-- INCLUDE "getbookvalidate.php:PHP" -->
<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>
 $( function() {
    $( "#dialog" ).dialog();
  } );
  
$(function() {
  $('form').submit(function(e) {
    e.preventDefault();
    var form = $(this);
    $('.alert').remove();
    $.ajax({
      url: 'getbookvalidate.php',
      data: form.serialize(),
      dataType: 'JSON'
      }).done(function(resp) {
     if (!resp.success) {
        for(var i = 0; i < resp.error.length; i++) 
		{
          var error = resp.error[i];
		  // want to return the errors to display in a dialog box to user
        
       }
     
    });    
  });
});
</script>
</body>
</html> 

Open in new window

Comment
Watch Question

Author

Commented:
Update: I  see one of my glaring errors _ I need to rewrite the validate form....
When I am done, I will re-post it...
Most Valuable Expert 2011
Author of the Year 2014

Commented:
I got a neglected question alert on this.  Are you doing OK?  Should we wait to see your next post?

Author

Commented:
Yes, please. I should be able to post it this evening...thank you....,

Author

Commented:
Here is my revised validate form and html pages. the getbooking.html does not redisplay the values nor the error messages. and as a FYI - using PHP 5.6 - have to use that version.
I have no clue. I would like to display the error messages either a dialog box or alert - something of that nature for the user, instead of echoing onto my page. I have no clue how on that one either.
I have included a screen shot of the console. I can see the values of my input fields in the address bar, but it does not return then to populate my form nor does it display my error message.
My var_dump does not show anything.I have no clue what is wrong. Any help appreciated.
Here is the html page:
<!doctype html>
<html>
<head>
<title>Booking</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>
</head>
<body>
<br><br>
        <table style="margin: auto;">
            <tr>
                <td style="text-align:center">Booking</td>
            </tr>
        </table>
        <br><br>
		<div id="result">Error Messages</div>
	<form>
            <table style="margin:auto;">
				<tr>
				    <td style="text-align:right">Enter Booking Nbr: 
                        <input type="text" id="txtbookingid" name="txtbookingid" />
					</td>
				</tr>
				<tr>
				    <td></td>
				</tr>
				<tr>
  				    <td style="text-align:right">UserName:
					<input type="text" id="txtuser" name="txtuser" />
					</td>
				</tr>
				<tr>
				     <td></td>
				</tr>
				<tr>
					<td style="text-align:right">Password:
				        <input type="password" name="txtpass" id="txtpass" />
                    </td>
                </tr>				
			</table>
			<br><br>
	        <table style="margin: auto;">
                <tr>
                     <td><input type="submit" id="search" name="search" value="Search" /></td>
                    <td><input type="submit" id="cancel" name="cancel"  value="Cancel"/></td>
                    <td><input type="reset" id="reset" name="reset"  value="Reset"/></td>
	    </tr>
            </table>
    </form>
<!-- INCLUDE "getbookvalidate.php:PHP" -->
<script src="http://code.jquery.com/jquery.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
  $("#retreive").click(function(e) {
    e.preventDefault();
    $.ajax({
      url: 'getbookvalidate.php',
      type: 'POST',
      data:{
	         'txtbookingid' : $('#txtbookingid').val(),
	         'txtuser' : $('#txtuser').val(),
		 'txtpass' : $('#txtpass').val(),
		}
    }).done(function(data, status) {
	      $('#result').html(data);
   });
 });
</script>
</body>
</html> 

Open in new window


And here is the getbookvalidate.php
<?php 
{
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
/*getbookvalidate - validates user input  */

   $errmsg= '';
   $result = '';

   $txtbookid = isset($_POST['txtbookingid']) ? $_POST['txtbookingid'] : 'No Booking Nbr passed through<br>';
   $txtusername = isset($_POST['txtuser']) ? $_POST['txtuser'] : 'No Username passed through<br>';
   $txtpassname = isset($_POST['txtpass']) ? $_POST['txtpass']  : 'No Password passed through<br>';;
   
	if (strlen($txtbookid) ==0)
	{
		$errmsg = 'Booking Nbr Required.<br>';
	}
	
	if (!is_int($txtbookid))
	{
		$errmsg = 'Booking Nbr Must be Numeric.<br>';
	}

	if (strlen($txtusername) ==0) 
	{
		$errmsg = $errmsg . 'Username Required.<br>';
	}
	
	if (strlen($txtpassname) ==0) 
	{
		$errmsg = $errmsg . 'Password Required.<br>';
	}
   
	 
	 if (strlen($errmsg) >0)
	 {
		 $result = 'ERRORS<br>' . $errmsg;
	 }
	 
     $result = $errmsg . 'Booking Nbr:' . $txtbookid  . '  User: ' . $txtusername . '  Password<br>' . $txtpassword; 
	 
	// echo $errmsg;
var_dump($errmsg);
var_dump($result);
     echo $result;
}

?>				

Open in new window

Capture.JPG

Commented:
greetings  Overthere , ,  ,  I looked at your code in the HTML and the PHP, and you have this in the page javascript -

      $("#retreive").click(function(e) {

BUT, I could not find any element or button with the  id="retreive" , , so it does not look like that AJAX is ever used?

Commented:
OK, I guess you are trying to do the <form> submit using jquery AJAX server communication?  You have a basic start on these operations, but not enough to have an effective server turnaround back to a dialog box.  You can look some online tutorials for that, what kind of help do you need for this. It looks like you may not have much practice with the jquery Dialog either?

this is some dialog code I have
the HTML -
<div id="dialog" title="Form Submit" style="display:none;">
<p id="dText">The Form was submited Sucessfully, thanks</p>
</div>

Open in new window


this is the jquery javascript -
function showDia(error1, html1) {
var en = "<b style='color:blue;'>Submited Sucessfully</b><br />";
var title1 = 'New Entry successfull';

if (error1 > 0) {
  en = "<b style='color:red;'>ERROR</b><br />";
  title1 = 'New Entry Unsuccessfull';
  }

  $( "#dialog" ).dialog({ title: title1 });
  $('#dText').html(en+html1);//"<b style='color:'>"+
}

Open in new window


the javascript AJAX is more complicated, but I can do some with the jquery   $.post( ) which is easier to understand
$.post( "jqy-post.php", sortPost);

Author

Commented:
I saw that error, retrieve,  and corrected it but it does not post back to my form. And you are right, I am a newbie with Jquery and Ajax.
 I need to have the specific error messages return and displayed. I just can not see why it will not redisplay. I just don't know what the problem.

Commented:
First, you must load JUST ONE jquery library script, and ONLY ONE, never two or three you have this twice -
      <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>

Please take OUT, REMOVE the bottom scripts for  jquery.js  and jquery-ui.min.js

also use the MINIMUM  jquery.min.js  not the  jquery.js
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

For AJAX -
Please read this jquery info page about the post ajax method -
       http://api.jquery.com/jQuery.post/

here is some you might try -
You might change the <form>  to -
     <form id="frm1">
with an ID to reference to get that element in jquery
<script>
$(function() {
// use the submit( ) method to fire when you click the form submit button
$( "#frm1" ).submit(function( event ) {
  event.preventDefault(); //you MUST prevent submission here

// Use the $.post( ) for ajax
  $.post( "getbookvalidate.php",  $( "#frm1" ).serialize() ) // serialize() will get ALL inputs in the form
    .done(function( server ) {
// show the server TEXT return in result div
    $('#result').html(server);
    })
    .fail(function() {
// always have a .fail( ) to catch errors
    alert( "Ajax error" );
  });

 });

 });
<script>

Open in new window

place the above <script> in the <head> BELOW, it has to be below the -
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
in order to work.

Author

Commented:
That's a great link! Thank you.  Do I understand right that I only need the link: "https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"?
I had downloaded plugins from http://www.jqueryscript.net.
 I let it select all plugins and files for me and those three files are what I thought I was  suppose to have in my page.  What about the links for the plugins??
What about the css reference etc.??
Thank you very much for helping, it is appreciated.
 I will make the changes and try it....and post results later today...

Author

Commented:
I tried your suggestions and it still would not work. But I did get it finally - not completely error free but in much better shape.
I still have a problem with the layout and having it redirect if error -free - so that will be a different question. The php coding is not liking my check for non-numeric input but that another question. Thank you for helping..., it what I had coded in the html.
I am curious to your dialog function  coding - where would I insert that in my html? Based on my coding would I place after  
var error = resp.error[i]; 

Open in new window

replacing the coding I have there with it? I think I know but what I have tried does not work.
Here's the html coding:
<!doctype html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Booking</title>
<link href="Styles/OldTheme.css" rel="stylesheet" type="text/css" > 

</head>
<body>
<header>
</header>

    <div id="result"></div>
	<form class="form">
        <div>
	        <input placeholder="bookingid" id="txtbookingid" name="txtbookingid" />
        </div>
        <div>
           <input placeholder="username" id="txtuser" name="txtuser" />
        </div>
        <div >
           <input placeholder="password" id="txtpass" name="txtpass" />
        </div>
        <input type="submit" class="btn btn-primary"/>
  </form>
<footer>

</footer>
<!-- INCLUDE "getbookval-2:PHP" -->
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(function() {
  $('form').submit(function(e) {
    e.preventDefault();
    var form = $(this);
    $('.alert').remove();
    $.ajax({
      url: 'getbookval-2.php',
      data: form.serialize(),
      type: 'POST',
      dataType: 'JSON'
    }).done(function(resp) {
      if (!resp.success) {
        for(var i = 0; i < resp.error.length; i++) {
          var error = resp.error[i];
          var alert = $('<div/>', {class: 'alert alert-danger'}).html(error.msg);
          $('#' + error.id).after(alert);
        }
      }
      else {
        alert('All good - redirect will happen here');
      }
    });    
  });
});
</script>
</body>
</html>

Open in new window

Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
I should say, that not all browsers are allowed to do javascript for security, , so many companies, as a failsafe for the form submit, place an action and method in the <form>, the action goes to a server page especially for non javascript response,, I placed this in the code above -

<form id="formAjx" method="post" action="nojavas.php">

Author

Commented:
Thank you for responding and the encouragement. It's a tad bit frustrating. I did use your coding from your first respond and tested it. It wouldn't work for me.  But it may have been an ID-10-T error on my part. One thing that just messes with me is and I am not sure how to communicate this but... I went to http://www.jquery.com and downloaded the file it created for me - all sorts of plugins. And thus, that is why you saw three links pertaining to my local folder which in production would also exist on the web site. It, for me, becomes confusing. I like the idea of having the folders locally because what if their web site , i.e. google or jquery.com, was not accessible - the script wouldn't work and then the user would be jumping up/down hollering. See my point? Thank again for all your help, it is appreciated.

Author

Commented:
Excellent help - thank you

Commented:
Thanks for points, but just keep coding for ajax, with many, many trial and error changes, it's low rewards at first, but now for web sites it is necessary and essential to effectively use AJAX and collapsing page containers for phone users , people now will leave a page in less than 10 or 15 seconds, if it does not seem phone friendly, because there are so many other sites they can use instead.

Author

Commented:
You are welcome. thank you for the encouragement. Everyone at EE is so nice.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.