capturing responseText as a JS variable

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
Forum Commoner
Posts: 70
Joined: Fri Aug 14, 2009 9:43 am

capturing responseText as a JS variable

Post by rick.emmet »

Hello All,
I'm having a real hard time finding anything on the web that will work in solving this problem, I've spent two days looking and haven't gotten anywhere with a search; or tinkering with what I have found to create a function that will run. I have the following AJAX function that accepts a form variable as an argument and passes that to my PHP page to process the MySQL query and return the values. All of this works fine.

Code: Select all

function getPromo(str) {
        // Create a var for the input and one to capture the return value
        var inPut = document.getElementById("promo_code").value;
        //var promo = NULL;

        if (str == "") {
            document.getElementById("dbText").innerHTML = "";
        } else {
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("dbText").innerHTML = this.responseText;
  "GET", "get_promo.php?q=" + inPut, true);

I do want to display the data, but also need to save the values in JS variables and use them in this function (will do more dev work once I can save the values) and also want to pass the variables to other JS functions. I read that I need to use a callback function and then store the values as JS variables. I haven't been able to write a function that accepts the form variable and has a callback feature.

My JavaScript textbook that includes AJAX isn't of any help - the AJAX as written in the book (or downloaded from the site) won't even run! The book doesn't even cover callback functions.

I've read that I can pass the response text to other functions, but I can't figure out a way to capture the read-only responseText as a JS variable in the first place. I've even tried to create $_SESSION variables in my PHP file and inject them into the JS functions, and that won't work either. Can anyone suggest a way to make this work, or another approach that I need to take? Thanks in advance for the help.
User avatar
Posts: 6425
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: capturing responseText as a JS variable

Post by Celauran »

Why not just return JSON from the server? Both PHP and JS know how to handle that.
Post Reply