tags:

views:

113

answers:

2

Hello,

I have an input box which i use to add items to a table in the db.

It looks like this:

<td>
  <form class="insCat" action="#" name="insertCat">
    <input name="categorienaam" type="text"> 
    <input class="insert" type="submit" value="nieuwe categorie">
  </form>
</td>

And i handle it like this in jquery

jQuery(".insert").click(function(){

  str = jQuery("form.insCat").serialize();
  console.log(str);

  jQuery.ajax({
    type: "POST",
    data: str + "&cmd=insert",
    url: "ajax_handler.php",
    success: function(msg){}
  });

  jQuery("div.result").empty();

});

But i can't see anything in my log since the page is refreshed after each insert. Which i don't want.

Are there ways around this?

+4  A: 

You need to prevent the default event of the submit button:

    jQuery(".insert").click(function(e){
            e.preventDefault();

            ...your code...    

            return false;
    });
ToRrEs
+3  A: 

You are attaching the event handler to the submit button, and not stopping the execution of the default event. So the JS runs and then the form is submitted as normal.

First, set a more sensible action than "#" (a link to the top of the page) if the form gets submitted without JS.

Next, attach the event to the form, not the button. That way if it gets submitted through other means (such as the enter key being pressed on the text input) it will still work.

jQuery("form.insCat").bind("submit", yourFunction);

Then, edit your function so that it stops the default event action.

var yourFunction = function(event){
  // do whatever you like then...
  event.preventDefault();
};
David Dorward