简体   繁体   中英

How to send form data without page refresh?

I have sending my data in ajax using submit button without any page refresh. But the page refreshed.

Please check my code and let me know the problem.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#idForm").submit(function() { alert("hi");

    var url = "ajax.php";
    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(),
           success: function(data) {
               alert(data);
           }
         });

    return false;
});
</script>
<form id="idForm" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

ajax.php

echo "Hello";
//Program a custom submit function for the form
$("form#data").submit(function(event){

  //disable the default form submission
  event.preventDefault();

  //grab all form data  
  var formData = new FormData($(this)[0]);

  $.ajax({
    url: 'formprocessing.php',
    type: 'POST',
    data: formData,
    contentType: false,
    processData: false,
    success: function (returndata) {
      alert(returndata);
    }
  });

  return false;
});

The js already prevents the form submitting

The code in the question already prevents the form from submitting by this line:

return false;

which means: The JavaScript code in the question isn't running at all.

The form doesn't exist yet

The problem here is that when this line of code runs:

$("#idForm")...

that element isn't in the dom yet . As such the submit handler isn't attached to anything - when the form submits it's just a standard HTTP post request.

To just fix the problem in the question - do one of the following

Ensure the element exists before trying to manipulate it

If the script runs after the element appears in the source code - the form does exist:

<form id="idForm">...
<script>
    $("#idForm")...
</script>

Put jquery code in a document ready handler

If the js is in a ready handler:

<script>
    $(function() {
        $("#idForm")...
    });
</script>
<form id="idForm">...

It doesn't matter where the script tag is as the dom has already finished loading when it runs.

Put all js at the end of the page

If javascript is systematically put allat the end of the page:

<body>
    <form id="idForm">...
    ...
    <script src="//ajax.googleapis.c...
    <script>
        $("#idForm")...
    </script>
</body>

That would be following established best practices , avoid such problems, don't need to use ready-handlers in any js code (as the html source is always already in the dom when scripts are parsed that way) and have pages that are perceived to load faster.

use event.preventdefault()

$("#idForm").submit(function(e) { 
e.preventDefault();//use it here to stop default behaviour
   alert("hi"); 
   var url = "ajax.php";
    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(),
           success: function(data) {
               alert(data);
           }
         });

    return false;
});

I think you can use the 'preventDefault' function for this:

<script>
$("#idForm").submit(function(e) { alert("hi");
    e.preventDefault();
    var url = "ajax.php";
    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(),
           success: function(data) {
               alert(data);
           }
         });

    return false;
});
</script>

I have Form and in the form i have table and i am sending by formData on server

 $("#submit").on("click", function() { console.log("this is form table data and sending by formData on server ") var emptab = document.getElementById("tab_body") var tabrows = emptab.getElementsByTagName("tr") var tabinfo = {}; var formdata = new FormData() for (let tr = 0; tr < tabrows.length; tr++) { var tabdata = tabrows[tr].getElementsByTagName("td") tabinfo[tabdata[0].textContent] = tabdata[1].textContent formdata.append(tabdata[0].textContent, tabdata[1].textContent) } console.log("tabinfo", tabinfo) $.ajax({ url: "{{ url_for('genrate_idcard')}}", method: "post", data: formdata, datatype: "json", processData: false, ContentType: 'multipart/form-data', cache: false, error: function(e) { alert("error:", e) } }); // return false; });

jQuery ajax and XHR is quite oldschool, jQuery can not handle unknown object without setting contentType & processData to false

It would be just easier to use the fetch api instead

Also let the html markup define the method & action like it have always done. Don't let javascript define the behavior. Then your function can be used on more places to ajaxify any form and be more generic. Plus that your site would work without JS in case it's turned off. Javascript should be a enhancement

 $('#idForm').on('submit', async function (event) { // disable the default form submission event.preventDefault() // grab all form data var formData = new FormData(this) var res = await fetch(this.action, { method: this.method, body: formData }) var json = await res.json() });
 <form id="idForm" action="{{ url_for('genrate_idcard')}}" method="post" enctype="multipart/form-data"> <input type="text" name="first" value="Bob" /> <input type="text" name="middle" value="James" /> <input type="text" name="last" value="Smith" /> <input name="image" type="file" /> <input type="submit" name="submit" value="Submit" /> </form>

It's better to listen to the sumbit event rather than using a btn.click event since the form can then validate all fields before the submit take actions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM