0

I'm trying to access variable in php file sent from AJAX. I tried $_POST['category_id'] as shown below but with no luck. category_id variable is set to some value, I checked that already. I think the problem may be in datatype JSON but I'm not sure.

    if( optimizedDatabaseLoading == 1 ){
        google.maps.event.addListener(map, 'idle', function(){
            if( searchClicked != 1 ){
                var ajaxData = {
                    optimized_loading: 1,
                    north_east_lat: map.getBounds().getNorthEast().lat(),
                    north_east_lng: map.getBounds().getNorthEast().lng(),
                    south_west_lat: map.getBounds().getSouthWest().lat(),
                    south_west_lng: map.getBounds().getSouthWest().lng(),
                };
                if( markerCluster != undefined ){
                    markerCluster.clearMarkers();
                }
                loadData(category_id, "assets/external/data.php", ajaxData);
            }
        });
    }
    else {
        google.maps.event.addListenerOnce(map, 'idle', function(){
            loadData(category_id, "assets/external/data.php");
        });
    }

    function loadData(category_id, url, ajaxData){
        console.log('inside:', category_id);
        $.ajax({
            url: url,
            dataType: "json",
            method: "POST",
            data: ajaxData, category_id: category_id,
            cache: false,
            success: function(results){
                for( var i=0; i <newMarkers.length; i++ ){
                    newMarkers[i].setMap(null);
                }
                allMarkers = results;
                placeMarkers(results);
            },
            error : function (e) {
                console.log(e);
            }
        });
    }

data.php

if (!isset($_POST['category_id'])) {
    if (!empty($_POST["optimized_loading"])) {
        $queryData = mysqli_query($connection, "SELECT id, title, latitude, longitude, address, marker_image FROM items WHERE latitude <= " . $_POST["north_east_lat"] . " AND latitude >= " . $_POST["south_west_lat"] . " AND longitude <=" . $_POST["north_east_lng"] . " AND longitude >= " . $_POST["south_west_lng"]);
    } else {
        $queryData = mysqli_query($connection, "SELECT id, title, latitude, longitude, address, marker_image FROM items");
    }
}
else {
    if( !empty( $_POST["optimized_loading"] ) ){
        $queryData = mysqli_query( $connection, "SELECT id, title, latitude, longitude, address, marker_image FROM items WHERE latitude <= " . $_POST["north_east_lat"] . " AND latitude >= " . $_POST["south_west_lat"] . " AND longitude <=" . $_POST["north_east_lng"] . " AND longitude >= " .$_POST["south_west_lng"] . " AND items.item_category_id = " . json_decode($_POST['category_id']));
    }
    else {
        $queryData = mysqli_query( $connection, "SELECT id, title, latitude, longitude, address, marker_image FROM items WHERE items.item_category_id = 1" . json_decode($_POST['category_id']) );
    }
}
Go Go
  • 37
  • 1
  • 7
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky Jun 09 '17 at 14:02

1 Answers1

1

The data you're sending is not what you think it is, you're setting category_id as a property of the object passed to $.ajax not the data being sent.

You could extend the object and add the property

$.ajax({
    url      : url,
    dataType : "json",
    method   : "POST",
    data     : $.extend(ajaxData, {category_id: category_id}),
    success  : function(results){
        for( var i=0; i <newMarkers.length; i++ ){
            newMarkers[i].setMap(null);
        }
        allMarkers = results;
        placeMarkers(results);
    },
    error   : function (e) {
        console.log(e);
    }
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Now how can I access the variable in PHP? $_POST['category_id'] is still being set to null? – Go Go Jun 10 '17 at 09:12
  • Where is `category_id` coming from in your javascript, it's not defined in the posted code ? – adeneo Jun 10 '17 at 09:53
  • console.log('inside:', category_id) outputs 2 for example. It is a parameter from the outer function. – Go Go Jun 10 '17 at 10:57
  • If you just remove `dataType : 'json'` and in the PHP just do `print_r( $_POST );` you can see the returned post data in the success function with `console.log(results)` etc. – adeneo Jun 10 '17 at 13:54