0

I have an index.php page that I want to receive information from a user in a textArea, and, upon hitting save, the variable should be posted to another page called changePage.inc.php. Once the post variable has been set onto the other page, the changePage.inc.php should redirect away from the original index.php to a page called secondPage.php.

variable in jquery on index.php -> same variable as a post on changePage.inc.php -> user is redirected off of index.php to secondPage.php, as instructed by changePage.inc.php

File named index.php

<?php
    session_start();
?>

<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
    crossorigin="anonymous">
</script>
<script>
    $(document).ready(function(){
        $('#saveForm').submit(function(event){
            event.preventDefault();
            var message = "";

            var changeText = function(){
                message = "You wrote: " + $('#text').val();
            };

            var send = function(){
                if(message !== ""){
                    $.post("includes/changePage.inc.php", {message: message});
                    window.location.href = "includes/changePage.inc.php";
                }
            };

            changeText();
            send();
        });
    });
</script>
<body>
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
  <button type="submit" id="saveButton">Save!</button>    
</form>
</body>
</html>

File name changePage.inc.php

<?php

session_start();

if(isset($_POST['message'])){
    header("Location: ../secondPage.php");
}

exit();

File named secondPage.php

<?php
    echo 'Hello World';
?>

With the code as it is right now, it gets to changePage.inc.php, but not secondPage.php. I believe that the post variable is either not being set at all, or being set too late (maybe this is because of a race condition).

I have asked this question before and thought that an answer using function(data) within the $.post() method to create an object with $.parseJSON(data) was going to work. But upon running the code, errors were generated, so now I am asking it again. This is the previous attempt: POST variable from jquery redirecting but is not set

je123
  • 19
  • 6
  • Why are you posting to a page and then setting the location to that page? Why not just do an ordinary form submission? – Barmar Oct 17 '17 at 20:44
  • You're not being redirected because when you assign to `window.location.href` there's no `POST` parameters, so the `if(isset($_POST['message']))` fails. – Barmar Oct 17 '17 at 20:45
  • Do you realize that you're running `changePage.inc.php` twice? You run it once when you do `$.post`, and that gets the `POST` parameter. You run it a second time when you do `window.location.href =`, and that has no POST parameter. – Barmar Oct 17 '17 at 20:46
  • I did not realize that I was running it twice – je123 Oct 17 '17 at 21:15
  • Getting rid of window.location.href = "includes/changePage.inc.php"; still only gets me to changePage.inc.php, and not all the way to secondPage.php – je123 Oct 17 '17 at 21:16

2 Answers2

0

Don't leave the page just after triggering an AJAX request, wait for the result using the callback.

$.post("includes/changePage.inc.php", {message: message}, function (data) {
    // here you see 'Hello World' in your browser console
    console.log(data);
    // here you don't see anything in your browser window because it is no POST
    window.location.href = "includes/changePage.inc.php";
});

But why to trigger an ajax request and redirect to the same page afterwards...

Maybe this is what's intended (second try):

<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous">
    </script>
  </head>
  <body>
    <script>
$(document).ready(function(){
    $('#saveForm').submit(function(event){
        // NO: event.preventDefault();
        var message = "";

        var changeText = function(){
            message = "You wrote: " + $('#text').val();
        };

        changeText();

        // Check for text as message can't be empty here
        if (!$('#text').val()){
            // preventDefault() here if text is empty
            event.preventDefault();
        }
    });
});
    </script>
    <form id="saveForm" action="includes/changePage.inc.php" method="POST">
      <!-- put textarea inside your form, and write tags in lowercase -->
      <textarea id="text"></textarea>
      <button type="submit" id="saveButton">Save!</button>    
    </form>
  </body>
</html>
clemens321
  • 2,103
  • 12
  • 18
  • This still won't redirect to `secondPage.php` – Barmar Oct 17 '17 at 20:58
  • @Barmar It will solve the *mystery* about a race-condition. But it's still unclear what je123 intends to do. Abort the initial post, submit an ajax post and then redirect using location.href doesn't make sense to me either. – clemens321 Oct 17 '17 at 21:14
  • I think he's trying to do what an ordinary form submission does when the script performs a redirect. – Barmar Oct 17 '17 at 21:15
  • I want to change the page from index.php to secondPage.php. – je123 Oct 17 '17 at 21:18
  • I only want the page to change though once the POST variable reaches changePage.inc.php – je123 Oct 17 '17 at 21:18
  • This is a miniature version of the problem I am having within a bigger project. I can post an explanation of my project, and why this specific transfer of data is necessary, if that would be beneficial. – je123 Oct 17 '17 at 21:19
  • I am giving the user the ability to enter text into a bunch of textAreas, that are structured as a tree. So when I want to save this tree structure to my database, I must first format all of the text to create a linear version of all of the tree structure. This is why I must use jquery to be able to get all of the user entered text, format it, and send it to a separate php page with access to the database to be able to save their text. Once saved, I want to redirect the user back to their account page, where they can click a link to load the text back into the tree structure – je123 Oct 17 '17 at 21:21
  • I've updated the answer with a hopefully working version for you. I think you misunderstood the event.preventDefault(); In jQuery (at least) it might be easier to simply `return true;` or `return false;` instead of `preventDefault;` to tell the browser you want to submit the data or not. Furthermore, don't put script tags in html, only in head or body. – clemens321 Oct 17 '17 at 21:29
  • event.preventDefault may not be pretty, but it was not the issue. @Barmar 's solution is exactly what was needed. – je123 Oct 17 '17 at 22:08
0

Redirect to secondPage.php in the Javascript, not PHP. And do it in the callback function of $.post so it waits for the script to complete.

        var send = function(){
            if(message !== ""){
                $.post("includes/changePage.inc.php", {message: message}, function() {
                    window.location.href = "includes/secondPage.php";
                });
            }
        };

But much simpler would be to just add message as an input in the form, and let the form submit normally.

$("#saveForm").submit(function() {
  $("#message").val("You wrote: " + $("#text").val());
}
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
  <input type="hidden" name="message" id="message">
  <button type="submit" id="saveButton">Save!</button>    
</form>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I want changePage.inc.php to make the call, because I want to be sure that the post variable is accessible within changePage.inc.php. – je123 Oct 17 '17 at 21:23
  • In my bigger project, the changePage.inc.php step is where I will be saving the POST variable to a database. – je123 Oct 17 '17 at 21:24
  • This should do that. The redirect doesn't happen until the first script finishes, so the variable will be saved. – Barmar Oct 17 '17 at 21:28
  • Did you mean "accessible within secondPage.php"? – Barmar Oct 17 '17 at 21:28
  • I still don't understand why you're not just submitting the form. That will follow the header redirect after the script is done. – Barmar Oct 17 '17 at 21:30
  • I did not mean "accessible within secondPage.php" – je123 Oct 17 '17 at 21:32
  • In my bigger project, I want to format a lot of text that the user entered after a button has been clicked. After the text is formatted in jquery, I want to send it off the jquery to a different php page to save it to a database there. Once saved, I want to redirect the user off the original page, back to their account. – je123 Oct 17 '17 at 21:34
  • Check my comment on @clemens321 for a longer description of my larger project – je123 Oct 17 '17 at 21:35
  • I'm pretty sure my answer does what you want. – Barmar Oct 17 '17 at 21:37
  • Your solution of putting the window.location.href = in the callback function does everything that I needed. I would have accepted the answer sooner, but I had to find a way to check that the POST variable made it to the next page. Thank you very much! – je123 Oct 17 '17 at 22:07