Skip to content Skip to sidebar Skip to footer

Submit A Form Without Refreshing A Page Using AjaxForm

I'm a total novice so please excuse my ignorance. I have website with a php shopping cart that refreshes to the cart page when something is added to to the cart. I want to modify i

Solution 1:

The major problem here is not that you have a loop, but that you have a server-call inside of it. The best way to handle this is to change the way that jsrefreshincart.php handles calls from the server. Instead of having multiple calls inside the loop, collect all the data and have a single call outside the loop.

I don't think that's something the jQuery Form plugin can handle; rather, you'll probably have to write some custom code (like below):

<script>
  $(document).ready(function() {
    $("[id^=ectform]").on('submit', function(e) {
      e.preventDefault();
      $('[id^=gld]').html('loading...'); // Trigger all loading messages simultaneously
      var formNums = [];
      for (i = 0; i < count; i++) {
        formNums.push(i);
      }
      $.post({
        $(this).attr('action'), // Where to send the form action
        formNums: formNums, // The data to send when submitting the Ajax call
        refreshCartData // The callback used to refresh the page
      });
    });
  });

  // Called automatically when the server responds with data
  function refreshCartData(data) {
    // Loop through all forms and update them
    for (var i = 0; i < data.length; i++) {
      // Update HTML
      $('#gld' + data[i].formNum).html(data[i].cartHTML);
    }
  }
</script>

Your jsrefreshincart.php should return data for all of this. For example:

<?php

// Used to load the cart data - I'm sure you have something similar
require_once('cart.php');
// Send everything back as JSON
header('Content-type: application/json');
// Initialize the data to send back
$data = array();
// Iterate over all data send to the server
foreach ($_POST['formNums'] as $formNum) {
  $data[] = array(
    // The unique ID for the form number
    'formNum' => $formNum,
    // Again, however you get the view data for your cart line items works fine
    'cartHTML' => Cart::getCartHTML($formNum)
  );
}
// Spit out the JSON data
echo json_encode($data);

Some additional suggestions:

  • Your variables d, e, and f in your original code are not necessarily all updated during the Ajax round-trip
  • You need to add more commenting and indentation - it seems simple, but proper documentation is the best way to communicate your problems to other developers
  • Consider using a different way to keep track of data besides a "count of forms" - classes can work too
  • My assumption is that anything starting with an ID of ectform is a form to have this functionality captured in; if this is not the case, parts of the above solution might not make sense

Solution 2:

After looking at the suggestion by Dykotomee (thank you), it gave me the idea how I could amend my script to work without the loop:

<script>
 $(document).ready(function(){ // when DOM is ready
   $("[id^=ectform]").on('submit', function(e) {  // on submission of any form with id beginning "ectform"
    e.preventDefault();             // prevent the form itself submitting the data
      var subformid = $(this).attr('id'); // set variable with the id of the submitted form
       $(this).ajaxSubmit({     // submit the form via ajax which will add the product to the cart
        success:function(){    //on successful submission of the form
         $.ajaxSetup({ cache: false }); // turn off cache so the updates will refresh on all browsers
         $("#div1").load("jsrefresh.php");  //  load div in mini cart with new updated cart quantity
        var str = subformid.replace("ectform", "");  // trim subformid to leave just the end digits and call this variable str
       var d = "#glc" + str;   // not important for purposes of explanation
      var f ="#gld" + str;  // f is the id of the div in the submitted form to be updated 
    var e = eval("z" + str);  // e is the product number
$(f).html('Adding item to Cart...').load("jsrefreshincart.php",{ prodynum: e, divno: d}); // send data to jsrereshincart.php and load updated html into div f.
      }
    });
   });
 });
</script>

I used ajaxSubmit instead of ajaxForm which allowed me to trigger the submission of the form using $("[id^=ectform]").on('submit', function(e) {....... I was then able to catch the id of the form submitted with var subformid = $(this).attr('id'); Now I had the id of the submitted form , I was able to use ajax .load to get the updated cart HTML into the div in that particular form rather than looping through all the forms and updating them one by one. The script now only makes a total of 2 server calls per form submission. My previous script made up to 50 calls when a maximum of 25 products/forms were displayed on the products page. I could modify this script and the php scripts to do everything with a single call but other pages on the site don't have products, just the mini cart so it's easier to keep the scripts separate.


Post a Comment for "Submit A Form Without Refreshing A Page Using AjaxForm"