RonnieT
RonnieT

Reputation: 2203

Using Ajax but page still refreshing

I have the below on a search form but the Ajax portion seems to still refresh the entire page. My search results come back just fine however, I would like it NOT to refresh the page each time.

showLoader() appears before refresh but the results show after refresh.

Do I just have the success pointed in the wrong DIVs? Or is the submit occuring at the wrong time? I'm lost

    $('.em-events-search-form').submit(function(){
        showLoader()
        if( this.search.value=='<?php echo $s_default; ?>'){
            this.search.value = '';
        }           
        if( $('#em-wrapper .em-events-list').length == 1 ){
            $(this).ajaxSubmit({
                url : EM.ajaxurl,
                data : {
                    _wpnonce : '<?php echo wp_create_nonce('search_states'); ?>',
                    return_html : true
                },
                success : function(responseText) {
                    $('#em-wrapper .em-events-list').replaceWith(responseText);
                }
            });
        } 
    });

Upvotes: 1

Views: 2296

Answers (3)

Bankzilla
Bankzilla

Reputation: 2096

Try

$("..em-events-search-form").live('click', function () {
  showLoader()
if( this.search.value=='<?php echo $s_default; ?>'){
    this.search.value = '';
}           
if( $('#em-wrapper .em-events-list').length == 1 ){

    $.ajax({
      type: "POST"
      url: EM.ajaxurl,
      data: {
            _wpnonce : '<?php echo wp_create_nonce('search_states'); ?>',
            return_html : true
        },
      dataType: 'json',
      success: function (response){
         $('#em-wrapper .em-events-list').replaceWith(response._wpnonce);
      }


   })
  }
});

Upvotes: 0

donutdan4114
donutdan4114

Reputation: 1272

May I suggest instead of using submit, use the click event handler on the button?

Also, e.cancel(); may do the trick, but the above statement is fool proof.

Upvotes: 1

Clive
Clive

Reputation: 36965

You need to prevent the default action of the form from executing:

$('.em-events-search-form').submit(function(e){
    showLoader()
    if( this.search.value=='<?php echo $s_default; ?>'){
        this.search.value = '';
    }           
    if( $('#em-wrapper .em-events-list').length == 1 ){
        $(this).ajaxSubmit({
            url : EM.ajaxurl,
            data : {
                _wpnonce : '<?php echo wp_create_nonce('search_states'); ?>',
                return_html : true
            },
            success : function(responseText) {
                $('#em-wrapper .em-events-list').replaceWith(responseText);
            }
        });
        e.preventDefault();
    }
});

The two slight changes are that the e (event) argument is now passed into the function, and once you've set the AJAX call going you prevent the default action from executing.

Upvotes: 3

Related Questions