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 containsheader('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.
In php u echo the URL to redirect to like
If you want php to do redirect you shouldn't use Ajax.
Non ajax method, you almost got it right
The above code will submit to run.php directly, and you can use your original header() function to do redirect.
in php
Update
Then in javascript you need to check for false
// various functions
});
you can try windows.location of JavaScript and pass your value instead of header location.