-2

I am trying to call a php file, which will display a html page, using AJAX from my js. This is my php file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snippet details</title>
</head>
<body>
    <?php
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    
        require "../server_detail.php";
    
        $con=mysqli_connect($server,$username,$pass);
        $connection=mysqli_select_db($con,$database);
    
        if(!$connection)
            echo "Connection to database failed! Please try again";
        else{
            $sql="SELECT `Snapshot` FROM `snippet` WHERE `Date`='".$_POST["date"].
                "' AND `newspaper`='".$_POST["newspaper"]."' AND `Subject_desc`='".$_POST["news_desc"]."'";

            $result = $con->query($sql);
            $temp=explode('.',$result->fetch_array()[0]);

            echo "<div style=
             'text-align:center; vertical-align: middle;
             background-color: #FFFFFF; margin: 0 auto !important; 
             min-height: 100%; padding: 0; width: 978px !important; overflow:auto;'>";

            echo "<h3>{$_POST['newspaper']}</h3>";
            if($temp[count($temp)-1]=="pdf" || $temp[count($temp)-1]=="PDF")
                echo "<iframe src='{$result->fetch_array()[0]}' height='200px'>";
            else
                echo "<img src='{$result->fetch_array()[0]}' height='200px'>";
            echo "<p>{$_POST["news_desc"]}</p>";
            echo "</div>";
        }
        $con->close();
    ?>
</body>
</html>

I am trying to call this script from my js (when a li is pressed):

document.querySelector('body').addEventListener('click', function(event) {
      if (event.target.tagName.toLowerCase() === 'li') {
        var str=event.target.innerText.split('-');
        $.ajax({
            url: '/all_backend_stuff/view_page.php',
            type: 'POST',
            data:{
                "date":document.getElementById("date").value,
                "newspaper":str[0],
                "news_desc":str[1]
            },
            success:function(response){
                window.open('/all_backend_stuff/view_page.php'); //shows that all my array keys are undefined 
            },
            complete:function(){}
        });
      }
});

My POST variables are showing as undefined. Why is that?

  • 3
    **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Mar 11 '22 at 10:16
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use it again. – ADyson Mar 11 '22 at 10:16
  • 1
    `nothing happens. Why is that?`...I doubt that _nothing_ happens. Have you checked your browser's Console? After all the only code you've written to make anything happen after the AJAX call has finished is `console.log(response);`. I think maybe you've misunderstood how AJAX works. With an AJAX call, you send a request to the server asynchronously, and the response which comes back from the server (i.e. anything which is echoed by the PHP, in your case) is delivered back to your AJAX/JavaScript code, inside a variable (the `response` variable of your "success" function)... – ADyson Mar 11 '22 at 10:18
  • ... so for now it's just sitting there in that variable, and all you've done is log it to the console. If you want it to show somewhere on your page, you need to write some JavaScript code in the "success" function which tells the browser where within your existing page you want to show that content. It will not do anything automatically - the whole point of AJAX is to allow you to stay on the same page without refreshing everything. And it wouldn't know where in the current page to automatically add the returned content, unless you tell it specifically. Therefore it's up to you to sort it out – ADyson Mar 11 '22 at 10:20
  • P.S. If you're wanting to include this content from PHP within the existing page which runs the AJAX, then the fact your PHP contains doctype, head and body HTML tags is not good thing - it will end up trying to embed an entire HTML document inside the existing HTML document, and the results may not be good. You should be returning only a snippet of HTML which can then be added into your page. Or, as the answer below says, perhaps you should not be using AJAX at all, and should be using a hyperlink or a form to redirect the browser to your PHP page as a whole new page. Depends what you want. – ADyson Mar 11 '22 at 10:23
  • 1
    `
  • ` elements are not designed to be interactive. Without extra work, users can't tab to them with the keyboard and screen readers won't announce them as being clickable. You should make your click targets `
  • – Quentin Mar 11 '22 at 10:23
  • `My POST variables are showing as undefined. Why is that?`...because `window.open('/all_backend_stuff/view_page.php');` makes a brand new GET request to view_page.php, entirely separate than the one you've just made via AJAX. It runs all over again, and this time, you didn't send it any data. Again, you still seem to have somewhat misunderstood the purpose and concept of AJAX (and possibly HTTP in general, I'm not sure). – ADyson Mar 11 '22 at 10:28
  • Then how do I send the POST variables and display the `php` page at the same time? –  Mar 11 '22 at 10:30
  • Either by the method I've just described above, where you write some JS code to include the response from PHP into the page which ran the AJAX call. Or you forget about AJAX and make a standard HTML form (or a set of forms, if you need) whose action points to the PHP script, which the user submits and the browser posts back in the usual way. – ADyson Mar 11 '22 at 10:31
  • (Disregarding images and iframes for a moment) There are essentially 3 ways to trigger a HTTP request from a browser - click a link, submit a form, or make an AJAX request. All 3 can also be automated via JavaScript commands. The first two cause the browser to navigate to a whole new page automatically. The last one is asynchronous as we've been describing, and merely sends and receives data, leaving it up to you to decide what to do with the data when you've received it. – ADyson Mar 11 '22 at 10:32
  • 1
    _"My POST variables are showing as undefined. Why is that?"_ - because you are looking at the result of a request, that did not send any POST data to begin with: `window.open('/all_backend_stuff/view_page.php')` - this causes a _new_ request, completely independent from your AJAX request. And it is a GET request as well. – CBroe Mar 11 '22 at 10:33