0

Possible Duplicate:
How to return AJAX response Text?

I'm trying to put together a JQuery timeout function for a form submit action. I have something similar in place via PHP for a page reload, and have the time of the initial page load stored in $_SESSION['pageLoad']. What I'm now trying to do is grab that value and use it in some JQuery math.

After searching around SO, I have arrived at the following:

PHP

<?php
    //filename: getsession.php
    session_start();
    echo json_encode($_SESSION['pageLoad']);

JQuery

$("#sms-creator").submit(function() {
    var     session;
    $.ajaxSetup({cache: false})
    $.get('sms_includes/getsession.php', function(data) {
        session = data;
    });

    //at this point I just want to see what I'm getting, hence the next 2 lines...
    alert(session);
    return false;
});

The path to the PHP file is relative to the form page, not the .js file.

My alert only returns 'undefined'. I'm inexperienced with Javascript and its libraries, so the fault is not apparent to me. Any help appreciated.

Community
  • 1
  • 1
Eamonn
  • 1,338
  • 2
  • 21
  • 53

1 Answers1

2

ajax call is done asynchronously. so when $.get is executed, request is sent to server for response, however, the javascript program will not wait for the response because it is done asynchronously. when you alert(session), variable session hasn't been set to data returned by server. Try do ajax synchronously, or put alert session in the ajax callback.

Evan
  • 138
  • 6
  • Okay, I can see the issue now, and have located some examples. Thanks guys. Accepting when I can – Eamonn Dec 17 '12 at 18:11