Home > Blockchain >  Can't Submit Form Using Jquery
Can't Submit Form Using Jquery

Time:12-01

I need to know that what is the error in my code because everything is correct but form data could not be submitted and in php file the error popups that undefined index lname while submiting the form that means form is submitting through jquery but data is not going in backend. so please resolve this error or help me find out what the error is in code.

this is the html code:-

<span id="answer"></span>
            <form id='contact_form' method="post">
                <div >
                    <div id='name_error' class='error'>Please enter your name.</div>
                    <div>
                        <input type='text' name='lname' id='name'  placeholder="Your Name" required>
                    </div>

                    <div id='email_error' class='error'>Please enter your valid E-mail ID.</div>
                    <div>
                        <input type='email' name='email' id='email'  placeholder="Your Email" required>
                    </div>

                    <div id='phone_error' class='error'>Please enter your phone number.</div>
                    <div>
                        <input type='text' name='phone' id='phone'  placeholder="Your Phone" required>
                    </div>
                </div>
                <div >
                    <button type="button"  data-bs-dismiss="modal">Close</button>
                    <button type="submit" onclick="formSubmit(event);" >I Agree</button>
                </div>
            </form>

This is the jquery code:-

$('#subButton').click(function(e) {
        console.log('in');
        e.preventDefault();
        var FormData = $('#contact-form').submit();
        $.ajax({
            type: "POST",
            url: "admin/backend/leads.php",
            data: FormData,
            dataType: "json",
            success: function(data) {
                var html = '';
                if (data.errors) {
                    html = '<div >'   data.errors   '</div>';
                }
                if (data.success) {
                    html = '<div >'   data.success   '</div>';
                    $('#contact-form')[0].reset();
                    localStorage.setItem('#phone', true);
                }
                $('#answer').html(html);
            },
            error: function(data) {
                html = '<div >'   data.errors   '</div>';
                $('#answer').html(html);
            }
        });
    });

CodePudding user response:

Problems in your code are...

  1. There is no element with id="subButton"
  2. There is no formSubmit function
  3. $('#contact-form').submit() submits the form normally which you don't want. It also returns a jQuery object, not the form data.

First, remove the onClick from your submit button.

<button type="submit" >I Agree</button>

Second, either add id="subButton" to your <button> or, as is my preference, listen to the submit event on the form instead.

Third, use jQuery's .serialize() to capture all the form data

$("#contact_form").on("submit", (e) => {
  e.preventDefault();
  const postData = $(e.target).serialize();

  $.post("admin/backend/leads.php", postData, null, "json")
    .done((data) => {
      // make HTML changes, etc
    })
    .fail((_, textStatus, errorThrown) => {
      // report error, etc
    });
});

It's 2022 and you might not need jQuery

document
  .getElementById("contact_form")
  .addEventListener("submit", async (e) => {
    e.preventDefault();
    const body = new URLSearchParams(new FormData(e.target));
    try {
      const res = await fetch("admin/backend/leads.php", {
        method: "POST",
        body,
      });
      if (!res.ok) {
        throw res;
      }
      const data = await res.json();
      // make HTML changes, etc
    } catch (err) {
      // report error, etc
    }
  });

CodePudding user response:

Try this,

$('#contact-form').submit(function(e) {
        console.log('in');
        e.preventDefault();
        var body = $(this).serialize();
        $.ajax({
            type: "POST",
            url: "admin/backend/leads.php",
            data: JSON.stringify(body),
            dataType: "json",
            success: function(data) {
                var html = '';
                if (data.errors) {
                    html = '<div >'   data.errors   '</div>';
                }
                if (data.success) {
                    html = '<div >'   data.success   '</div>';
                    $('#contact-form')[0].reset();
                    localStorage.setItem('#phone', true);
                }
                $('#answer').html(html);
            },
            error: function(data) {
                html = '<div >'   data.errors   '</div>';
                $('#answer').html(html);
            }
        });
    });
  • Related