Unable to access AJAX data [PHP]

2019-09-20 05:00发布

A form on my homepage (index.php) opens a randomly generated URL in a new tab, after being submitted. That random url is running a script called run.php

<form action="/run.php" method="POST" target="_blank">
    <input type="hidden" id="idgen" name="idgen" value="<?php echo $random ?>">
    <input type="text" name="userinput" id="userinput">
    <button type="submit" onclick="calcResult();">Go!</button>
</form>

There are JS functions on my homepage that use the userinput data to calculate a result.

I'm trying to use AJAX to send a value from my index.php to the random url generated by the form.

function calcResult() {
  var userinput = document.getElementById('userinput').value;
  var randomid = document.getElementById('idgen').value;

  // various functions

    $.ajax({
            type: "POST",
            url: 'http://example.com/' + randomid, // same random url as the form sends to
            data: {result: "Hello!"}, // using simple result for testing purposes
            success: function(response){
                console.log(response);
           }
});

I added <?php echo $_POST['result']; ?> to the run.php file (the random url that the form opens is running run.php)

console.log(response) shows it working. It console logs the entire example.com/<randomID> source code (shows entire run.php code), and even replaces <?php echo $_POST['result']; ?> with "Hello".

However, this only works in the console. When that webpage is opened by the form, "Hello" is not shown.

I have a MySQL database that I insert values into from the run.php file. I tried to do the same for $_POST['result']; with no luck.

There are no console errors when I use the above code, nor are there any fatal errors in the error log.

Extra info

  • The form submits to run.php which contains header('Location: http://example.com/'.$_POST['idgen']); in order to redirect to the random url.
  • The random urls exist using a htaccess RewriteRule RewriteRule ^([0-9a-zA-Z]+)$ /run.php?idgen=$1 [L]
  • Attempted to use 'Flight' framework, but was runnning into issues when trying to use JS functions with it.

Goal

  • The overall goal is to send the results (obtained from JavaScript functions on my homepage) to PHP. Such that they will display on the random url that opens after the form is submitted - so that I can display them, add them to the database etc.

2条回答
倾城 Initia
2楼-- · 2019-09-20 05:18

In php u echo the URL to redirect to like

echo 'http://example.com/' . $_POST['idgen'];
die();

If you want php to do redirect you shouldn't use Ajax.

Non ajax method, you almost got it right

<form action="run.php" method="POST" target="_blank">
    <input type="hidden" id="idgen" name="idgen" value="<?php echo $random ?>">
    <input type="text" name="userinput" id="userinput">
    <button type="submit">Go!</button>
</form>

The above code will submit to run.php directly, and you can use your original header() function to do redirect.

in php

header('Location: http://example.com/'.$_POST['idgen']);

Update

/* RUN.PHP PAGE - THE PAGE TO RECEIVE THE JAVASCRIPT RESULTS */

<?php

    $endurl = $_POST['idgen']; ?>

    <?php
    if (isset($_POST['userinput'])) {

  // DATABASE LOGIN DETAILS HERE
        $conn = new mysqli($servername, $username, $password, $dbname);

        if ($conn->connect_error) {
            echo 'false';
            die();
            //die("Connection failed: " . $conn->connect_error);

            //Just echo False so Javascript knows what's happening.
        }

        $sql = "INSERT INTO mydatabasename (userinput,randurl)
        VALUES ('$_POST[userinput]','$_POST[idgen]')";

        if ($conn->query($sql) === TRUE) {
            //echo "New record created successfully"; // You cannot echo anything else if you want to do a redirect. Try error_log?
            error_log('New Record Created Successfully');
        } else {
            echo 'false';
            die();
            //echo "Error: " . $sql . "<br>" . $conn->error;
            //let javascript know you failed.

        }

        $conn->close();
           // header('Location: http://example.com/'.$endurl);
           echo 'http://www.example.com/'.$endurl;
           die();
    }
    else if (isset($_GET['idgen'])) {
      // DATABASE LOGIN DETAILS HERE
        $conn = new mysqli($servername, $username, $password, $dbname);

        if ($conn->connect_error) {

            //die("Connection failed: " . $conn->connect_error);
            error_log('Connection Failed:' . $conn->connect_error );
            echo 'false';
            die;
        }

        $sql = "SELECT userinput FROM mydatabasename WHERE randurl = '".$_GET['idgen']."'";

        $result = $conn->query($sql);

        if ($result) {
                if ($row = $result->fetch_array()) {

            }
            $result->close();
      }
      $conn->close();
    }
    ?>

Then in javascript you need to check for false

function calcResult() {
  var userinput = document.getElementById('userinput').value;
  var randomid = document.getElementById('idgen').value;

// various functions

$.ajax({
        type: "POST",
        url: 'http://example.com/' + randomid, // same random url as the form sends to
    data: {
    result: "Hello!",
    userinput: userinput,
    idgen: randomid

    }, // using simple result for testing purposes
    success: function(response){
        if (response != 'false') {
        window.location.replace(response);
        } else {
        alert('error encountered');
        }
   }

});

查看更多
唯我独甜
3楼-- · 2019-09-20 05:30

you can try windows.location of JavaScript and pass your value instead of header location.

查看更多
登录 后发表回答