artlemaks
artlemaks

Reputation: 147

jQuery AJAX not sending variables to PHP page - no error

I have an AJAX that runs when any of my dropdowns are changed in order to refresh data in datatables. I have this function

$("select").on('change', function() {
    //get values for all checkboxes (different IDs!)
    var location_city = document.getElementsByName("city_filter")[0].value;
    var location_county = document.getElementsByName("county_filter")[0].value;
    var location_region = document.getElementsByName("region_filter")[0].value;
    var location_country = document.getElementsByName("country_filter")[0].value;

    $.ajax({
        url: "load_group_stores.php",
        data: {
            'action': 'reload_table',
            'location_city': location_city,
            'location_county': location_county,
            'location_region': location_region,
            'location_country': location_country
        },
        type: 'post',
        success: function(result) {},
        error: function() {}
    });

});

and inside load_group_stores.php I try to fetch the variables in the usual way

$action = $_GET['action'];
$location_city = $_GET['location_city'];
$location_county = $_GET['location_county'];
$location_region = $_GET['location_region'];
$location_country = $_GET['location_country'];

but the results are empty. I even tried to echo the $_GET by itself

echo 'city: ' . $_GET['location_city'];

and just got a blank line. I honestly can't see what I am missing as I have multiple AJAX requests all over my site and they all work fine.

Upvotes: 0

Views: 223

Answers (3)

Sathish Kumar D
Sathish Kumar D

Reputation: 274

php code having checking for array of get method. you are calling the file via post method. in get method you can user variable $_GET or $_REQUEST.

$action = $_POST['action'];
$location_city = $_POST['location_city'];
$location_county = $_POST['location_county'];
$location_region = $_POST['location_region'];
$location_country = $_POST['location_country'];
echo 'city: ' . $_POST['location_city'];

it will print the city

otherwise please change the method in ajax call as get and use the same php code

Upvotes: 0

Elisha Senoo
Elisha Senoo

Reputation: 3594

You need to be consistent. Since you are sending a post request, you have to retrieve the data from the $_POST variable:

$action = $_POST['action'];
$location_city = $_POST['location_city'];
$location_county = $_POST['location_county'];
$location_region = $_POST['location_region'];
$location_country = $_POST['location_country'];

Upvotes: 1

NibyNool
NibyNool

Reputation: 81

It looks like you're using POST to send the data, but you're only looking for query parameters in your PHP code.

I'd suggest changing $_GET (only look in the query string) to $_REQUEST (look int he query string OR post data) or $_POST (only look in post data).

Upvotes: 1

Related Questions