9

I am trying to load a page into a modal window "checkout.php" after submitting a form, but I need it to load with the results of the form. Normally, one would just set the action of the form to the url and the data gets passed, but in this case, the page needs to be loaded into a modal with that data which requires the use of more jQuery than I know.

HTML

<form id="shippingform" name="shippingform" method="post" action="#">
<table id="box-table-a" width="25%" border="1">
<thead>
    <tr>
        <th scope="col" width="40%">USPS Option</th>
        <th scope="col" width="40%">Price</th>
        <th scope="col" width="20%" style="text-align: right;">Select</th>
    </tr>
</thead>
<tbody>
<tr>
  <td class="first">Ground:</td>
  <td><?php echo "$" . sprintf("%01.2f", $groundTotal) ?></td>
  <td class="last"><input name="shipping" type="radio" id="radio" value="<?php echo $groundTotal ?>" checked="checked" /></td>
</tr>
<tr>
  <td class="first">Priority:</td>
  <td><?php echo "$" . sprintf("%01.2f", $priorityTotal) ?></td>
  <td class="last"><input type="radio" name="shipping" id="radio2" value="<?php echo $priorityTotal ?>" /></td>
</tr>
<tr>
  <td class="first">Express:</td>
  <td><?php echo "$" . sprintf("%01.2f", $expressTotal) ?></td>
  <td class="last"><input type="radio" name="shipping" id="radio3" value="<?php echo $expressTotal ?>" /></td>
</tr>
</tbody>
</table>
<a href="#" onclick="totalCalc()">submit</a>
</form>

JS

<script language="javascript">
function totalCalc() {
$('#cartdialog').load("/ash/shop/checkout.php");
}
</script>

What I have above will load the checkout.php page into the modal after clicking the submit button for the form. I AM NOT asking why the page isnt loading with the information sent with the form. I completely understand that what I am doing here is simply executing a function to load "checkout.php" into the div that is the modal. I need someone to explain to me how I can edit my function so that "checkout.php" gets loaded like if it were the action of the form, the data would be passed through.

Thanks in advance for the help!

EDIT BELOW

<form id="shippingform" name="shippingform" method="post" action="#">

JS

$('#shippingform').submit(function(event){
var data = $(this).serialize();
$.post('/ash/shop/checkout.php', data)
    .success(function(result){
        $('#cartdialog').html(result);
    })
    .error(function(){
        console.log('Error loading page');
    })
return false;
});

THE CHECKOUT.PHP PAGE WHERE IT CALLS THE INPUT "shipping"

<?php 
//total up price of all items
$subtotal = ($subtotal + ($row_rsMyCart['price'] * $row_rsMyCart['quantity']));
$myTotal = ($subtotal + $_POST['shipping']);

} while ($row_rsMyCart = mysql_fetch_assoc($rsMyCart)); ?>
</table>
<p>
<?php
//development
echo "<br>";
echo "Subtotal: $" . sprintf("%01.2f", $subtotal);
echo "<br>";
echo "Total: $" . sprintf("%01.2f", $myTotal);
?>
</p>
livinzlife
  • 863
  • 3
  • 17
  • 33
  • Possible duplicate: http://stackoverflow.com/questions/1218245/jquery-submit-form-and-then-show-results-in-an-existing-div The question is not quite the same but the answers are equivalent, that's why I marked this as duplicate. – pgpb.padilla Sep 05 '12 at 15:27

2 Answers2

11

Bind to the submit event on your form, instead of using the onClick attribute.

On submit, serialise the form values, post to your url and insert the result into the target div.

$('#myform').submit(function(event){
    var data = $(this).serialize();
    $.post('/ash/shop/checkout.php', data)
        .done(function(result){
            $('#cartdialog').html(result);
        })
        .fail(function(){
            console.log('Error loading page');
        })
    return false;
});

EDIT 1: Given your html, you need to replace

<a href="#" onclick="totalCalc()">submit</a> 

with

