1

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?

2 Answers 2

4

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

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

            ...your code...    

            return false;
    });
Sign up to request clarification or add additional context in comments.

Comments

3

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();
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.