Tonya
Tonya

Reputation: 278

event.preventdefault() or return false not working (I need to stay on the same page after submit)

I know, there are a lot of questions relating to this theme, and I've checked a lot of them, but I can't figure out, what is wrong with my code. And I don't know what else to try. After submit I go to lang.php, but I need to stay on the same page.

Here is a block for a language change:

      <div id="language">
  <form method="post" action="lang.php" id="langForm">
  <select name="language" onchange="this.form.submit()">
    <option value="en">en</option>
    <option value="ru">ru</option>
  </select>
 </form>
</div>

And here is js:

$(document).ready(function() {
$('form#langForm').submit(function (event) {
          $.ajax({
            type: 'post',
            url: 'lang.php',
            data: $('form#langForm').serialize()                
          });
     event.preventDefault();
     return false;
   });
});

What can be wrong with it?

Upvotes: 0

Views: 106

Answers (1)

Timothy Lee
Timothy Lee

Reputation: 828

Don't use native form submit $('form#langForm').submit

it will redirect your location.

just send ajax by yourself.

Try Something like

<select name="language" onchange="sendAjax">
  <option value="en">en</option>
  <option value="ru">ru</option>
</select>

js :

function sendAjax() {
   $.ajax({
        type: 'post',
        url: 'lang.php',
        data: $('form#langForm').serialize()                
      });
}

Upvotes: 1

Related Questions