<input type="submit" name="submit" value="Submit">
Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87
Rob Cowie
  • 22,259
  • 6
  • 62
  • 56
  • @robcowie @mattball Seems like these two are pretty close and are doing the same thing. I am getting spit out to the site root with the data appended to the end like this: www.siteroot.com/?shipping=19.32 Ultimately the goal is to load "checkout.php" which is found at www.siteroot.com/ash/shop/checkout.php with the data INSIDE the modal. I have been using .load() to load the contents of the page within the modal – livinzlife May 11 '11 at 23:05
  • @robcowie closer but still no cigar... This is actually causing the page to reload on "checkout.php" when what I need to do is ONLY reload the contents of the div #cartdialog with "checkout.php" Also, it is appending the data to the end of the URL, and normally the form will post, "checkout.php" will load with the submitted data and there will be nothing extra in the url – livinzlife May 11 '11 at 23:41
  • @livinzlife: I've fixed a bug in my answer so try again. As for the query string, .post() will not cause that to happen. Make sure you remove your original totalCalc() function (or otherwise ensure it is not called). – Rob Cowie May 12 '11 at 00:02
  • @robcowie Sorry I didnt realize I couldnt put code in comments. I edited my original post. I fixed the form, made use of a regular form submit button, and got rid of totalCalc(). Now my modal window just disappears and nothing happens. The checkout.php page is not loaded into the #cartdialog div, and I dont know how to check whether the form was submitted or not – livinzlife May 12 '11 at 00:26
  • @robcowie Not yet, is there a reason I am using .html() instead of .load() ? – livinzlife May 12 '11 at 00:31
  • @livinzlife: You _could_ use .load() instead of .post(); .load() will use the POST method if data is supplied (i.e. `.load('url', {})`). I would suggest however using .post() as it provides the opportunity to handle errors explicitly. `.html(result)` simply inserts the value returned from your url into the target div. Are you getting javascript errors? Can you confirm your request is being handled by your server correctly? – Rob Cowie May 12 '11 at 00:46
  • @robcowie I am not sure if I am getting javascript errors, what utility could I use to check. Also, please let me know how I can test that the request is being handled properly. Note in my edit above that I have posted where the value for input name "shipping" gets called in the checkout.php page. That is just a section of the site, but that is the page I need to load within the modal and the data submitted from the form gets used there. Wasnt sure if that would help. I appreciate you sticking this one out with me, some of this is built by someone else and I am trying to work with it – livinzlife May 12 '11 at 00:55
  • @livinzlife: No problem. It's very late here but I'll check back tomorrow. Let us know what browser you are using – Rob Cowie May 12 '11 at 00:58
  • @robcowie I am using firefox, however I am getting the same results in safari and chrome. When I click the submit button, it closes my modal window and then appends the # symbol from the form action to the end of the url in the url bar. It may or may not be doing stuff behind the scenes too I am not sure, but it doesn't load checkout.php in the modal. Ill check in tomorrow. – livinzlife May 12 '11 at 01:03
  • @livinzlife: Can you post your entire page source (html and js) somewhere... suggest https://gist.github.com/ (create a new public gist). For some reason, the default submit event of the form is not being prevented correctly. – Rob Cowie May 12 '11 at 08:10
  • @robcowie I wont be able to until late tonight, Ive got a long work day. Ill try this gist.github.com out. I have been able to figure out how to send it using .load() but like you mentioned, it may be better to be able to handle errors. I think it may be beneficial to learn how to do this the .post() way. Something that may or may not be relevant is that this form is not intended to return any results, it is just intended to load a new page and post a value into a php variable. – livinzlife May 12 '11 at 15:08
  • 1
    I would like to note that the jQuery API has changed and `.success()` and `.error()` are no longer supported. They have been replaced by `.done()` and `.fail()` – Nick Jun 20 '14 at 13:18
2

Use $.post() to submit the form using ajax.

$('#shippingform').submit(function ()
{
    var $this = $(this);

    $.post('/ash/shop/checkout.php',
    {
        data: $this.serialize()
    }, function (response)
    {
        $('#cartdialog').html(response);
    });

    return false;
});
Matt Ball
  • 354,903
  • 100
  • 647
  • 710