Solved

jQuery submitHandler: function not displaying data

Posted on 2013-10-31
18
637 Views
Last Modified: 2013-11-01
I am using jQuery to input data to a php file and return the results vis json. However, the json is appearing in firebug, but the variable 'messageOutput' is not displaying results on the form. If I replace 'messageOutput' with 'msg.box' then it prints fine. If I enter more than 1 item then it errors with: 'object object'. Can someone point out where my error is as I have been struggling with this for ages. If you need to see any further code, please ask. many thanks.

jQuery code:

submitHandler: function()   {
                if ($("#BA_boxform").valid() === true)  { 
                var data = $("#BA_boxform").serialize();
                $.post('/domain/admin/requests/boxes/boxesadd.php', data, function(msg) {
				
               var messageOutput = '';
                for (var i = 0; i<msg.length; i++){
                    messageOutput += msg[i].box+'  ';     
                }
				$("#BA_addbox").html("You have entered box: " + "<b>" + messageOutput + "</b><br /> You may now close this window.");
                $("#BA_boxform").get(0).reset();
                }, 'json');

         } else

         { 
           return; 
         }
        },
        success:    function(msg)   {
                //$("#BA_addbox").html("You have entered a box");
                //$("#BA_boxform").get(0).reset();
        } 

Open in new window


boxesadd.php

     
<?php

     $dept = mysql_real_escape_string($_POST['customerdept']);
     $company = mysql_real_escape_string($_POST['BA_customer']);
     $address = mysql_real_escape_string($_POST['customeraddress']);
     $service = mysql_real_escape_string($_POST['BA_service']);
     $box = mysql_real_escape_string($_POST['BA_box']);
     $destroydate = mysql_real_escape_string($_POST['BA_destdate']);
     $authorised = mysql_real_escape_string($_POST['BA_authorised']);
     $submit = mysql_real_escape_string($_POST['submit']);
     $boxerrortext = 'You must enter a box for intake';

     $array = split('[,]', $_POST['BA_box']);

     if (isset($_POST['submit'])) 	{
      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
  • 9
  • 6
  • 3
18 Comments
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39614877
It seems like some of your PHP script is missing - there are no closing tags for anything.

Also the logic seems a little flawed. You seem to be splitting the BA_Box data on [,] which seems like an odd delimiter. You then loop through the data and for each box try and json encode the info, over and over again, echoing it out each time. This won't produce valid json

Can you maybe explain what your trying to do (along with a sample of what might be sent through in the 'BA_box')
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39614906
where's the end bracket of your PHP if-else inside the loop line 27
where's the end bracket of your PHP loop line 16
0
 

Author Comment

by:peter-cooper
ID: 39614923
@leakim Sorry my bad. It is there just for some reason didn't post it. Here is revised code. Thanks

if (isset($_POST['submit'])) 	{
      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
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 250 total points
ID: 39614931
replace :
$form=array('dept'=>$dept,
by :
$form[] = array('dept'=>$dept,

and :
foreach ($array as $box) {
by :
$form = array();
foreach ($array as $box) {
0
 

Author Comment

by:peter-cooper
ID: 39614935
@ChrisStanyon
Please see attached revised code for php script. I also attach output that appears in the json tab in firebug. The idea behind , as delimiter is if a client inputs more than 1 item. For example: demobox1000,demobox1001. Thanks

dept
	"DEMO"
	
company
	"DEMO"
	
address
	"28 Some Road London N8 6TY"
	
service
	"Standard"
	
box
	"demobox1001"
	
destroydate
	"27/11/2013"
	
authorised
	"Admin"
	
submit
	"Add Box"

Open in new window

0
 

Author Comment

by:peter-cooper
ID: 39614959
@leakim
I have replaced code and  for 1 item it displays fine, but if 1 enter more than 1 nothing is displayed in BA_boxadd. I have included the relevant code section that I changed. Thanks

$array = split('[,]', $_POST['BA_box']);

     if (isset($_POST['submit'])) 	{
	  $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
 
LVL 82

Expert Comment

by:leakim971
ID: 39614966
put :
 
$result=json_encode($form);
     
     echo $result;

Open in new window

outside the loop !
0
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 250 total points
ID: 39614992
If I understand this correctly, you will have one set of information, and possibly several boxes.  Is there a need to pass back all the form data or are you only interested in the boxes part. And although you seem to be generating an error for empty boxes, you're not doing anything with it, so maybe explain that part

You can't echo json_encode() inside the loop. You do this once at the end of your script. Have a look at this:

<?php 
$boxes = array();
$postBoxes = explode(',', $_POST['BA_box']);
	
foreach ($postBoxes as $box) {
	$boxes[] = $box;
}; 

$results = array(
	'boxes' => $boxes,
	'dept'=>$dept,
	'company'=>$company,
	'address'=>$address,
	'service'=>$service,
	'destroydate'=>$destroydate,
	'authorised'=>$authorised,
	'submit'=>$submit
);

echo json_encode($results);
?>

Open in new window

In your jQuery, you will now have access to all the form data (msg.dept, msg.company etc), plus an array of submitted boxes.

You can either loop through them:

$.each(msg.boxes, function(i,e) {
   //do something with each box:
   console.log("Box Name: " + e);
});

Open in new window

or just join the whole array into a string:

var messageOutput = msg.boxes.join('    ');

Open in new window

0
 

Author Comment

by:peter-cooper
ID: 39615034
@leakim

Displays 1 item but not more than 1. If i enter 2 items then the result is blank. Thanks
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:peter-cooper
ID: 39615041
@leakim
Sorry, my bad. Didn't have it outside the loop. It now displays multiple entries. Thanks
0
 

Author Comment

by:peter-cooper
ID: 39615045
Would it be ok if I split the points as both solutions work. Thanks
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39615048
Yup :)
0
 

Author Comment

by:peter-cooper
ID: 39615073
There is one more thing. After I have returned results, would my sql query be placed after the echo $result. Here is my final code. Also, the error block is redundant because I am using jquery validation. Thanks

$array = split('[,]', $_POST['BA_box']);

     if (isset($_POST['submit'])) 	{
	  $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
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39615085
No. The database stuff should go before echoing results, otherwise how to you respond to errors from your SQL.

FYI - you're still using split() - it's deprecated - switch to explode() instead. Also, it looks like you're trying to use the mysql_* library for your database stuff. That's also deprecated! Switch to mysqli or PDO
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39615090
And I ask again - why are you sending all the data back based on the number of boxes (including the submit button!). Surely you only need the info send back once, as it's the same. If you've got 10 boxes, why send the company name back 10 times??? In fact, why send it back at all? You're not using it..
0
 

Author Comment

by:peter-cooper
ID: 39616284
@Chris

Good point. In my scenario, I only need to send back the box value. Thanks for the heads up re split. Will check it out.
0
 

Author Closing Comment

by:peter-cooper
ID: 39616286
Thanks for all the help
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39616316
If you only need the boxes, your script is very simple:

$boxes = explode(',', $_POST['BA_box']);
$newBoxes = array();

foreach ($boxes as $box) {
   if (!empty($box)):
        $newBoxes[] = $box;
   endif;
endforeach;

$echo json_encode($newBoxes);

Open in new window

In jQuery:

var boxes = msg.join("   ");
$("#BA_addbox").html("You have entered box: " + boxes + "</b><br /> You may now close this window.");

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

863 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

24 Experts available now in Live!

Get 1:1 Help Now