Solved

submitHandler: triggering incorrect dialog

Posted on 2014-03-03
7
308 Views
Last Modified: 2014-03-05
I am trying to debug a problem I have with submitHandler: function. What is happening, in firebug it is displaying the correct error message based on the true handle in the submitHandler. But, it is firing the success dialog and not the error dialog. I am fairly new to jquery and ajax so I have proably got some brackets or commas in the wrong place.

I would be grateful if someone could point out my error. Thanks

submitHandler: function()   {
                if ($("#USRboxint").valid() === true)  { 
                var data = $("#USRboxint").serialize() + '&submit=true';
                $.post('/domain/users/box.php', data, function(msgs) {

                if (msgs.boxerror === true) {

                   var $dialog = $('<div id="dialog"></div>').html('<br /><b>Your New entry was NOT SUBMITTED.<br /><br />Thank you.</b>');
                   $dialog.dialog({
                   autoOpen: true,
                   modal: true,
                   title: 'New entry Unsuccessfull',
                   width: 400,
                   height: 200,
                   draggable: false,
                   resizable: false,
                   buttons: {
                   Close: function() {
                   $( this ).dialog( "close" );
                   }
                   }
                   });

                    }

                else

               var messageOutputs = '';
                for (var i = 0; i<msgs.length; i++){

                    messageOutputs += msgs[i].box+'  ';

                }



                $("#USRboxint").get(0).reset();

                var $dialog = $('<div id="dialog"></div>').html('<br /><b>Your New entry was successfully submitted.<br /><br />Thank you.</b>');
                   $dialog.dialog({
                   autoOpen: true,
                   modal: true,
                   title: 'New entry successfull',
                   width: 400,
                   height: 200,
                   draggable: false,
                   resizable: false,
                   buttons: {
                   Close: function() {
                   $( this ).dialog( "close" );
                   }
                   }
                   });

                //$("#frmreport").get(0).reset();
                }, 'json');

         } 
        },
        success:    function(msgs)   {

        } 

Open in new window


PHP Code

<?php

$boxerrortext = 'No duplicates';
$array = split('[,]', $_POST['box_add']);

     if (isset($_POST['submit']))   {
            if ($box == 'DEMO111')
            {

            $error = array('boxerror'=>$boxerrortext);
            $output = json_encode($error);

            echo $output;
            return;
            }
            else
      $form = array();
      foreach ($array as $box) {


      // if (empty($box)) {
       // $error = array('boxerrortext'=>$boxerrortext);

     // $output = json_encode($error);

     // echo $output;


     // }
    // else
     // {

     $form[] = array('dept'=>$dept, 
                 'company'=>$company,
                 'address'=>$address,
                 'service'=>$service,
                 'box'=>$box,
                 'destroydate'=>$destroydate,
                 'authorised'=>$authorised,
                 'submit'=>$submit);


      }

   } 
   $result=json_encode($form);

     echo $result;

?>

Open in new window

0
Comment
Question by:peter-cooper
  • 3
  • 3
7 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39901248
Consider adding error_reporting(E_ALL) to your PHP scripts.  In the example above, $box appears to be undefined, but PHP will not tell you unless you ask PHP to tell you.

You may also want to adopt a coding standard.  It will make your code easier to read and debug.  See #7 for an explanation and suggestion.

Whenever you're unsure about what a PHP variable contains, you can find out with var_dump().

If you change these scripts to use the GET method (temporarily) you will be able to test the PHP script with a browser-address-bar URL.  Just a thought... That might make testing easier.
0
 
LVL 33

Expert Comment

