Asked  9 Months ago    Answers:  5   Viewed   49 times

Following the examples on this page: http://www.formget.com/submit-form-using-ajax-php-and-jquery/ I am converting the forms on one of my sites to use ajax for submission, that way uses can use the forward and back buttons, and their info isn't showing up in the address bar. It's worked so far, on pages that have a single form. But one page has multiple forms on it.

Form from campers.php

<form id="retro1457806069">
<input type="hidden" id="class" name="classa" value="retro">
<input type="hidden" id="type" name="type" value="1">
<input type="submit" id="submit" value="Rent This Camper"></form>

<form id="two1457806069">
<input type="hidden" id="class" name="classa" value="classtwo">
<input type="hidden" id="type" name="type" value="1">
<input type="submit" id="submit" value="Rent This Camper"></form>

<form id="three1457806069">
<input type="hidden" id="class" name="classa" value="classthree">
<input type="hidden" id="type" name="type" value="1">
<input type="submit" id="submit" value="Rent This Camper"></form>

Those are the actual form codes generated by my script (with all the excess text and such removed around them.

script.js:

$(document).ready(function() {
  $("#submit").click(function() {
    var classa = $("#classa").val();
    var type = $("#type").val();
    // Returns successful data submission message when the entered information is stored in database.
    var dataString = 'class=' + classa + '&type=' + type;
    if (classa == '' || type == '') {
      alert("Please Fill All Fields");
    } else {
      // AJAX Code To Submit Form.
      $.ajax({
        type: "POST",
        url: "campersub.php",
        data: dataString,
        cache: false,
        success: function(result) {
          window.location.assign("gear.php")

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

campersub.php

<?php
session_start();
$_SESSION["class"]=$_POST["class"];
$_SESSION["type"]=$_POST["type"];
echo "Success.";
?>

The problem is, instead of adding the form information to the $_SESSION array and redirecting the browser to gear.php when I click on the first submit button, absolutely nothing happens. But when I click on the second or third submit buttons it redirects the page to campers.php?classa=classone&type=1 for example.

 Answers

75

I have modified some things, having in mind mainly: 'Id attributes must be unique in the document'

(Even, If there are not other references in the code to the form elements by id then the id attribute can be removed) So I have renamed ids as they have an unique value, then I fetch the click event for catch any input submit

NOTE: I have accessed to the other elements from the parent (its form) which contains the last clicked element because I'm not sure if it is the entire HTML you have.

campers.php

<form id="retro1457806069">
<input type="hidden" id="class1" name="classa" value="retro">
<input type="hidden" id="type1" name="type" value="1">
<input type="submit" id="submit1" value="Rent This Camper"></form>

<form id="two1457806069">
<input type="hidden" id="class2" name="classa" value="classtwo">
<input type="hidden" id="type2" name="type" value="1">
<input type="submit" id="submit2" value="Rent This Camper"></form>

<form id="three1457806069">
<input type="hidden" id="class3" name="classa" value="classthree">
<input type="hidden" id="type3" name="type" value="1">
<input type="submit" id="submit3" value="Rent This Camper"></form>

script.js

$(document).ready(function() {
  $("input[type=submit]").click(function(e) {
    // **Accesing by proximty of the last clicked element, and by its name.
    e.preventDefault();
    var classa = $(this).parent('form').find('input[name="classa"]').val();
    var type = $(this).parent('form').find('input[name="type"]').val();
    // Returns successful data submission message when the entered information is stored in database.
    var dataString = 'class=' + classa + '&type=' + type;
    if (classa == '' || type == '') {
      alert("Please Fill All Fields");
    } else {
      // AJAX Code To Submit Form.
      $.ajax({
        type: "POST",
        url: "campersub.php",
        data: dataString,
        cache: false,
        success: function(result) {
          window.location.assign("gear.php")

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

I think it must run with these changes...

Wednesday, March 31, 2021
 
apokryfos
answered 9 Months ago
23

Wait until the ajax completes then submit the form.

   jQuery(document).ready(function() {
      function senddata() {
        var formdata = jQuery("#danlevi").serialize();
        var decoded = decodeURIComponent(formdata);
        strip = decoded.replace(/[[]]/g, "_");
        alert(strip);
        jQuery.ajax({
          type: "GET",
          url: 'dev/wp-content/themes/twentythirteen/custom/process_address.php',
          data: strip,
          complete: function(){
              jQuery("#danlevi").submit(); //submit the form after ajax completes
          }
        });
        return false; //stop the form from initially submitting
      }
    });
Wednesday, March 31, 2021
 
Slinky
answered 9 Months ago
50

Another option is to have your controller return something other than a response and use the kernel.view event to transform that into what you want. This would be better DRY because the logic is encapsulated in the listener. You just need to decide what you want your controllers to return.

if ($form->isValid()) {
    return new Something($redirectUrl, $ajaxData);
}

And in your listener:

public function onKernelView($event)
{
    $request = $event->getRequest();
    $result = $event->getControllerResult();

    if ($result instanceof Something) {
        if ($request->isXmlHttpRequest()) {
            $event->setResponse(new Response(json_encode($result->getAjaxData())));
        } else {
            $event->setResponse(new RedirectResponse($result->getRedirectUrl()));
        }
    }
}
Saturday, May 29, 2021
 
madphp
answered 7 Months ago
24

The form is submitting after the ajax request.

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'post.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form>
      <input name="time" value="00:00:00.00"><br>
      <input name="date" value="0000-00-00"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>
Tuesday, June 1, 2021
 
OMGKurtNilsen
answered 7 Months ago
43

can you try $.post instead of $.ajax

$.post(url, {argument_name: value, ...} , function(data){

// callback function..

}, 'json'}
Tuesday, August 31, 2021
 
Mateusz Pryczkowski
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share