June 29, 2013

Ajax response error

TNK’s Question:

I need to make a mysql query according to the value of dropdown list. Here I use ajax to send dropdown value to the server. I think this part is working for me. But problem is I can not get it to php. Note: both are in the same page.

This is my Jquery code :

$('#filter-value').change(function(){
    var filterValue = $(this).val();
    //console.log(filterValue); 

    $.ajax({
        type: 'post',
        dataType: 'html',
        data: {filter: filterValue},
        success:function(data){ 
            alert(data); 
        }, 
        error:function (xhr, ajaxOptions, thrownError){
            //On error, we alert user
            alert(thrownError);
        }, 
        complete: function(){
            //alert('update success'); 
        }
    });
});

This is HTML form

    <form method="post" action="">
        <select id="filter-value" name="filter">
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>              
        </select>
    </form>

This is my PHP code that I am trying on the top of the page :

if (isset($_POST['filter'])) {
    $filter = $_POST['filter']; 
    echo $filter; 
    exit;
} else {
    echo 'bad';
}

But this php code is always going to else part and print ‘bad’

Can anybody tell me where I am going wrong?

Thank you.

You have missed to specify the URL of the script. Be ensure that you are querying the correct file from the AJAX.

$.ajax({
    type: 'post',
    url: 'yourpage.php', // This one 
    //.....
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!