-1

Yesterday I asked about connecting HTML, Javascript and PHP with sessions.

I was advised to use $.ajax(), but I'm having trouble figuring out how to get it working.

To start off with I have a HTML file:

<?php session_start(); ?> <!-- This is on the first line of the page -->
...
<form id="formexample" method="post" action="cart.php">
<select name="formexample1">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
<select  name="formexample2">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
<button type="button" onclick="addToCart()">Add to Cart</button>
</form>
<div class="test"></div>

I have this in a separate, inlcuded PHP file: cart.php

<?php   

session_start(); 
$PHPtest = 1;
echo json_encode($PHPtest);
/* 
$_SESSION['cart'][$_POST['formexample1']] = $_POST['formexample1'];
$_SESSION['cart'][$_POST['formexample1']][$_POST['formexample2']] = [$_POST['formexample2']] 

*/
?>

My goal is to access the $_SESSION variable in my Javascript, but for the moment I'm trying to do get it to work with $PHPtest first.

In the Javascript I have this:

function addToCart()
{
    var test;
    $.ajax(
    {
        url:"cart.php",
        type:"post",
        data: data,
        success:function(PHPtest) 
        {
            test = $.parseJSON(PHPtest);
            console.log(test); //sends the response to your console
        },
        error:function() 
        {
            console.log("Error");
        }
    });
    alert(test);
}

To see how I got to this point, see the thread from yesterday (linked at the top of the page) and the discussion under Josh S's answer. I'm trying to get $.ajax() to work, but without success. I've been looking at online examples and have been trying to write the same format, but nothing I try seems to work.

Thanks in advance.

EDIT:

This is what I have now:

    var test;
    $.ajax(
    {
        url:"cart.php",
        type:'post',
        data: 'test',
        datatype: 'json'
        success:function(PHPtest) 
        {
            test = $.parseJSON(PHPtest);
            alert(test);
            console.log(test); //sends the response to your console
        },
        error:function() 
        {
            console.log("Error");
        }
    });

EDIT 2

I finally figured out how to send $PHPtest to Javascript. I wrote:

$.get( "cart.php", function( PHPtest ) {
test = PHPtest;     
alert(test);
        });

My PHP remains:

<?php   

/* session_start();*/ 
$PHPtest= "test";
echo json_encode($PHPtest);
?>

It works for various values of PHPtest. As far as I can tell taking out "json_encode" between "echo" and "$PHPtest" makes no difference.

EDIT 3

Here's what I have now.

HTML: This is in a file "bookings.php". ... Option 1 Option 2 Option 1 Option 2 Add to Cart

Javascript:

function addToCart()
 {
    var test;
    get( "cart.php", function(PHPtest) 
    {
    test = PHPtest;
    alert(test);
    });
}

PHP: External PHP file, "cart.php":

<?php   

    /* session_start();*/
        $PHPtest= "Example";
        echo json_encode($PHPtest);
        if(isset($_POST))
        {
             $_SESSION['cart']['0'] = $_POST['formexample1'];
        }
?>

The alert shows:

"Example"
Notice: Undefined index: formexample1 in (directory) on line 8

The same text appears in the top left of the page, even if I comment out the "$.get()".

EDIT 4

I'm trying to extract a single PHP variable, $PHPtest, with AJAX. I'm also trying to retrieve POST information correctly.

HTML:

<?php session_start(); ?> <!-- This is on the first line of the page -->
...
<form id="bookingform" method="post" action="cart.php">
<select name="day">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
<select  name="time">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>
<button type="button" onclick="addToCart()">Add to Cart</button>
</form>

Javascript:

function addToCart()
{
        $("#bookingform").submit();
        var test;
        $.get( "cart.php", function(PHPtest) {
        test = PHPtest;
        alert(test);
        });
}

cart.php:

session_start();
    $PHPtest = "Test";
    $PHPtest = "Test2";
    echo json_encode($PHPtest);
    echo json_encode($PHPtest2);

    if(isset($_POST['day']))
    {
        /*$PHPtest3 = "test3"
        $_SESSION['cart']['0'] = $_POST['day'];
        echo json_encode($PHPtest3);
        echo json_encode($_POST['day']);*/

    }

As it is, the alert produces

