Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to get multiple Javascript values from an AJAX responseText

Posted on 2006-11-24
14
Medium Priority
?
870 Views
Last Modified: 2009-01-07
I have a Javascript function using httprequest to retrieve information.
However, I want it to return several things, and then change multiple parts of the page accordingly.
How can I do this?

I don't want to start slicing up the returned code wiuth string/search functions - each part of the response has a variable length.

If I put the responseText into XML, is there any way that the Javascript can see these as child objects?
(eg, xmlHttp.responseText.someTag)


Here is the function which xmlHttp.onreadystatechange triggers, hopefully demonstrating what I want it to do:

function showComments()
{
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
      {
            returnedInfo=xmlHttp.responseText;

            document.getElementById('misc_html_tag').value = [one snippet of returnedInfo];
            document.getElementById('some_other_tag').value = [other snippet of returnedInfo];
            numVar = parseInt([another snippet of returnedInfo]);
            numVar2 = parseInt([yet another snippet of returnedInfo]);
      }
}

Any other suggestions for methods for getting several values out of the response?
0
Comment
Question by:Arathalion
  • 5
  • 4
  • 3
  • +1
14 Comments
 
LVL 12

Expert Comment

by:enachemc
ID: 18007628
send a response text like: val1#val2#val3 and split the string. Or you can send pure JavaScript as response and execute it on client.
0
 
LVL 1

Author Comment

by:Arathalion
ID: 18007974
enachemc: I see - so I could have the xmlHttp.responseText return a string like "var1='hello';var2=2" etc? What format does it have to be in? Would that require any headers/footers/other tags? Would apostrophes or quotes have to be doubled up, or not? Would it, in essence, be running "eval()" on the string?
0
 
LVL 12

Expert Comment

by:enachemc
ID: 18007995
no, you do not need to use eval (though this is a solution). You can process the string (that is what the response is, a custom string). So what you return in the string and how you process it ... it is up to you.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:Arathalion
ID: 18008113
I'm sorry; I don't quite understand. Can you give a brief example?
0
 
LVL 12

Expert Comment

by:enachemc
ID: 18008140
What I want to say is that, for example, if you want to retrieve 3 values from the DB, the response text could be: 4;2.2;3
Now, when you receive the response, you will know that you will receive 3 values separated by ; Now you will have to split the string and get your 3 values.

One other scenario is that you want to update a line of a table: send a AJAX request for the row and return the complete table row (HTML code) and use inertHTML to replace the old row (using innerHTML).
0
 
LVL 1

Author Comment

by:Arathalion
ID: 18008239
Ah, string manipulation. I specifically don't want to start trying to chop up code with string/split/search commands - I mentioned it in the original request. I'm dealing with text code here, so I could well pull a ";" out of the database as a part of the data. In HTML you'd get around this with " &#59;", but there's still a semi-colon there as far as the javascript is concerned, and parsing things like that would be hellish. That's why I'm avoiding that.

And, as I also mentioned, I need to get more than one thing out at one time - one row I can do fine, but I need a row here, a row there, and some internal variables...
0
 
LVL 1

Expert Comment

by:scathe
ID: 18008245
this is the simplest solution...note sndReq is populating the smtext div with "loading" text

<script>
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}
var http = createRequestObject();
function sndReq(action,p1) {
    http.open(''get'', ''../my_ajax_server_program?action=''+action+''&p1=''+p1);
    http.onreadystatechange = handleResponse;    
    document.getElementById("smtext").innerHTML = ''loading...'';
    http.send(null);
}

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();
        if(response.indexOf(''|'' != -1)) {
            update = response.split(''|'');
             document.getElementById("smtext").innerHTML = '''';
            document.getElementById(update[0]).innerHTML = update[1];
            if (  document.getElementById(update[2]))
           { document.getElementById(update[2]).innerHTML = update[3]; }
           if (  document.getElementById(update[4]))
           { document.getElementById(update[4]).innerHTML = update[5]; }
        }
    }
}
</script>

so.........

if you have <div id=area1> <div id=area2> <div id=area3> on your page

you can have your ajax server side program pass back this string.....

area1| some html |area2| more html |area3| yet more html

and this script will split on the pipe and put the text into each div.

Its probably not elegant, but its a start for you and sounds like the easiest way to do what you ask.
0
 
LVL 1

Expert Comment

by:scathe
ID: 18008261
oh apologies for the double single quotes - its being parsed again in an oracle databse in my version
0
 
LVL 1

Author Comment

by:Arathalion
ID: 18008461
Hmm. I can see how it works, and that it's a fairly clean way of doing string manipulation, but it's still string manipulation.
And, once again, I can't be sure that the data will not contain the delimiting character. Admittedly, the "|" is rare, but I need something that won't break.

I'm surprised that the question hasn't come up before - a search found me nothing. It sounds like such a useful thing to be able to do!

Is there no way that it can auto-populate an object?


If there isn't, I think I'll have it return HTML, fill a hidden div, and use getElementById on tags within that!
0
 
LVL 1

Expert Comment

by:scathe
ID: 18009492
can you split on  more than one character then ?  i remember from my Amiga days the wildcard for any search was  #?  and by using both characters together it allowed for any characters in file names - similar thing here ?

sorry - for the misunderstanding too, i thought you meant you didnt want to have to think of the code for string manipulation not that you didnt want to use it at all.
0
 
LVL 12

Expert Comment

by:enachemc
ID: 18010840
if your values are not related, then perhaps there is better that you do more AJAX request.
0
 
LVL 23

Accepted Solution

by:
rama_krishna580 earned 1000 total points
ID: 18012035
0
 
LVL 1

Author Comment

by:Arathalion
ID: 18012148
rama_krishna580: Excellent, thanks, that's exactly what I need.
0
 
LVL 23

Expert Comment

by:rama_krishna580
ID: 18012170
Thanks for 'A'.

R.K
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

783 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question