by:Slick812
ID: 39901522
greetings peter-cooper, there are many things incorrect in your PHP code, I will guess that this is box.php page for the ajax request in JS as -
$.post('/domain/users/box.php', data, function(msgs) {

you use this to get your datd to send -
var data = $("#USRboxint").serialize() + '&submit=true';

In your PHP you have -
$array = split('[,]', $_POST['box_add']);

this may be correct, BUT I do not see it as a good way to do this ?
But this will ALWAYS be false -
    if ($box == 'DEMO111')
so it is INCORRECT code,

later in code you have a foreach ($array
however, you use variables that do not exist yet (undefined, PHP will tell you) as $dept
, $company , $address , $service , $destroydate

So this code is ALSO incorrect ! !

You can NOT use any of the code arrangement you have now, and need to begin again to code for PHP with more understanding of whats happening in AJAX exchanges.

ALSO your javascript for an AJAX request is incorrect, for instance you have -

} // for the if (msgs.boxerror === true)
else var messageOutputs = '';

so the -
  var $dialog = $('<div id="dialog"></div>').html('<br /><b>Your New entry was successfully submitted.<br /><br />Thank you.</b>');

will display even if the ERROR above it is displayed.

It looks like you are just trying to understand and use an ajax, but these code sections may not help you with this.
You need to redo your code, and use a more simple learning JS code for browser display, you need to see what the PHP is sending back to the ajax, to know where to start your  use of JS code.
0
 

Author Comment

by:peter-cooper
ID: 39902926
@ Slick812

Thank you for your constructive comments. There are however, a couple of points I take issue with.

1) In this line if (msgs.boxerror === true) { Fire bug is showing me the correct response from php - ''No duplicates', so php is sending the correct message and the submitHandler is responding to the php.

2) This line 'if ($box == 'DEMO111')' is working correctly and is sending the 'boxerror' .

The only area where I am getting stuck seems to be responding to the correct dialog. How do I code so that if an error has occured, open the 'New Entry Unsuccessfull' and if code is ok, open the 'New Entry Successfull dialog.

If I enter valid values, the php enters correct values into db.

Hope you can help. Many thanks
0
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 39903862
Yes I can help, but from your last comment, you do NOT know what is going on in this code work AT ALL, NONE. You simply can not expect to be able to build this AJAX with your very limited knowledge of PHP an Javascript. Since you have asked, I took a closer look at your code in JS and PHP, BOTH ARE JUST INCORRECT for this ajax operation.

you say -
1) In this line if (msgs.boxerror === true)  "so php is sending the correct message"
wrong, PHP is NOT sending the correct response. But My Point was that you have left out the code container brackets { } after the else
else { // YOU NEED THESE BRACKETS
  var messageOutputs = '';
  for (var i = 0; i<msgs.length; i++){
    messageOutputs += msgs[i].box+'  ';
    }
// rest of code here
  } // end of else code

Open in new window


2) This line 'if ($box == 'DEMO111')' is working correctly and is sending the 'boxerror' .
wrong, It is IMPOSSIBLE because there is NO $box variable to test! , , it is non-existent, undefined.

Some how you believe that this is working because the Jquery Dialog box for success pops up, the way your code is, this line -
var $dialog = $('<div id="dialog"></div>').html('<br /><b>Your New entry was successfully submitted.<br /><br />Thank you.</b>')

will execute no matter what, if there is an ajax response, if there is not an ajax response, if the response is correct or incorrect, it will pop up, That is my opinion of your code work. No where do you TEST the JS variable msgs to see if it has anything in it, or WHAT is in it.

Sorry but I can not correct your code (php or js) since I can not see it as a way to do this ajax operation.
I have made some code to show you how to set up a Development testing for Ajax in JQuery and PHP, and maybe show you how this ajax operation works.

first the html page (no PHP here, although you can do a PHP page if thats your setup), that has a simple FORM, and does an ajax to php with the inputs, Please notice that it has a DEBUG check box, that you can check for development, to SEE the entire PHP sendback string, and see if it is correct, of course you need yo know what a JSON string shold look like
<!doctype html>
<html><head><title>jQuery AJAX post</title>
<style>
body{background:#e3f7ff;}

#form1{
position:relative;
width:25em;
min-height:4em;
background:#fbdba0;
margin:2px auto;
border:3px solid #5ad;
padding:9px;
}

#popup{
position:absolute;
top:4px;
left:2px;
display:none;
width:24.5em;
height:3.5em;
background:#ffbaaa;
border:4px solid #d00;
padding:6px;
}

.xBut{
position:relative;
top:-5px;
right:-5px;
width:1em;
height:1em;
font-weight:bold;
float:right;
line-height:98%;
cursor:pointer;
font-family:arial,sans-serif;
background:red;
color:white;
text-align:center;
border:1px solid white;
}