> "Test""Test2"

Uncommenting the "isset" in cart.php changes the alert to:

    <br />
<b>Parse error</b>: syntax error, unexpected '$_SESSION' (T_VARIABLE) in <b>(directory)</b> on line <b>14</b><br />

Line 14 is the line with "$_SESSION['cart']['0'] = $_POST['day'];".

Community
  • 1
  • 1
  • ajax is asynchronous. You can't alert the response outside of the success callback. Also what is `data`? ... it looks undefined. Are you seeing the response logged to console? Any errors thrown? – charlietfl Feb 27 '16 at 14:40
  • Thanks Nordenheim, I've added that. @charlietfl: Right now the "alert" shows nothing since the Javascript is broken, but before when I was playing around with it it simply showed "undefined". I wrote "data: data", because that's what I saw in online examples. I also tried "data: PHPtest" yesterday (see the link at the top of the page), but that didn't work. "You can't alert the response outside of the success callback" - Sorry, but I'm not sure what you mean here. Are you saying that I can't retrieve a PHP variable and then use it in PHP outside of $.AJAX()? – user5988698 Feb 27 '16 at 14:57
  • It means that you need to consume the data inside the `success` callback. Your alert will fire before the ajax has completed...it takes time to make the request. It's like ordering a pizza and trying to eat it before it is delivered – charlietfl Feb 27 '16 at 14:59
  • @charlietfl So I need to delay the onset of "alert()" until "$.ajax()" is completed, if I'm understanding correctly? I don't know how to do that. – user5988698 Feb 27 '16 at 15:07
  • Same place you are logging to console – charlietfl Feb 27 '16 at 15:09
  • @charlietfl I've added "alert()" before "console.log()". Is that what you mean? I've edited my post to show what I've done. – user5988698 Feb 27 '16 at 15:13
  • Exactly...that is where you need to consume the data. – charlietfl Feb 27 '16 at 15:15
  • @charlietfl Thanks, but my Javascript is still broken. I'm not sure what I'm doing wrong. – user5988698 Feb 27 '16 at 15:19
  • Need to explain what does happen..and if any errors show up in console – charlietfl Feb 27 '16 at 15:20
  • @charlietfl I'm not seeing any errors on the page, but all the Javascript on the page is broken (in every function) unless I comment out "$.AJAX". When I run the page everything seems good until I click the button (or do something to activate on of the other Javascript functions) and nothing happens. – user5988698 Feb 27 '16 at 15:24
  • *"broken"* is meaningless term. Are you sure there are no errors in browser dev tools console? – charlietfl Feb 27 '16 at 15:26
  • @charlietfl I just looked up how to use browser dev tools. It says "Uncaught ReferenceError: addToCart is not defined". It says the same thing when I try to run every other Javascript function on the page (with the function name instead of addToCart). Commenting out "$.AJAX()" in addToCart removes all errors. – user5988698 Feb 27 '16 at 15:33
  • @charlietfl Incidentally, I just noticed that the value of $PHPtest is printed in the top-left of the screen. – user5988698 Feb 27 '16 at 15:36
  • That console is your first line of debugging anything in javascript. That's what was meant by `any errors?` – charlietfl Feb 27 '16 at 15:36
  • Suggest you study some ajax tutorials – charlietfl Feb 27 '16 at 15:37
  • Ah, sorry about that. – user5988698 Feb 27 '16 at 15:37
  • @charlietfl With all due respect, isn't it a bit overkill to learn a new language just to do one thing - to get a PHP variable into Javascript? I feel like there has to be a simple function that does this in a second, but I've been trying to do this one thing for several days and it's getting more and more complicated. I've been looking at some AJAX tutorials since that post yesterday, but they're difficult to understand and they seem far too complicated for what I'm trying to do. – user5988698 Feb 27 '16 at 15:45
  • Unless you plan to submit the form itself and reload page each time there isn't really any shortcuts – charlietfl Feb 27 '16 at 15:47
  • @charlietfl I've read this page a dozen times, but I still don't get it: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp I've written "var test = XMLHttpRequest();, xhttp.open("PUT", "cart.php", "true");, xhttp.send(__);", but I have no idea what I'm meant to send and why I'm meant to send it. – user5988698 Feb 27 '16 at 16:55
  • Then study some jQuery and php ajax tutorials. Using `$.ajax` is simpler. SHould be easy to find numerous tutorials for this – charlietfl Feb 27 '16 at 16:58
  • @charlietfl That's extremely discouraging for someone who's done nothing but read tutorials for several days and is no closer to understanding any of it :-D The tutorials I've don't teach from the beginning. So far learning programming I've found that understanding a lot of explanations for beginners require deeper knowledge of the subject than the thing being explained, and you can go in circles reading a definition of a term inside the definition of another term and so on; and when you finally get it, you realise it's much simpler than you thought. – user5988698 Feb 27 '16 at 17:33
  • @charlietfl For example, look at this: http://www.w3schools.com/jquery/jquery_ajax_load.asp The explanation, function prototype and examples seem to do completely different things to me. The explanation is that "The load() method loads data from a server and puts the returned data into the selected element". That seems simple enough, and exactly like what I want. The function prototype is "$(selector).load(URL,data,callback);". Data is a "parameter [which] specifies a set of querystring key/value pairs to send along with the request.". – user5988698 Feb 27 '16 at 17:34
  • @charlietfl I don't understand why you'd do this, and how it's relevant to what the explanation says the function does. Callback "is the name of a function to be executed after the load() method is completed." It can have the parametres: "responseTxt - contains the resulting content if the call succeeds, statusTxt - contains the status of the call, xhr - contains the XMLHttpRequest object". – user5988698 Feb 27 '16 at 17:34
  • What's the XMLHttpRequest object? I read about what that means earlier, but I have no idea how to send it into the function after declaring it, since in the example they just wrote "xhr". I don't understand the point of the other two parametres, and looking and the example I have no idea how to specify WHAT to get from the server. – user5988698 Feb 27 '16 at 17:35
  • Sorry for my stupidity, but I am trying :-D – user5988698 Feb 27 '16 at 17:35
  • http://learn.jquery.com/ajax/ – charlietfl Feb 27 '16 at 17:41
  • @charlietfl I've finally figured out how to send $PHPtest to the Javascript (see my edit), but now I'm struggling to send the _SESSION variables. I've uncommented the _SESSION declarations in cart.php, but it tells me "Notice: Undefined index: (formexample) in (directory) on line (line)" for every line. It also tells me "Notice: A session had already been started - ignoring session_start() in (directory) on line 4" if I add "session_start()" to cart.php. These errors are printed onto the page, and they still appear after commenting the Javascript out. I have no errors in console tools. – user5988698 Feb 27 '16 at 20:38
  • error seems self explanatory... can only start session once. Google other error for explanation – charlietfl Feb 27 '16 at 20:40
  • @charlietfl The reason why I added the session_start() is because in the thread yesterday, I was told "Also, make sure your script that your ajax is calling has the session_start() on that page as well, or it won't be able to interact with your session." Sorry, I thought it was you who told me that! The other errors still appear even without session_start()... but I think I just figured it out. I'll at "if(isset($_SESSION['cart']){...}" and see if that solves it. Edit: The other errors are still there. – user5988698 Feb 27 '16 at 21:16
  • @charlietfl The last error is still there, but I also just noticed the values I'm echoing from cart.php are appearing printed on the site in the top left. – user5988698 Feb 27 '16 at 22:38
  • Are you using the same file to do other things than just output that json? – charlietfl Feb 27 '16 at 22:44
  • @charlietfl No. It's the same as the PHP on the top of this page (the second box) minus, except I uncommented the $_SESSION variables. – user5988698 Feb 27 '16 at 22:47
  • @charlietfl I think I found the source of the error. "$_SESSION['test']['0'] = "test";" produces no error, but "$_SESSION['test']['0'] = "$_SESSION['cart']['0'] = $_POST['formexample1'];" produces the same error I've been getting, even in "if(isset($_POST)){...}". I take it that means something's wrong with how I've been posting the form? – user5988698 Feb 27 '16 at 22:55
  • @charlietfl Now I get the following in the alert""Test"
    Notice: Undefined index: formexample1 in (directory) on line 8
    " That's what appears in the top-left of the page by the way.
    – user5988698 Feb 27 '16 at 23:05
  • Makes no sense including cart.php in main page if it echos json. That json was being used only for ajax – charlietfl Feb 27 '16 at 23:10
  • @charletfl I've updated the opening post (under "EDIT 3") to show what my code currently is. – user5988698 Feb 27 '16 at 23:24
  • "Makes no sense including cart.php in main page if it echos json. That json was being used only for ajax" - Wait, I was told yesterday that I had to echo the code for it to be accessed on the client side. Is this not correct? – user5988698 Feb 27 '16 at 23:25
  • @charlietfl Or are you saying I shouldn't include cart.php at the top of the main page at all, and simply send the form there and retrieve the data with AJAX? – user5988698 Feb 27 '16 at 23:31
  • I'm saying that when you use it ... it should only output json for the ajax....and should not if it is being used elsewhere. If it does other functionality then that needs to be considered wherever it is used – charlietfl Feb 27 '16 at 23:33
  • @charlietfl I've gotten rid of the include and that stops the error and echo appearing in the top left of the page, but it still appears in the alert. – user5988698 Feb 27 '16 at 23:34
  • @charlietfl I'm only using cart.php to retrieve POST data, store session data and pass those values to Javascript later. If that's all I'm doing, will I not need to include it? – user5988698 Feb 27 '16 at 23:39
  • @charlieftl I've changed the PHP to "$PHPtest = "Test"; $PHPtest2 = "Test2"; echo json_encode($PHPtest); echo json_encode($PHPtest2);". The problem is that the alert prints BOTH "Test" and "Test2"., even though the function only specifies PHPtest. I'm still having trouble assigning $_POST['formexample1'] to anything. – user5988698 Feb 27 '16 at 23:46

