Q:

why AJAX redirects to the new page in PHP

I have a form:
<form class="searchForm">
            <div class="box_style_1">
                <h4><?= Yii::t("common", "Age"); ?></h4>
                <?
                echo '<b class="badge">3</b> ' . Slider::widget([
                        'name'=>'age',
                        'value'=>'250,650',
                        'sliderColor'=>Slider::TYPE_GREY,
                        'pluginOptions'=>[
                            'min'=>3,
                            'max'=>21,
                            'step'=>1,
                            'range'=>true
                        ],
                    ]) . ' <b class="badge">21</b>';
                ?>
                <br /><br />
                <input type="submit" value="Search" class="searchByAge"/>
                <br /><br />
            </div>
            </form>

And want to show the result in console.log:
$('.searchByAge').on('click', function(e){
e.preventDefault();

var range = $('.form-control').val();
var min = range.split(',')[0];
var max = range.split(',')[1];

//alert(min+' '+max);

$.ajax({
    type: 'POST',
    url: '/age/'+min+'/'+max,
    data: $('.searchForm').serialize(),
    success: function (data) {
        console.log(data);
    },
    error: function(jqXHR, textStatus, errorMessage) {
        console.log(errorMessage); // Optional
    }
});
})

and that's my AJAX code. But when I click on Search button it redirects me to the new page and nothing in the console log. I do not know what is wrong in my code.
I return a JSON from the '/age/min_age/max_age' page, but the result shows in the new page.
How can I fix this problem?

A:

change code to below. change input type submit to button
<input type="button" value="Search" class="searchByAge"/>

also wrap your code in $(document).ready(); 

Make sure to  add jQuery library from correct path.

 $(document).ready(function(){

     $('.searchByAge').on('click', function(e){
        e.preventDefault();

        var range = $('.form-control').val();
        var min = range.split(',')[0];
        var max = range.split(',')[1];

          //alert(min+' '+max);

        $.ajax({
          type: 'POST',
          url: '/age/'+min+'/'+max,
          data: $('.searchForm').serialize(),
          success: function (data) {
           console.log(data);
          },
          error: function(jqXHR, textStatus, errorMessage) {
            console.log(errorMessage); // Optional
          }
      });
     });  
 });

