title: Stay on same page after a form submit using ajax
body: <p>I am doing a post upload using ajax, but as I make a call to addPost.php it dose not return back and show result on same page it redirects to addPost.php and shows the result on that page.</p>
  
  <p>As I tried alert in success method of ajax still it redirects to the another page. </p>
  
  <p>Why is this happening so? For my other function like getCategories it returns the data well. What can be the problem in this?</p>
  
  <p>I want to upload a file with this form,and data as well.</p>
  
  <pre><code>    &lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
  &lt;head&gt;
      &lt;meta charset="UTF-8"&gt;
      &lt;title&gt;Post&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;form class="postForm" id="postForm" method="post" action="addPost.php" enctype="multipart/form-data"&gt;
  
      &lt;fieldset&gt;
          &lt;legend&gt;Please add the details below &lt;/legend&gt;
          &lt;p&gt;
              &lt;label for="title"&gt;Title (required, at least 2 characters)&lt;/label&gt;
              &lt;input id="title" name="title" minlength="2" type="text" required&gt;
          &lt;/p&gt;
  
          &lt;p&gt;
              &lt;label for="desc"&gt;Description (required, at least 2 characters)&lt;/label&gt;
              &lt;input id="desc" name="desc" minlength="2" type="text" required&gt;
          &lt;/p&gt;
          &lt;p&gt;
              &lt;label for="keywords"&gt;Keywords (eg:#facebook)(required, at least 2 characters)&lt;/label&gt;
              &lt;input id="keywords" name="keywords" minlength="2" type="text" required&gt;
          &lt;/p&gt;
  
          &lt;select id="types" name="types" onchange="myFunction(this)"&gt;
  
              &lt;option value=""&gt;Select type&lt;/option&gt;
  
              &lt;option value="2"&gt;Add Link&lt;/option&gt;
              &lt;option value="0"&gt;Upload Image&lt;/option&gt;
              &lt;option value="1"&gt;Upload Video&lt;/option&gt;
  
          &lt;/select&gt;&lt;br&gt;&lt;br&gt;
  
          &lt;div id="link" style="display: none"&gt;
  
          &lt;p&gt;
              &lt;label for="url"&gt;URL (required)&lt;/label&gt;
              &lt;input id="url" type="url" name="url" required&gt;
          &lt;/p&gt;
  
          &lt;p&gt;
              &lt;label for="urlType"&gt;Select Url Type :(required)&lt;/label&gt;
              &lt;select name="urlType" id="urlType"&gt;
                  &lt;option value=""&gt;Select Url Type...&lt;/option&gt;
          &lt;!--        &lt;option value="0"&gt;Server Image&lt;/option&gt;
                  &lt;option value="1"&gt;Server Video&lt;/option&gt;--&gt;
                  &lt;option value="2"&gt;YouTube Video&lt;/option&gt;
                  &lt;option value="3"&gt;Vimeo Video&lt;/option&gt;
                  &lt;option value="4"&gt;Facebook Image&lt;/option&gt;
                  &lt;option value="5"&gt;Facebook Video&lt;/option&gt;
                  &lt;option value="6"&gt;Instagram Image&lt;/option&gt;
                  &lt;option value="7"&gt;Instagram Video&lt;/option&gt;
                  &lt;option value="-1"&gt;Other&lt;/option&gt;
              &lt;/select&gt;
          &lt;/p&gt;
  
          &lt;/div&gt;
  
          &lt;div id="filediv" style="display: none"&gt;
  
              Select file to upload:
              &lt;br&gt;&lt;br&gt;
              &lt;input name="file1" type="file" id="fileToUpload"&gt;&lt;br&gt;&lt;br&gt;
  
          &lt;/div&gt;
  
  
          &lt;p&gt;
              &lt;label for="postType"&gt; Select Post Type :(required)&lt;/label&gt;
              &lt;select name="postType" id="postType"&gt;
                  &lt;option value=""&gt;Select Post Type...&lt;/option&gt;
                  &lt;option value="0"&gt;Normal&lt;/option&gt;
                  &lt;option value="1"&gt;Featured&lt;/option&gt;
                  &lt;option value="2"&gt;Sponsored&lt;/option&gt;
              &lt;/select&gt;
          &lt;/p&gt;
          &lt;p&gt;
              &lt;label for="category"&gt; Select Category :(required)&lt;/label&gt;
              &lt;select name="category" id="category"&gt;
                  &lt;option value=""&gt;Select Category...&lt;/option&gt;
              &lt;/select&gt;
          &lt;/p&gt;
          &lt;p&gt;
              &lt;input type="hidden" name="action_type" id="action_type_id"/&gt;
              &lt;input type="hidden" name="id" id="p_id"/&gt;
  &lt;!--            &lt;a href="javascript:void(0);" class="btn btn-warning" onclick="$('#postForm').slideUp();"&gt;Cancel&lt;/a&gt;
              &lt;a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')"&gt;Add User&lt;/a&gt;--&gt;
             &lt;input type="submit" name="submit" id="submit" value="Submit"&gt;
          &lt;/p&gt;
      &lt;/fieldset&gt;
  
      &lt;div class="result" id="result"&gt;&lt;/div&gt;
  
  
  &lt;/form&gt;
  
  &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"&gt;&lt;/script&gt;
  &lt;script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"&gt;&lt;/script&gt;
  
  &lt;script&gt;
      window.onerror = function(error, url, line) {
          controller.sendLog({acc:'error', data:'ERR:'+error+' URL:'+url+' L:'+line});
      };
  
      $(document).ready(function(){
          getCategories();
  /*
  
          $("#postForm").submit(function(e){
              e.preventDefault();
          });
  */
  
          $('#postForm').validate({ // initialize the plugin
              rules: {
                  title: {
                      required: true,
                      minlength : 2
                  },
                  url: {
                      required: true
                  },
                  desc: {
                      required : true,
                      minlength : 2
                  },
                  keywords : {
                      required : true,
                      minlength : 2
                  },
                  urlType :
                      {
                          required : true
                      },
                  postType :
                      {
                          required : true
                      },
                  category :
                      {
                          required : true
                      },
                  file1 :
                      {
                          required : true
                      }
              },
              submitHandler: function (form) {
  
  
                  var url = document.getElementById('urlType').value;
  
                  if(validate_url(document.getElementById('url').value) == 'facebook' &amp;&amp; url == 6)
                  {
                      alert('Please enter valid facebook image,video url or select valid url type.');
                  }
                  else if(validate_url(document.getElementById('url').value) == 'facebook' &amp;&amp; url == 7)
                  {
                      alert('Please enter valid facebook image,video url or select valid url type.');
                  }
                  else if(validate_url(document.getElementById('url').value) == 'facebook' &amp;&amp; url == 3)
                  {
                      alert('Please enter valid facebook image,video url or select valid url type.');
                  }
                  else if(validate_url(document.getElementById('url').value) == 'facebook' &amp;&amp; url == 2)
                  {
                      alert('Please enter valid facebook image,video url or select valid url type.');
                  }
                  else if(validate_url(document.getElementById('url').value) == 'instagram' &amp;&amp; url == 3)
                  {
                      alert('Please enter valid instagram image,video url or select valid url type.');
                  }
                  else if(validate_url(document.getElementById('url').value) == 'instagram' &amp;&amp; url == 2)
                  {
                      alert('Please enter valid instagram image,video url or select valid url type.');
                  }
                  else if(validate_url(document.getElementById('url').value) == 'instagram' &amp;&amp; url == 4)
                  {
                      alert('Please enter valid instagram image,video url or select valid url type.');
                  }
                  else if(validate_url(document.getElementById('url').value) == 'instagram' &amp;&amp; url == 5)
                  {
                      alert('Please enter valid instagram image,video url or select valid url type.');
                  }
                  else if(validate_url(document.getElementById('url').value) == 'vimeo' &amp;&amp; url != 3)
                  {
                      alert('Please enter valid vimeo video url or select valid url type.');
                  }
                  else if(validate_url(document.getElementById('url').value) == 'youtube' &amp;&amp; url != 2)
                  {
                      alert('Please enter valid youtube video url or select valid url type.');
                  }
                  else {
  
  
                      userAction('add');
  
                    /*  var data = new FormData();
                      jQuery.each(jQuery('#file')[0].files, function(i, file) {
                          data.append('file-'+i, file);
                      });
  
                      $.ajax({
                          type: "POST",
                          url: 'addPost.php',
                          dataType: 'text',
                          data: $('#postForm').serialize(),
                          async: false,
                          cache: false,
                          success: function (result) {
                              //alert(report);
                              $(".result").html(report);
                              $("#postForm").trigger('reset');
                          }
                      });
  */
  
                      /*             jQuery.ajax({
                                       url: 'addPost.php',
                                      // data: data,
                                       data: $('#postForm').serialize(),
                                       cache: false,
                                       contentType: false,
                                       processData: false,
                                       encctype: "multipart/form-data",
                                       type: 'POST',
                                       success: function(report){
                                           alert(report);
                                          // $(".result").html(report);
                                           $("#postForm").trigger('reset');
                                       }
                                   });*/
                   //   e.preventDefault();
                  }
              }
          });
  
      });
  
      function getCategories() {
  
          $.ajax({
              type: "POST",
              url: 'getCategories.php',
              dataType: 'text',
              async: false,
              cache: false,
              success: function (result) {
  
                  $('#category').html(result);
              }
          });
  
      }
  
  
      function userAction(type,id){
  
      /*    var statusArr = {add:"added",edit:"updated",delete:"deleted"};
  
  */
          var form = $('#fileUploadForm')[0];
  
          // Create an FormData object
          var data = new FormData(form);
  
          if (type == 'add') {
  
              $('#action_type_id').val(type);
              $('#p_id').val(id);
          }
  
          $.ajax({
              type: 'POST',
              url: 'addPost.php',
              enctype: 'multipart/form-data',
           //   data : data,
           //   data: $(this).serialize(),
              data: $('#postForm').serialize(),
              cache: false,
              success:function(report){
                  // replace data to report
  
              $(".result").html(report);
              $("#postForm").trigger('reset');
              }
          });
       //   e.preventDefault();
  
  /*
      $("form#data").submit(function(){
  
          var formData = new FormData($(this)[0]);
  
          $.ajax({
              url: 'addPost.php',
              type: 'POST',
              data: formData,
              success: function (data) {
                  $(".result").html(report);
                  $("#postForm").trigger('reset');
              },
              cache: false,
              contentType: false,
              processData: false
          });*/
  
        /*  var data = new FormData();
          jQuery.each(jQuery('#file')[0].files, function(i, file) {
              data.append('file-'+i, file);
          });
  
  
          jQuery.ajax({
              url: 'addPost.php',
              data: data,
              cache: false,
              contentType: false,
              processData: false,
              type: 'POST',
              success: function(report){
                  $(".result").html(report);
                  $("#postForm").trigger('reset');
              }
          });*/
  
      }
  
      function myFunction(obj) {
  
          var type = obj.value;
          var x = document.getElementById('link');
          var y = document.getElementById('filediv');
  
  
          if(type == "2")
          {
              x.style.display = 'block';
              y.style.display = 'none';
          }
          else {
              x.style.display = 'none';
              y.style.display = 'block';
          }
  
      }
  
      function validate_url(url)
      {
          if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
              return 'facebook';
  
          if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
              return 'facebook';
  
          if (/^(https?:\/\/)?((w{3}\.)?)instagram.com\/.*/i.test(url))
              return 'instagram';
  
          if (/^(https?:\/\/)?((w{3}\.)?)vimeo.com\/.*/i.test(url))
              return 'vimeo';
  
          if (/^(https?:\/\/)?((w{3}\.)?)youtube.com\/.*/i.test(url))
              return 'youtube';
  
          return 'unknown';
      }
  
  &lt;/script&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>EDIT :</p>
  
  <pre><code>   else {
                 // userAction('add');
  
                  var data = new FormData();
                  jQuery.each(jQuery('#file')[0].files, function(i, file) {
                      data.append('file-'+i, file);
                  });
                  e.preventDefault();
  
                  jQuery.ajax({
                      url: 'addPost.php',
                     // data: data,
                      data: $('#postForm').serialize(),
                      cache: false,
                      contentType: false,
                      processData: false,
                      encctype: "multipart/form-data",
                      type: 'POST',
                      success: function(report){
                          alert(report);
                         // $(".result").html(report);
                          $("#postForm").trigger('reset');
                      }
                  });
               //   e.preventDefault();
              }
  </code></pre>
  
  <p>Tried like this still it redirects to the next page.</p>
  
  <p>addPost.php</p>
  
  <pre><code>    &lt;?php
  
  include 'Database.php';
  ini_set('display_errors', 1);
  error_reporting(1);
  ini_set('error_reporting', E_ALL);
  ini_set('post_max_size', '1.8G');
  ini_set('upload_max_filesize', '1.8G');
  
  
  if(isset($_POST['submit']))
  {
  
           $database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
          $dbConnection = $database-&gt;getDB();
          $dbConnection-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  
          $stmt = $dbConnection-&gt;prepare("insert into keywords(keyword) 
                                      values(?)");
          $stmt-&gt;execute(array($_POST['keywords']));
  
          $file_result = "";
  
          if(strcmp($_POST['types'],"2") == 0)
          {
  
              //insert data into posts table
              $stmt = $dbConnection-&gt;prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type) 
                                      values(?,?,?,?,?,?,?)");
              $stmt-&gt;execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'],$_POST['postType']));
  
              $count = $stmt-&gt;rowCount();
  
              if ($count &gt; 0) {
  
                  echo "Post submitted.";
              } else {
  
                  echo "Could not submit post.";
              }
  
  
          }
        else {
  
                  if (isset($_FILES["file1"]["name"])) {
  
                      $file_result = "";
  
                      if ($_FILES["file1"]["error"] &gt; 0) {
                          $file_result .= "No file uploaded or invalid file.";
                          $file_result .= "Error code : " . $_FILES["file1"]["error"] . "&lt;br&gt;";
                      } else {
  
                          if (strcmp($_POST['types'], "0") == 0) {
                            //  $target_dir = "./agtvapp/images/";
                              $target_dir = "images/";
                          } else {
                             // $target_dir = "./agtvapp/videos/";
                              $target_dir = "videos/";
                          }
  
                          $newfilename = preg_replace('/\s+/', '',
                              $_FILES["file1"]["name"]);
                          $target_file = $target_dir . basename($newfilename);
  
                       /*   $target_file = $target_dir . basename($_FILES["file1"]["name"]);*/
  
                          $file_result .=
                              "Upload " . $_FILES["file1"]["name"] . "&lt;br&gt;" .
                              "type " . $_FILES["file1"]["type"] . "&lt;br&gt;" .
                              "temp file " . $_FILES["file1"]["tmp_name"] . "&lt;br&gt;";
  
                          if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file)) {
  
                              $stmt = $dbConnection-&gt;prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type) 
                                      values(?,?,?,?,?,?,?)");
                              $stmt-&gt;execute(array($_POST['category'], $_POST['title'], $newfilename, $_POST['types'], $_POST['desc'], $_POST['keywords'], $_POST['postType']));
  
                              $count = $stmt-&gt;rowCount();
  
                              if ($count &gt; 0) {
  
                                  echo "The file " . basename($_FILES['file1']['name']) . " has been uploaded, and post submitted.";
  
                              } else {
  
                                  echo "Could not submit post.";
                              }
  
                          }
                      }
  
                  }
                  else{
  
                      echo 'empty file';
                  }
              }
  
  }
  ?&gt;
  </code></pre>
  
  <p>Here I dont understand, if I write       data: $('#postForm').serialize(), to send the form in userAction function for ajax then I get the $_FILES array as empty, but the same code if I am doing directly in else part of validate function then the files array is not empty the file gets uploaded successfully but it redirects to next page. And From userAction function it dose not redirect to next page but I get $_FILES array empty so  can not upload the file.</p>
  
  <p>Please, can anyone help with this? I am a beginner in web development so not getting hoe to do this. Thank you.</p>