1

I am two files, a PHP file and another file made of javascript and HTML.

PHP file :

<?php
session_start(); //start session

$_SESSION['data'] = "The content should be displayed as alert in the JS file";

JS/HTML File:

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<form class="form-item" id="idForm">
        <input type="hidden" name="product_code" value="prince"/>
        <button id="btn_add" type="submit">Add to Cart</button>
</form>
<script>


    $(function(){
        $("#idForm").submit(function(e) {

            var url = "test2.php";

            $.ajax({
                type: "POST",
                url: url,
                data: $("#idForm").serialize(),
                success: function()
                {
                    alert(/*The content of the session in the php file should be display here*/); // show response from the php script.
                }
            });

            e.preventDefault();
        });
    });
</script>

In the PHP file, I have a session $_SESSION['data']. All I want to do, it is to be able display the content of that session in alert() after making the ajax request to test2.php

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Prince
  • 1,190
  • 3
  • 13
  • 25

2 Answers2

4

Add response as parameter to success. Response is basically anything that would normally display in the browser (including syntax errors)

  $.ajax({
            type: "POST",
            url: url,
            data: $("#idForm").serialize(),
            success: function(resp)
            {
                alert(resp); // show response from the php script.
            }
        });

Make sure to echo what you wish to display in your PHP script. Anything which gets echoed will be returned in the AJAX response:

<?php
session_start(); //start session

$_SESSION['data'] = "The content should be displayed as alert in the JS file";
echo $_SESSION['data'];
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Moussa Khalil
  • 635
  • 5
  • 12
2

1.In php you have to write in last:-

echo $_SESSION['data']; // so that it will go as a response to the ajax call

2.Then in ajax:-

success: function(response){ // grab the response
   alert(response); // alert the response
}
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • Thanks for your answer, it is working well. What about if in the php file I add this line of code `echo $title;` and I want to alert only `$title` ? – Prince Jul 08 '16 at 15:23