.dere{
border:2px solid #00d;
min-height:2em;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>  // I use the latest version of Jquery as 1.11.0

// I always have the ajaxError(function for development
$(document).ajaxError(function( event, request, settings, exc ) {
if (request.status==404) alert("ERROR from Ajax as '404 status' the "+settings.url+" page was NOT on Server, \nCan NOT recover from this ERROR, This operation is NOT available!"); else
alert("ERROR from Ajax POST= Server-Status: "+request.status+", post-URL: "+settings.url+", post-Data: "+settings.data+", error because: "+exc);
});

//I use an Independent (non Jquery) function doPost( ) for development
//I do not do any verification, that will be added AFTER I get the ajax working
function doPost( ) {
  var postOut = $("#form1").serialize();// get the FORM inputs as a string
 
//Get the Debug checkbox to set PHP for NON JSON response
  if($('#check1').prop('checked')) postOut += "&debug=yes";

  var postRe = $.post( "jqy-post.php", postOut);//do asyncronous POST ajax
  
// IMPORTANT, you need to understand what should be SENT and RECEIVED by ajax
  postRe.done(function( data ) {
  if(typeof(data)=='object'){  //IMPORTANT for DEBUG test for JSON Object
    $('#debug1').html("No DEBUG");// erase the DEbug
    if(data.error) { // test for error response
      alert("ERROR="+data.error+"- php value check Invlaid, "+data.message);
      return; // end ALL JS code
      }
// Format your browser output next in the out1 variable string
    var out1 = "Success as <b>"+data.name2+"</b>, gave "+data.age2+", "+data.email2+" and made it around the ajax operations";
    $('#ajaxRe').html(out1);// load formated ajax response to div
    $('#popup').show(); //show div
    } else { // IMPORTANT for DEBUG, Show the entire Ajax RESPONCE in the debug div
    $('#debug1').html(data);
    alert("ERROR- JSON was NOT retutned, see Debug DIV");
    return;
    }
    });
  };

</script>
</head>
<body><h3 style="text-align:center;">JQuery AJAX post development</h3>
<hr>
<form name="aform" id="form1">
Name: <input type="text" name="name" size="16" value="" /> must be more than 4 characters<br />
Age: <input type="text" name="age" size="5" maxlength="3" value="" /> Years: must be older than 17 years<br />
Email: <input type="text" name="email" size="20" value="" /> not checked in PHP<br />
<div id="popup"><div class="xBut" onclick="$('#popup').hide();">X</div><span id="ajaxRe">NONE YET</span></div>
</form><center><button type="button" onclick="doPost()">do Ajax Form</button></center>
<br />Debug: <input type="checkbox" id="check1" />-Check to get return string in Debug Div
<div id="debug1" class="dere">No DEBUG</div>
</body></html>

Open in new window


next is the code for the jqy-post.php page
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Change the Type to text/plain
header('Content-Type: text/plain');

// Get the POSTs next
$name = $_POST['name'];
$age = (int) $_POST['age'];
$email = $_POST['email'];
$debug=(empty($_POST['debug']))?'no':$_POST['debug'];


$bob = $nothere; // Will cause PHP Notice, just to show you the DEBUG in the browser
if ((strlen($name) > 4) && ($age > 17)) { // Check the nessary POST values for valid
// Build a JSON object send back array in PHP
  $ajaxOut = array('name2'=>$name, 'age2'=>$age, 'email2'=>$email);
  $ajaxOut = json_encode($ajaxOut);
  } else {
  $ajaxOut = array('error'=>5, 'message'=>'FAILURE! Your AJAX Submission was Junk! n='.$name.' a='.$age);
  $ajaxOut = json_encode($ajaxOut);
  }
  
// IMPORTANT VERY ! you must set the Content-type to get the Jquery to do a JSON object
if ($debug != 'yes') header('Content-type: application/json');
echo $ajaxOut;
?>

Open in new window

Try and see if this code can help you to do a ajax, ask questions is you need more.
0
 

Author Comment

by:peter-cooper
ID: 39906548
@Slick Thanks for taking so much time on this. I shall accept it as a solution and play around with it so I can understand what is supposed to happen in what order. Thanks very much.
0
 

Author Closing Comment

by:peter-cooper
ID: 39906551
Thanks once again
0
 
LVL 33

Expert Comment

by:Slick812
ID: 39907636
a couple of things, in an ajax send and receive it really depends on what needs to be done to the web page using it, as you only do one thing (submit a form) and just show a error or success announcement, you do not have to deal with changing data sends and different data receives and the html formatting for page output. But even with this you will likely need to do mysql database in php, and need some sort of error control for user mis-typed form entries, to have the correct input. For me all of this needs testing in ajax development on the JS and in the PHP, so I have to have a way to see what is used for the ajax.
In your code you return two different types of JSON, an array and an object (for error), you can do this if you know how to differentiate in the JS which is which, , but in your code you have -
if (msgs.boxerror === true)
if it is an array the msgs.boxerror will be undefined, and that code will produce an incorrect JS code evaluation as undefined, You can use -
if (msgs.boxerror) because undefined will evaluate as false, in mine I use -
if (data.error) {

I consider it to be best when JSON is used to send back one type of JSON, as all send backs are arrays, , or all send backs are Objects. It is helpful for me to have an object identifier, such as error, or result, or opp (operation) such as -
if (data.opp) {
switch (data.opp){
  case 0: showError(0, null); // fatal Error
    break;

  case 1: showError(1, data.entry); // entry Error
    break;

  case 2: showSuccess(data.finish); // success dialog, 
//data.finish is an ARRAY to be used in function as= for (var i = 0; i<finish.length; i++){
    break;

  case 3: showNoData(data.missing); // incorrect db dialog
    break;

  default: alert('ERROR - Sever not able to complete operation, ecode'+data.opp);
  }

} else alert('ERROR - Sever not able to respond, may not recover, ecode111');

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now