3

I am using jquery to submit a form using serialize and all is well except if I input more than 1 box. If I input 1 box, the msg.box appears in #BA_addbox. If however I enter more than 1 box using , as delimiter, then no msg is shown and no json tab appears in firebug. just the html which is correct. Where have I gone wrong with code.

I have created an array and using foreach with explode to seperate the values but no multiple value being returned. Thanks

UPDATE: vars are being collected in the php script like thus:

php code

$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']);
$date = DateTime::createFromFormat('d/m/Y', $_POST['BA_destdate']);
$destdate = $date - > format('Y-m-d');
$authorised = mysql_real_escape_string($_POST['BA_authorised']);
$submit = mysql_real_escape_string($_POST['submit']);

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

     if (isset($_POST['submit']))   {
        foreach ($array as $box) {

        //$sql = "INSERT INTO `act` (service, activity, company, address, department, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$company', '$address', '$dept', '$authorised', '$destdate', NOW(), '$box', 1)";
        //$result = runSQL($sql) or die(mysql_error());

        $form=array('dept'=>$dept,
                 'company'=>$company,
                 'address'=>$address,
                 'service'=>$service,
                 'box'=>$box,
                 'destroydate'=>$destdate,
                 'authorised'=>$authorised,
                 'submit'=>$submit);
        $result=json_encode($form);

        echo $result;


   } 
  }

jquery code

submitHandler: function()   {
                if ($("#BA_boxform").valid() === true)  { 
                var data = $("#BA_boxform").serialize();
                $.post('/domain/admin/requests/boxes/boxesadd.php', data, function(msg) {
                $("#BA_addbox").html("You have entered box(es): " + "<b>" + msg.box + "</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();
        }   
9
  • 3
    If your PHP loop processes more than one item you're producing invalid JSON as your response, because it echoes out several pieces of JSON one after the other (which doesn't form up to become one large JSON string). You need to use the loop to create an array with all of the data and then use json_encode() after the loop. Commented Jul 6, 2013 at 12:48
  • First of all mysql API is deprecated. Secondly, escaping string with mysql_real_escape_string does not protect you from XSS attacks. Commented Jul 6, 2013 at 12:50
  • @PLB thanks for that but how does that help with my problem? Commented Jul 6, 2013 at 13:05
  • @nnnnnn i have tried your sggestion but all I get in console is 'msg is null'. Could you do fiddle to illustrate how to do correct json markup based on my code. thanks Commented Jul 6, 2013 at 13:07
  • @user1532468 I was not aiming to solve this problem. I just gave you notification. ;) IMO, it's important not to pass by when you see something wrong. Commented Jul 6, 2013 at 13:08

2 Answers 2

1

Per @nnnnnn:

Your resulting json looks like the structure below if there is more than one box. This is invalid json, and therefore can not be reliably parsed.

{
  ...
}{
  ...
}

To fix this, you have to add the arrays to another array, then encode the parent array.

$box = mysql_real_escape_string($_POST['BA_box']);
$array = explode(",", $_POST['BA_box']);
$output = Array();

if (isset($_POST['submit']))   {
  foreach ($array as $box) {

    //$sql = "INSERT INTO `act` (service, activity, company, address, department, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$company', '$address', '$dept', '$authorised', '$destdate', NOW(), '$box', 1)";
    //$result = runSQL($sql) or die(mysql_error());

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

    //Add to a parent array instead
    $output[] = $form;

  }

  //encode the entire array
  $result = json_encode( $output );

  echo $result;
}

This will result in the following structure and for a variable data that contains the parsed json each box can be retrieved via data[0], data[1] etc.

[
  {
    ...
  },
  {
    ...
  }
]
Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain the data[0] code for me. How would I retrieve values based on my original code. thanks
I have no clue what you want to display. In your javascript: data[0] will return the structure for the first box (e.g. what you put in $form in your php script). data.length returns the amount of boxes that are send back.
1

First fix the php to return a valid json array.

if (isset($_POST['submit']))   {
  foreach ($array as $box) {

    //$sql = "INSERT INTO `act` (service, activity, company, address, department, user, destroydate, date, item, new) VALUES ('$service', '$activity', '$company', '$address', '$dept', '$authorised', '$destdate', NOW(), '$box', 1)";
    //$result = runSQL($sql) or die(mysql_error());

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

  }
  echo json_encode( $result );
}

Then the msg parameter in the post callback should be an array of results, so you can't just do msg.box to get the list of boxes. I would suggest something like this:

boxes = jQuery.map(msg,function(item){
  return item.box;
}).join(',');

That extracts the box property from each item in the array and joins them into a comma separated list. You can then display that list like this:

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

Given these changes, your code works for me. If you're having other problems, I suggest you post more of your html - in particular your form structure. It's possible your form isn't submitted the correct values to get a valid response from the server.

7 Comments

I am getting error: length = elems.length, in jquery.js. I have made a fiddle to show the code I am using. Can you check for error please. thanks jsfiddle.net/T2NuC/1
Your php is missing a semicolon at the end of this line: $result[]=$form. Also you're going to have to assign some values to the variables $dept, $company, $address, etc. I would suggest you hardcode some strings initially.
james Strange but when I posted code there was a semi coln. def one in my code. The values are being assigned using serialize are they not? However, still getting error. Please see my update in OP. thanks
You haven't initialised the $submit variable. Also you should be aware that mysql_real_escape_string won't work if you haven't opened a database connection with mysql_connect. I'm also not sure why you're calling that on the values you're going to be returning in the json object - that only makes sense if you're using those values in a database query.
James I am making a db query just not shown in code. In my code I have: $submit = mysql_real_escape_string($_POST['submit']); and I have update OP with code. Can you please explain how I haven't initialized the $submit variable with an example as I am fairly new to jquery. I have updated fiddle with code. jsfiddle.net/T2NuC/3 thanks
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.