Skip to content
Advertisement

PHP not reading $_GET parameter when sending an AJAX request

I’ve been struggling with this since months, and finally got to the point I need to fix it on my project.

The thing is, I’m sending an ajax request to a php file where I need to read the current $_GET[‘user_id’] value in order to insert a query. But php just won’t read $_GET[‘user_id’] value from the current URL address, like if it doesn’t exist.

This is driving me crazy, since I don’t know any other methods that can achieve the desired result which is following a user account.

Here’s the piece of code, which is meant for explanation purposes only:

// PHP

<?php
require_once "db.php";

$query = "INSERT INTO followers(follower, following) ";
$query .= "VALUE('{$_SESSION['id_user']}','{$_GET['user_id']}' )";
$result = mysqli_query($connect_db, $query);

?>

// AJAX

<script>
    $('.js-follow_user_btn').click(function(){
            follow_unfollow_action();
        });


        function follow_unfollow_action(){

            $.ajax({
                type: 'POST',
                url: 'follow_user.php',
                success: function(data) {
                    alert('done');
                }
            });

        }
</script>

Advertisement

Answer

The PHP $_GET superglobal is populated with data from the query string of the URL requested (regardless of the HTTP method used to make the request).

This is the URL you are using:

url: 'follow_user.php',

There is no query string on it at all.

Possibly you are expecting it to copy the query string from the page hosting the JavaScript. It doesn’t work like that, you need to provide the data explicitly.


A little aside:

You are inserting data into the database. You should be using a POST request for this (and you are) but you should be passing the data in the request body (otherwise you are very likely to accidentally create something that improperly responds to a GET request.

So first things first: Change the PHP to use $_POST instead of $_GET.

While you are editing it, your PHP is dangerously vulnerable to SQL injection attacks. You need to learn how to defend your code from them.


OK, so next you need to get the data from the query string of the current page.

You can read it in JavaScript. This answer explains a few approaches.

Once you have the data, you can put it in the request:

var user_id = (new URL(url_string)).searchParams.get("user_id");
// See the answer linked above to see how this works and for compatibility with old browsers

$.ajax({
    type: 'POST',
    url: 'follow_user.php',
    data: { user_id: user_id },
    success: function(data) {
        alert('done');
    }
});

… remember, this puts it in the request body so you’ll need to read it with $_POST and not $_GET.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement