0

I have two PHP pages. On one of the pages, I want to post data to the other page when a button is pressed. However, when I try to access the post array from the other page, it appears empty. Would appreciate if someone could show me where I'm going wrong. (Also I'm not allowed to use a html form to post)

Page called test2.php:

<?php
    if(isset($_POST['testing1'])){
        die(json_encode($_POST));
    } 
?> 
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="testbtn" onclick="location.href='test1.php'">Test Button</button>
<script>
    $(document).ready(function(){
        $('#testbtn').click(function() {
            $.ajax({
                method: 'POST',
                url: 'test1.php',
                data: {
                    testing1: 'string1',
                    testing2: '111'
                },
                success: function(data){
                    alert(data);
                    output = JSON.parse(data);
                }
            });
        });
    });
</script>
</body>
</html>

Page called test1.php:

<?php
    $testvar = json_encode($_POST);
    echo $testvar;
?> 
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>
  • Might https://stackoverflow.com/questions/16432685/pass-post-data-to-two-php-files help you? – Sintuz Sep 11 '20 at 06:32
  • try `json_encode($_REQUEST);` – Devsi Odedra Sep 11 '20 at 06:33
  • You're trying to parse the response as json even though you seem to be returning HTML as well. That would make `JSON.parse()` fail (and throw errors in the console). – M. Eriksson Sep 11 '20 at 06:36
  • @Sintuz - That link isn't really relevant here, since the OP is simply trying to post some data to another page, while the link is about passing it to multiple pages. – M. Eriksson Sep 11 '20 at 06:39
  • 2
    Might want to remove `onclick="location.href='test1.php'"` as the `onclick=` **fires before** the `$("#testbtn").click` - so it's not even *trying* the ajax (you can confirm this with using the browser's debugging). You're simply opening the 2nd page without a POST so there's no POST data. – freedomn-m Sep 11 '20 at 06:39
  • If you want to redirect the client as well as posting data, then just use an ordinary form instead of ajax (or any js at all) since that's the normal behavior. Ajax is for making requests in the background _without_ redirecting the client. – M. Eriksson Sep 11 '20 at 06:41
  • Or redirect in the `success:` when you've got the result back (if a redirect is actually needed, I suspect not) – freedomn-m Sep 11 '20 at 06:42

3 Answers3

0

the reason the it's failing is because you have so much html on test1.php

alert(data) is having an issue because there is so much content. JSON.parse(data) is failing because it's not just json it's also html

test1.php should just simply parse post to json and echo it

<?php
    echo json_encode($_POST);
?>
Jpsh
  • 1,697
  • 12
  • 17
  • `alert(huge text)` doesn't fail, it truncates the text try: `alert($("body").html())` – freedomn-m Sep 11 '20 at 06:41
  • Also "*when I try to access the post array from the other page, it appears empty*" - so OP isn't even getting to the `success:` callback. But the final part is a good idea for the first step to get things working. – freedomn-m Sep 11 '20 at 06:51
0

When you press the button 2 things are happening in same time :

  1. The ajax call that sends data to the page test1.php
  2. The page redirection beacause of the onClick attribute on the button.

The ajax request calls the page test1.php which is not the same instance as the page you call when you use the onClick attribute. So I think you could try placing "location.href = 'test1.php'" in the success function and store $_POST in a session variable. That way the data will reach the test1.php page before your redirect.

success: function(data){
    alert(data);
    output = JSON.parse(data);
    location.href = 'test1.php';
}
jbolle013
  • 1
  • 3
0

Maybe like this:

Page called test2.php:

<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="testbtn" onclick="location.href='test1.php'">Test Button</button>
<script>
    $(document).ready(function(){
        $('#testbtn').click(function() {
            $.ajax({
                method: 'POST',
                url: 'test1.php',
                data: "yourData="+"{
                    testing1: 'string1',
                    testing2: '111'
                }",
        dataType:"json",
                success: function(data){
                    alert(data);
                    output = JSON.parse(data);
                }
            });
        });
    });
</script>
</body>
</html>

Page called test1.php:

<?php
    if(isset($_POST["yourData"]){
      $testvar = json_decode($_POST["yourData"]);
      echo $testvar->testing1."<br/>";
      echo $testvar->testing2;
    }else{
      echo"is not set";
    }
    if(!empty($_POST["yourData"]){echo $_POST["yourData"];}else{echo"is empty";}
?> 
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>

NB:

  • dataType:"json" used if you want to get a json answer;
  • if you use dataType:"json" that mean you have to change the method json_decode() in my code to json_encode();
  • isset() check if name of associative array is exist;
  • ! means not;
  • empty() check that if the value of that name in associative array is empty (like ' ');
  • !empty() check that if the value of that name in associative array is not empty (not like ' ').
Mohamed Reda
  • 136
  • 1
  • 11