Search code examples
phpajaxformssubmitcolorbox

Php Ajax form submit in colorbox


I have a form with some php to validate and insert in the database on submit and the form opens in colorbox.

So far so good. What I'm trying to do is to close colorbox and refresh a div on success.

I guess I need to pass a response to ajax from php if everything OK, close the colorbox with something like setTimeout($.fn.colorbox.close,1000); and refresh the div, but I'm stuck because I'm new in ajax.

I'll appreciate any help here.

Here is my ajax:

jQuery(function(){
 jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
   cbox_submit();

  }});
});


function cbox_submit()
{
  jQuery("#pre-process").submit(function(){
   jQuery.post(
      jQuery(this).attr('action'),
      jQuery(this).serialize(),
      function(data){
       jQuery().colorbox({html: data, onComplete: function(){
          cbox_submit();

        }});
      }
    );
    return false;
  });
}

form php code:

    <?php
error_reporting(-1); 
include "conf/config.php";

if(isset($_REQUEST['rid'])){$rid=safe($_REQUEST['rid']);}
if(isset($_REQUEST['pid'])){$pid=safe($_REQUEST['pid']);}
$msg = '';
if (!$_SESSION['rest_id']) $_SESSION['rest_id']=$rid; //change to redirect

$session_id=session_id();


if(isset($_REQUEST['submit'])){

if(isset($_POST['opta'])){
$opta=safe($_POST['opta']);
$extraso = implode(',',array_values( array_filter($_POST['opta']) ));
                    }

if (array_search("", $_POST['opt']) !== false) 
{
$msg = "Please select all accessories!";
}else{

$extrasm = implode(',',array_values( array_filter($_POST['opt']) ));

if ($_POST['opt'] && isset($_POST['opta'])) {$extras= $extrasm .",". $extraso;}
if ($_POST['opt'] && !isset($_POST['opta'])) {$extras= $extrasm;}
if (!$_POST['opt'] && isset($_POST['opta'])) {$extras= $extraso;}

$sql['session_id']  = $session_id;
    $sql['rest_id'] = $_POST['rid'];
    $sql['prod_id'] = $_POST['pid'];
    $sql['extras']  = $extras;
    $sql['added_date']  = Date("Y-m-d H:i:s");
    $newId=insert_sql("cart",$sql);

    }
}
?>

<form id="pre-process" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div style="background-color:#FFF; padding:20px;">
<?=$msg;?>
  <?php
  $name = getSqlField("SELECT name FROM products WHERE resid=".$_SESSION['rest_id']." and id=".$pid."","name");
  echo "<div style='color:#fff; background-color:#F00;padding:10px;' align='center'><h2>".$name."</h2></div><div style='background-color:#FFF; padding: 20px 70px 30px 70px; '>Please select accessories.<br><br>";
 $getRss = mysql_query("SELECT * FROM optional_groups_product where prodid=".$pid." order by id asc");
    while ($rsrw = @mysql_fetch_array($getRss)) {

  $goptionals = getSqlField("SELECT goptionals FROM optionals_groups WHERE resid=".$_SESSION['rest_id']." and id=".$rsrw['goptid']."","goptionals");

        $goptionals=explode(', ',($goptionals));

echo "<select name='opt[]' id='opt[]' style='width:220px;'>";
echo "<option value='' >Select Options</option>";
    foreach($goptionals as $v)
    {
         $vname = mysql_query("SELECT * FROM optionals where id=".$v." LIMIT 0,1");
         while ($rsgb = @mysql_fetch_array($vname)) {
             $aa=$rsgb['optional'];
         }
             echo "<option value=".$v." >".$aa."</option>";


    }
         echo "</select>(required)<br>";       
    //}
        }
        $getRss = mysql_query("SELECT * FROM optional_product where prodid=".$pid.""); 
        ?>
        <br><br>
        <table border="0" cellpadding="0" cellspacing="0" >
       <tr>
    <td bgcolor="#EAFFEC">
<div style="width:440px; "> 
<?php

while ($rssp = @mysql_fetch_array($getRss)) {
 $optional=getSqlField("SELECT optional FROM optionals WHERE id=".$rssp['optid']."","optional");
 $price=getSqlField("SELECT price FROM optionals WHERE id=".$rssp['optid']."","price");
?>
<div style="width:180px;background-color:#EAFFEC; float:left;padding:10px;""><input type="checkbox" name="opta[]" id="opta[]" value="<?=$rssp['optid']?>"  /> <i><?=$optional?> [<?=CURRENCY?><?=$price?> ]</i> </div>
<?php } ?>
</div>

</td>
 </tr></table>
<input type="hidden" name="rid" value="<?=$rid?>" />
<input type="hidden" name="pid" value="<?=$pid?>"/>
    </div><input type="hidden" name="submit" /><input  id='submit' class="CSSButton"    style="width:120px; float:right;" name='submit' type='submit' value=' Continue ' /><br />

<br /><br />
</div>
</form>

Solution

  • I don't know colobox, but if I understand well what you are trying to do,
    I would say your javascript should more look like this

    function cbox_submit()
    {
      jQuery("#pre-process").submit(function(e) {
        e.preventDefault(); // prevents the form to reload the page
        jQuery.post(
          jQuery(this).attr('action')
        , jQuery(this).serialize()
        , function(data) {
            if (data['ok']) { // ok variable received in json
              jQuery('#my_colorbox').colorbox.close(); // close the box
            }
          }
        );
        return false;
      });
    }
    
    jQuery(function() {
      jQuery('#my_colorbox').colorbox({
        maxWidth: '75%'
      , onComplete: cbox_submit // Bind the submit event when colorbox is loaded
      });
    });
    

    You should separate at least your php script that does the post part.

    And this php (called with jQuery(this).attr('action')) should return a json ok variable if successfull. Example:

    <?php
    # ... post part ...
    # if success
    ob_clean();
    header('Content-type: application/json');
    echo json_encode(array('ok' => true));
    ?>