1 Answers1

0

With so many edits it's hard to tell where you stand with this. So let's work backwards and figure this out.

Edit 3

You're getting this error because you're not actually posting anything. The $_POST is always going to be set. So your check for it is giving you a false positive. You're instead going to want to do something like this:

<?php   
  session_start();
  if (isset($_POST['formexample1'])) {
    $_SESSION['cart']['0'] = $_POST['formexample1'];
  }

Edit 2:

You had it right in the first place. You're actually looking to POST data to the backend. That's the way it seems from cart.php, at least. If you want to skip using the whole $.ajax() call then you can look into jQuery post.

Edit 1:

...
    url:"cart.php",
    type:"post",
    data: data,
 ...

I don't see where your data object is coming into play. Javascript will let you throw around undefined variables. jQuery will silently handle them for you. This may instead be helpful to you.

...
    url:"cart.php",
    type:"post",
    data: { 
      "formexample1" : $('select[name="formexample1"]').val(),
      "formexample2" : $('select[name="formexample2"]').val()
    }
...

That should help you get back the results you're looking for. Let me know if it doesn't.

Iwnnay
  • 1,933
  • 17
  • 18
  • Thanks for the reply! I'm looking at what you suggested for edit three. It looks like you made "$_POST['formexample1']" the key to the value "$_POST['formexample2']" in the array. I'm confused why you did this. I'm also a bit confused with this on what you said about the second edit: "You're actually looking to POST data to the backend." Isn't that the job of the form in the HTML, or am I missing something? Thanks in advance. – user5988698 Feb 28 '16 at 00:16
  • For Edit 3 I only did that because it looked like that's what you wanted originally. I'll fix my answer to be more inline with what you posted under edit 3. Edit 2 you switched to `$.get()`. But you're actually not using the form submit action from the page. You're using ` – Iwnnay Feb 28 '16 at 00:18
  • Would the HTML be fixed if I gave the form an ID of "bookingform" and wrote "$("#bookingform").submit();" in "addToCart()" before $.get()? – user5988698 Feb 28 '16 at 00:28
  • It's up to you. There's no one way to do this. You could jquery.submit -> jquery.get or you could jquery.ajax(formData) – Iwnnay Feb 28 '16 at 00:31
  • Thanks. I've updated my opening post with a fourth edit. – user5988698 Feb 28 '16 at 00:50
  • I think I have two main problems: 1) storing the values I get from POST and 2) getting the value of a single variable from PHP. – user5988698 Feb 28 '16 at 01:04