0

I use ajax in a small part of my application to post form variables to a php script that makes a query to my api.

Here is the form

<input name="answer_id" id="answer_id<?= $i;?>" type="radio" style="width: 21px" value="<?= $ans_id; ?>"> <!-- I have a for loop here that provides 3 different answers for the radio button -->
<input name="question_id" id="question_id" type="hidden" style="width: 21px" value="<?= $question_id; ?>">
<input name="all_answers" id="all_answers" type="hidden" style="width: 21px" value='<?= serialize($answers); ?>'>
<input name="Submit" onclick="post_question()" type="submit" value="Submit" class="btn btn-success">
<input type="hidden" id="campaign_id" value="<?= $campaign; ?>">

The post_question() function

var responseData = [];
function post_question(){
    var data = new FormData(),
        obj,
        campaign = document.getElementById('campaign_id').value;
    data.append("all_answers", document.getElementById('all_answers').value);
    data.append("question_id", document.getElementById('question_id').value);
    data.append("campaign_id", document.getElementById('campaign_id').value);
    load_post("controllers/post_question.php", data);
    var tempVar = responseData['response'];//The problem begins here. responseData['response'] appears to be an empty string
    console.log("tempVar variable: " + tempVar);
    console.log(tempVar);
}

The load_post() function

function load_post(url, params){
    new imageLoader(cImageSrc, 'startAnimation()');
    var xhr,
        response = [];
    if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
    else {
        var versions = ["MSXML2.XmlHttp.5.0",
            "MSXML2.XmlHttp.4.0",
            "MSXML2.XmlHttp.3.0",
            "MSXML2.XmlHttp.2.0",
            "Microsoft.XmlHttp"]
        for(var i = 0, len = versions.length; i < len; i++) {
            try {
                xhr = new ActiveXObject(versions[i]);
                break;
            }
            catch(e){}
        } // end for
    }
    xhr.onreadystatechange = ensureReadiness;
    function ensureReadiness() {
        if (xhr.readyState !== 4) {
            return;
        }
        responseData['response'] = xhr.responseText;
        responseData['code'] = xhr.status;
    }

    xhr.open('POST', url, true);
    xhr.send(params);
    responseData['response'] = xhr.responseText;
    responseData['code'] = xhr.status;
    return responseData;
}

The variable responseData is a global variable. It is an array. responseData['response'] is a json array containing an object.

[{"id":"10082","question_id":"26","answer_id":"46","profile_id":"42121","correct":"1","attempts":"8"}]

and that is what is returned from the post_question.php page. What I have trouble doing is accessing that JSON object, I've tried storing it in a global variable and I've tried passing it to another function with no success. And for some reason the global variable says its an empty string. however, using firebug checking the responseData variable, this is what I get:

The Console

This didn't quite solve my problem and neither did this there's a few other resources I've gone to that didn't quite help solve my problem. What I would like is to either pass the responseData variable that gets saved in load_post() or access that variable from the post_question() function, it is a global variable after all. Any help would be appreciated. P.S. I'm new to javascript.

Community
  • 1
  • 1
billions_ln
  • 554
  • 4
  • 10
  • @Quentin I have the response stored in a global variable. I'm just having trouble accessing the global variable. And that post is a solution using the Jquery library, I'm using vanilla js (raw javascript), I'd hate to have to recode everything using Jquery over something so small. – billions_ln Jan 28 '14 at 09:26
  • *I have the response stored in a global variable.* — No, you don't (at least, not at the time you try to read it). – Quentin Jan 28 '14 at 09:27
  • *I'd hate to have to recode everything using Jquery* — The *principles* are the same, only the syntax is different. – Quentin Jan 28 '14 at 09:27
  • Is it `load_post` called after `post_question`? – MarcoL Jan 28 '14 at 09:40
  • @MarcoCI Yes, it gets called within `post_question` – billions_ln Jan 28 '14 at 09:47
  • @Quentin Thanks for the post, [this link](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) makes sense, now I understand why you say when its being accessed its empty. I'll try that solution out. – billions_ln Jan 28 '14 at 09:50

1 Answers1

0

This line of code

load_post("controllers/post_question.php", data);

is async, so the following line will access an empty array in responseData.

To handle the async nature of the AJAX call you have to pass a callback that would be called at the end of the AJAX task, something like:

function load_post(url, params, callback){
    new imageLoader(cImageSrc, 'startAnimation()');
    var xhr,
        response = [];
    if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
    else {
        var versions = ["MSXML2.XmlHttp.5.0",
            "MSXML2.XmlHttp.4.0",
            "MSXML2.XmlHttp.3.0",
            "MSXML2.XmlHttp.2.0",
            "Microsoft.XmlHttp"]
        for(var i = 0, len = versions.length; i < len; i++) {
            try {
                xhr = new ActiveXObject(versions[i]);
                break;
            }
            catch(e){}
        } // end for
    }
    xhr.onreadystatechange = ensureReadiness;
    function ensureReadiness() {
        if (xhr.readyState !== 4) {
            return;
        }
        responseData['response'] = xhr.responseText;
        responseData['code'] = xhr.status;
        callback(responseData);
    }

    xhr.open('POST', url, true);
    xhr.send(params);

  }

  function post_question(){
    var data = new FormData(),
        obj,
        campaign = document.getElementById('campaign_id').value;
    data.append("all_answers", document.getElementById('all_answers').value);
    data.append("question_id", document.getElementById('question_id').value);
    data.append("campaign_id", document.getElementById('campaign_id').value);
    load_post("controllers/post_question.php", data, processNewData);
  }

  function processNewData(newData){
    var tempVar = newData['response']; // or you can use responseData at this point as well
    console.log("tempVar variable: " + tempVar);
    console.log(tempVar);
  }

In the implementation above I'm passing responseData as argument of the callback, but because it is a global variable you can also call the callback without arguments and access it if you want.

billions_ln
  • 554
  • 4
  • 10
MarcoL
  • 9,829
  • 3
  • 37
  • 50