Shirantha
Shirantha

Reputation: 71

Page Reloaded afer ajax query is made

I have a small jquery script which runs an ajax call from wordpress plugin option page to add some data to database. the ajax call works & the data can be inserted to the database as required.

But the issue, which I have is, once the data is inserted, and the success message is displayed. the page reloads auto matically. how can i stop page reloading.

given below is the code which i use .

jQuery(document).ready(function(){

    jQuery("#holiday-submit").click(function(){
        var date = jQuery("#holiday").val();
       var reason =jQuery("#holiday-reason").val();
        jQuery.ajax({
            type: 'POST',
            url: MyAjax.ajaxurl,
            data: {"action": "add_holiday", "holiday":date, "reason" :reason},
            success: 
            function(){
                jQuery("#holiday-status").html( date);
            }
        });
    });
});

This is what I have on the relevant admin page

<form action="" method="post">

            <input type="date" id="holiday" name="holiday">
            <input type="text" id="holiday-reason" placeholder="Holiday reason">
            <input type="submit" id="holiday-submit">
        </form>
<div id="holiday-status">

</div>

Can someone point me to the right direction please ?

Upvotes: 0

Views: 29

Answers (2)

Black Mamba
Black Mamba

Reputation: 15555

Just use type="button" instead of type="submit". So your:

<input type="submit" id="holiday-submit">

Becomes:

<input type="button" id="holiday-submit" value="submit">

Or

<button id="holiday-submit">Submit</button>

Or use e.preventDefault() as suggested in other answer

Upvotes: 1

yasaryousuf
yasaryousuf

Reputation: 89

change to this

  jQuery(document).ready(function(){
        jQuery("#holiday-submit").click(function(event){
        event.preventDefault();
            var date = jQuery("#holiday").val();
           var reason =jQuery("#holiday-reason").val();
            jQuery.ajax({
                type: 'POST',
                url: MyAjax.ajaxurl,
                data: {"action": "add_holiday", "holiday":date, "reason" :reason},
                success: 
                function(){
                    jQuery("#holiday-status").html( date);
                }
            });
        });
    });

Upvotes: 0

Related Questions