Home > Blockchain >  Send PHP Variable with Ajax Call
Send PHP Variable with Ajax Call

Time:09-26

I wrote a PHP application that makes an AJAX call (XMLHttpRequest) and is called every 5 seconds. The page called makes a database query. However, I need a variable from the main page and am unable to find a solution to attach it to the Ajax call.

Using $_GET seems a bit too insecure to me. Is there another way here?

This is my first expierence with ajax so please dont be to hard with me :)

Here is my Ajax Call


    const interval = setInterval(function() {
    loadText() }, 5000);

    function loadText(){
    
        //XHR Objekt
        var xhr = new XMLHttpRequest();

        // OPEN
        xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.'&name='.$_SESSION['name'].'&org='.$_SESSION['org'];?>', true);
        xhr.onload = function() {
            if(this.status == 200){

                document.getElementById('table_view_div').innerHTML = this.responseText;            }
       
                })


            if(this.status == 404){
                document.getElementById('apps').innerHTML = 'ERROR';
            }
        }

        xhr.send();

        // console.log(xhr);
    }

Ill hope i provided enough Information

WIsh u all a great weekend

CodePudding user response:

You do not need sending session variables at all: those are already known to the called page, because it can share the session information of the calling page.

// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?= $role ?>'

is enough, provided that "table_view.php" issues a session_start() command.

CodePudding user response:

I have fixed your code; It's here:

(Note: \' means that the character ' doesn't closing the string.)

const myInterval = setInterval(function(){loadText();}, 5000);

function loadText(){
  //XHR Objekt
  var xhr = new XMLHttpRequest();

  // OPEN
  xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.\'&name=\'.$_SESSION[\'name\'].\'&org=\'.$_SESSION[\'org\']; ?>', true);
  xhr.onload = function(){
    if(this.status == 200){
      document.getElementById('table_view_div').innerHTML = this.responseText;
    }
    if(this.status == 404){
      document.getElementById('apps').innerHTML = 'ERROR';
    }
  }
  xhr.send();
}
  • Related