skip to Main Content

I have an html page with a search field that can have a name typed in which returns a table of Names and IDs (from Steam, specifically). The leftmost column, the names, are hyperlinks that I want to, when clicked, take the user to said player’s profile (profile.php) and I want to send the "name" and "steamid" to that profile.php when the name link is clicked, so essentially sending two JS variables from one page to the PHP backend of another page.

I’m new to ajax and it seems that that is the only way to use it, so after researching for a while this is what I’ve come to:

$(document).ready(function() {

        $('#playerList td').click(function(e) {
            if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
                console.log($(this).text());

                var name = $(this).text();
                var steamid = $(this).closest('tr').children('td:nth-child(2)').text();

                $.ajax({
                  url: 'profile.php',
                  method: 'POST',
                  data: {
                        playersSteamID : steamid,
                        playersName : name 
                  },
                  success: function() {
                    console.log('success');
                  },
                  error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest);
                    console.log(textStatus);
                    console.log(errorThrown);
                  }
                })
            }
        });
        
    });

Everything up to the ajax definition works as I want, and I want to send the "name" and "steamid" vars to profile.php, but I don’t think I’m understanding how ajax works. My understanding is that ajax can "post" information (usually a json object from what I’ve seen) to a url, but can also return information from a page? That’s where I’m a bit confused and am wondering if I’m just using it wrong.

As a quick note: playerList is my table’s id.

When I click the hyperlink, it takes me to profile.php, which is what I want, but php’s $_POST[] array seems to be empty/null as I get the "undefined array key" error when trying to access both ‘playersSteamID’ and ‘playersName’. var_dump() returns NULL as well, so I’m wondering if there’s a problem with the way the data{} field is being sent in the ajax. I’m still very new to this so any help would be much appreciated.

Update: How I’m accessing the variables in profile.php

<?php
    echo var_dump($_POST['playersName']);
    echo var_dump($_POST['playersSteamID']);

    if (isset($_POST['playersName'])) {
        console_log("PLAYER_NAME => ".$_POST['playersName']);
    }
    if (isset($_POST['playersSteamID'])) {
        console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
    }
?>

The rest of profile.php is taking those variables and running several sql queries and building a table which work given proper variables, but since the $_POST[] is empty I can’t continue past the above point as the first two lines return null and the conditionals are never true since isset() is false.

2

Answers


  1. A hyperlink may be causing the page navigation, which you dont want.
    Page navigation will make a get request but your endpoint is expecting a post request.
    You can stop the navigation by setting the href to # or by removing the <a> altogether.
    You could also try calling the preventDefault on the event object.

    $(document).ready(function() {
    
            $('#playerList td').click(function(e) {
                e.preventDefault();
                if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
                    console.log($(this).text());
    
                    var name = $(this).text();
                    var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
    
                    $.ajax({
                      url: 'profile.php',
                      method: 'POST',
                      data: {
                            playersSteamID : steamid,
                            playersName : name 
                      },
                      success: function(data) {
                        console.log('success', data);
                      },
                      error: function(XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest);
                        console.log(textStatus);
                        console.log(errorThrown);
                      }
                    })
                }
            });
            
        });
    
    Login or Signup to reply.
  2. The ajax is used to, post or get parameters/info from/to URL without redirecting/refreshing/navigating to a particular page.

    Please note down without redirecting/refreshing/navigating

    In your case you want to send 2 parameters to profile.php and you also want to navigate to it, yes..? but for that you are using Ajax, which is not a right choice.

    Solutions:-

    -> Use normal form submission kinda thing, and post the parameters to profile.php, in this case you will get redirect to profile.php and can expect proper functionality.

    You can use a normal form with a submit button {pretty normal}, or use a custom function to submit form with some further work if need to be done {form validation}.

    you function would look like this…

    $(document).ready(function() {
    
            $('#playerList td').click(function(e) {
                e.preventDefault();
                if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
                    console.log($(this).text());
    
                    var name = $(this).text();
                    var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
                   //Do some other stuffs
                   document.forms['someform'].submit();//submitting the form here
                }
            });
        });
    

    The rest in profile.php remains same.

    -> If you really wanna use ajax do following.

    Ajax are meant for dynamic web designing, pretty useful to grab data from server without refreshing the page.

    You should change the way your response is in profile.php file.

    for eg:-

    <?php
    if(isset($_POST['playersSteamID'])){
       $name = $_POST['playersName'];
       $id = $_POST['playersSteamID'];
       //Do your stuff here db query whatever
       //Here echo out the needed html/json response.
       echo "<h3>".$name."</h3>";
       echo "<h4>".$playersSteamID."</h4>";
    }
    ?>
    

    The response {from: echo} will be available in data of function(data) in ajax success, you can use this data in whatever you want and however you want.

    for eg:-

    success: function(data){
             console.log(data);//for debugging
             $('#mydiv').html(data);//appending the response.
             }
    

    -> Use php sessions and store steamID in sesssion variable, very useful if you have some login functionality in your website.

    $_SESSION['steamID'] = //the steamID here;
    

    This variable can be used anywhere in site use by calling session_start() in the page, you want to use sessions.

    for eg:-

    <a href="profile.php" target="_self"> click here to view your profile </a>
    

    profile.php

    <?php
        session_start();
        $id = $_SESSION['steamID'];
        //echo var_dump($_POST['playersName']);
        //echo var_dump($_POST['playersSteamID']);
    
        /*if (isset($_POST['playersName'])) {
            console_log("PLAYER_NAME => ".$_POST['playersName']);
        }
        if (isset($_POST['playersSteamID'])) {
            console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
        }*/
        echo $id;
        //Do your work here......
    ?>
    

    For any queries comment down.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search