skip to Main Content

I have this form

<form action="" method="post" enctype="multipart/form-data" onsubmit="submit()">
<input id="name" class="btn" type="file" name="pic" multiple>
<br/><br/>
<button class="btn btn-primary" type="submit" id="submit" name="submit">UPLOAD</button>
</form>
<br/><br/>

Uploaded file: <a target="blank" href="<?php echo $fileurl;?>"><?php echo $fileurl;?></a>

and I have this script

  <script>
function submit(event) {
    event.preventDefault()
    var http = new XMLHttpRequest();
    http.open("POST", "", true);
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
    http.send(params);
    http.onload = function() {
        alert(http.responseText);
    }
}
</script> 

I want to submit the form without the page reloading but isn’t working for me.

3

Answers


  1. Your function takes event property, on which you can invoke preventDefault()

    function submit(event) {
        event.preventDefault()
        var http = new XMLHttpRequest();
        http.open("POST", "", true);
        http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
        http.send(params);
        http.onload = function() {
            alert(http.responseText);
        }
    }
    
    Login or Signup to reply.
  2. See this check function to stop page reloding

    As you have requested I have given the full code

    function check(event) {
        event.preventDefault();
        console.log("stopped form submit");
    }
    <form onSubmit="check(event)">
    <input id="name" class="btn" type="file" name="pic" multiple>
    <br/><br/>
    <button class="btn btn-primary" type="submit" id="submit" name="submit">UPLOAD</button>
    </form>
    <br/><br/>
    </form>
    Login or Signup to reply.
  3. <script>
          $('#yourFormData').submit(function(e){
            e.preventDefault();
    
          var formData = new FormData($('#yourFormData')[0]);
          url ="your route" ;
          $.ajax({
          url : url,
          type : "post",
          data : formData,
          contentType:false,
          processData:false,
    
          success : function(data)
          {
              // success 
    
    
          },
          error :  function(y)
          {
    
            console.log(error );
           }
          });
    
        })
    

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search