user2076828 user2076828 - 4 months ago 6
Javascript Question

How do you use twitter bootstrap button with jquery?

What I want to do is when a user clicks on the submit button in a forum, it should send the data collected to the php script and ideally, stay on the same page. Currently, I have in the form(I have other tags in the form but these are the two things I need to focus on)

<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>


As you can see, I use a form that sends the data to sqlinserter.php when the user clicks the submit button. Basic form stuff. Right now, when it clicks submit it goes to the actual sqlinsert.php page which is blank because it is just sending data to the database.

However, I would like to create a simple jquery script where you click the button it sends the data using ajax. I have been noticing that twitter bootstrap works differently with buttons and I am not sure how to use their buttons with jquery. Any help with this would be great.

So,


  1. I need to figure out how to use twitter bootstrap buttons with
    jquery. Specifically, I need to figure out how to use the submit
    button.

  2. How to send data using ajax?


Answer

how to use jquery in bootstrap is same as always. you just need to add click event to the submit button, then put the ajax request inside the event. example:

<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
    <button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
</form>

<script>
    $(function(){
        $('#newThread').on('click', function(e){
            e.preventDefault(); // prevent the default form submit action

            var $form = $('#replyForm');

            $.ajax({
                url: $form.attr("action"),
                type: $form.attr("method"),
                data: $form.serialize(),
                success: function (response) {
                    alert('response received');
                    // ajax success callback
                },
                error: function (response) {
                    alert('ajax failed');
                    // ajax error callback
                },
            });
        });
    });
</script>