Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts

    Receiving AJAX /JSON Response & Parsing it (without JQuery)

    Okay so the problem I seem to be having is that apparently my Javascript seems unable to receive my JSON responseText correctly. My console area in Google Chrome is not showing any errors for the syntax of the JSON that I have been sending back to the Javascript.

    For error-checking purposes I created a small span at the bottom of my page called "notes_list" and had Javascript tell it to change the innerHTML of that area to whatever the length is, once the responseText was received and it said "undefined". Now I told it to "echo", for lack of better term, the value of JSON.parse(ajax.responseText) and it just says "[object Object]".

    Why is Javascript having problems accessing the responseText array? When I manually set a variable to the responseText by literally copying and pasting it from FireBug (which shows the AJAX response) and started playing with it, it didn't seem to have any problems. So what gives? Here is the relevant code:

    Code:
    function reorder () {
            'use strict';
            var ajax = getXMLHttpRequestObject();
            if (ajax) {
                
                //assign the values, at that moment, 
                var criteriaValue = criteria.value;
                var orderValue = order.value;
                var viewCountValue = viewCount.value;
                
                //create ajax object
                ajax.onreadystatechange = function() { //begin of function clause for readyStateChange
                    if(ajax.readyState === 4) { //start of correct ajax readyState (4) clause
                     //check the status code
                     if ( (ajax.status >= 200 && ajax.status < 300) || (ajax.status === 304) ) { //start of correct ajax status clause
                         var reorderResponse = JSON.parse(ajax.responseText);
                         var notesList = document.getElementById('notes_list');
                         notesList.innerHTML = 'Ajax Response = ' + JSON.parse(ajax.responseText);
                         var productGrid = document.getElementById('product_grid')
                         productGrid.innerHTML = '';
                         for (var i = 0; i <= reorderResponse.length; i++){
                             var productBox = document.createElement('div');
                             notesList.innerHTML = 'New div created. ';
                             productBox.className = "product_box";
                             productGrid.appendChild(productBox);
                             notesList.innerHTML = 'Product box appended. ';
                             var productImage = document.createElement('div');
                             productImage.className = "product_image";
                             var imageLink = document.createElement('a');
                             var responseProductId = reorderResponse[i].productId;
                             imageLink.href = "view_product.php?product_id=" + responseProductId;
                             notesList.innerHTML = 'Product ID appended. ';
                             var actualImg = document.createElement('img');
                             imageLink.appendChild(actualImg);
                             actualImg.removeAttribute("style");
                             var imgSrc = reorderResponse[i].imagePath;
                             actualImg.src="products/images/" + imgSrc;
                             notesList.innerHTML = 'Product image source added';
                             var responseProductDescription = reorderResponse[i].productDescription;
                             actualImg.alt = responseProductDescription;
                         }
                        } //end of correct ajax status clause
                     
                    } //end of correct ajax readyState (4)
                 
                }; //end of function for execution on ready state change
                    var data = 'newCriteria=' + encodeURIComponent(criteriaValue) + '&newOrder=' + encodeURIComponent(orderValue) + '&newViewCount=' + encodeURIComponent(viewCountValue);
                    if (typeof getCategory !== 'undefined' && getCategory.length >= 1){
                        data += '&getCategory=' + getCategory;
                    }
                    ajax.open('GET', 'resources/product_grid_order.php?' + data, true);
                    ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    ajax.send(data);
            } //end of ajax object being set
            
        } //end of reorder() function definition
    As you can see I am trying to loop through the array later on but I need to make sure Javascript is handling the response text and assigning to a variable correctly. Any help would be appreciated, thank you.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,349
    Thanks
    11
    Thanked 589 Times in 570 Posts
    Quote Originally Posted by d'Anconia View Post
    For error-checking purposes I created a small span at the bottom of my page called "notes_list" and had Javascript tell it to change the innerHTML of that area to whatever the length is, once the responseText was received and it said "undefined". Now I told it to "echo", for lack of better term, the value of JSON.parse(ajax.responseText) and it just says "[object Object]".
    if it says "[object Object]", that actually means it's working....

    try
    Code:
      var reorderResponse = JSON.parse(ajax.responseText);
    console.log( "parsed response object", reorderResponse );
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #3
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    Hmmm then exactly what do I have to do in order to find the length (number of elements) in the first dimension of the responseText array? It gave me 'undefined' when I tried using responseText.length and I need that number for my loop (so I can loop through each first dimension of the array and access the second-dimension elements).
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,549
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    responseText is *NOT* an array. It is just a string.

    To convert it to an array (assuming that it is correctly JSON-encoded as such), indeed you can use JSON.parse().

    *IF* the JSON encoding is correct and *IF* it is encode as a single array, then doing
    Code:
    var ary = JSON.parse( ajax.responseText );
    should, indeed, result in a single array in the variable ary.

    But that's easy to check, with a debugger. Just put a breakpoint on the next line and use the debugger to inspect the contents of ary.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,549
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    I don't suppose you'd care to share a sample responseText result with us? Before parsing it?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #6
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,349
    Thanks
    11
    Thanked 589 Times in 570 Posts
    reorderResponse.length, as long as you are serving an array-shaped JSON.
    if that's not the case, we'd need to see the actual response text to coin a specific path expression for you.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #7
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    No problema:

    Code:
    {"0": { "productId" : "7", 
                        "price" : "53",
                        "imagePath" : "677848166.jpg",
                        "productName" : "Speaker 2",
                        "productDescription" : "Blah  blah blah",
                        "dateOfCreation" : "2012-12-04 13:35:49",
                        "category" : "Electronics"},"1": { "productId" : "8", 
                        "price" : "77.9",
                        "imagePath" : "353839980.jpg",
                        "productName" : "Speaker 6",
                        "productDescription" : "These are Speakers 6",
                        "dateOfCreation" : "2012-12-04 13:50:03",
                        "category" : "Electronics"},"2": { "productId" : "9", 
                        "price" : "23",
                        "imagePath" : "579750224.jpg",
                        "productName" : "Studded Jean Shorts",
                        "productDescription" : "Ripped jean shorts with metal studs",
                        "dateOfCreation" : "2012-12-11 20:09:11",
                        "category" : "Apparel"},"3": { "productId" : "10", 
                        "price" : "1",
                        "imagePath" : "874346932.jpg",
                        "productName" : "Drop the Bass Shirt",
                        "productDescription" : "Shirt with \"Drop the Bass\" text on it.",
                        "dateOfCreation" : "2012-12-11 21:21:44",
                        "category" : "Apparel"},"4": { "productId" : "13", 
                        "price" : "499.99",
                        "imagePath" : "25869087.jpg",
                        "productName" : "Numark",
                        "productDescription" : "Numark combines two motorized turntables with adjustable torque, a premium Numark mixer, real vinyl, a professional audio interface and now a powerful effects controller for hands-on manipulation of the wide range of effects built into the included Serato ITCH software. The Numark is the complete performance solution that will satisfy the most hardcore turntablist.",
                        "dateOfCreation" : "2013-02-15 19:32:31",
                        "category" : "DJ Systems"},"5": { "productId" : "14", 
                        "price" : "4.99",
                        "imagePath" : "895376074.jpg",
                        "productName" : "Glowsticks (Pack of 3)",
                        "productDescription" : "The glow sticks run on three watch-type batteries and claim to run 200 hours before needing replacement. The LEDs will probably outlast the lights if Jake and Laura's past history is any indication.<br />These sticks/flashlights have three modes:<br /><br />1.LED Flashlight<br />2.Glow Stick<br />3.Flasher<br /><br />plus OFF and there's a whistle at the end.<br />The sticks put off enough light in glow mode to read in a dark room but I don't think you'd want to read for very long at that level.",
                        "dateOfCreation" : "2013-02-15 19:37:05",
                        "category" : "Glowsticks"},"6": { "productId" : "15", 
                        "price" : "75",
                        "imagePath" : "203045722.jpg",
                        "productName" : "Chauvet DJ Bank",
                        "productDescription" : "I setup with 4 different colors of lights.  Completely programmable.",
                        "dateOfCreation" : "2013-02-15 19:38:42",
                        "category" : "Lighting Systems"},"7": { "productId" : "16", 
                        "price" : "80",
                        "imagePath" : "597008355.jpg",
                        "productName" : "Girls' Glow-in-the-Dark Top",
                        "productDescription" : "Blue glow-in-the-dark top for ladies.  Powered by 2 AA batteries.",
                        "dateOfCreation" : "2013-02-15 19:40:47",
                        "category" : "Apparel"},"8": { "productId" : "17", 
                        "price" : "5",
                        "imagePath" : "770588972.jpg",
                        "productName" : "4\" Red Supreme Glowstick",
                        "productDescription" : "4\" Red Lighstik with Lanyard attached.  Will glow up to 10 hours.",
                        "dateOfCreation" : "2013-02-21 11:57:22",
                        "category" : "Glowsticks"} }
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,549
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    Well, *THERE* is your problem!!

    You do not *HAVE* any array!!!

    Pretend you created that same structure directly in JS code. Simplified, you would have:
    Code:
    var something = 
      {
         "0" : { 
                 "productId" : "7",
                 "price" : 53
               }
      };
    That is *NOT* an array. It is an *OBJECT*. It does *NOT* have a length property.

    So when you do this:
    Code:
        var reorderResponse = JSON.parse(ajax.responseText);
        ...
        for (var i = 0; i <= reorderResponse.length; i++)
        {
            ...
            var responseProductId = reorderResponse[i].productId;
    *BAM*! You are already dead.

    You need to, instead, do this:
    Code:
        var reorderResponse = JSON.parse(ajax.responseText);
        ...
        for ( var e in reorderResponse )
        {
            var elem = reorderResponse[e];
            ...
            var responseProductId = elem.productId;
    When in doubt, just plunk the JSON code into some JavaScript, directly, to find out what you have.
    Last edited by Old Pedant; 03-19-2013 at 11:50 PM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    d'Anconia (03-20-2013)

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,549
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    I guess, if you wanted to make minimal changes to existing code, you could do this:
    Code:
        var reorderResponse = JSON.parse(ajax.responseText);
        ...
        for ( var i in reorderResponse )
        {
            ...
            var responseProductId = reorderResponse[i].productId;
    But it seems pointless to have to keep re-evaluating reorderResponse[i] all the time when you could do it once at the top of the for loop.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #10
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    K I'll try it as soon as I can. For some reason my site is down right now (I use Dreamhost as the hosting company). Thanks for the help thus far.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,549
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    FWIW, I did test this.

    Without even using JSON.parse().

    Simple minded way, but it works:
    Code:
    <!DOCTYPE html>
    <html>
    <body>
    <script type="text/javascript">
    var html = new XMLHttpRequest();
    html.open("GET","junk.json",false); // synchronous instead of async, for simplicity
    html.send();
    var txt = html.responseText;
    var obj = eval( "(" + txt + ")" ); // way to do this without JSON.parse
    for ( var e in obj )
    {
        var elem = obj[e];
        // and hacky document.write, but w.t.h., it's simple:
        document.write( elem.productId + "::" + elem.productDescription + "<br/>" );
    }
    </script>
    </body>
    </html>
    "junk.json" is, of course, your JSON just saved as a text file.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,048
    Thanks
    0
    Thanked 251 Times in 247 Posts
    You should enclose JSON.parse inside try-catch block as it throws error if the passed string is not in a valid JSON format.

  • #13
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,048
    Thanks
    0
    Thanked 251 Times in 247 Posts
    Quote Originally Posted by Old Pedant View Post
    FWIW, I did test this.

    Without even using JSON.parse().

    Simple minded way, but it works:
    Code:
    <!DOCTYPE html>
    <html>
    <body>
    <script type="text/javascript">
    var html = new XMLHttpRequest();
    html.open("GET","junk.json",false); // synchronous instead of async, for simplicity
    html.send();
    var txt = html.responseText;
    var obj = eval( "(" + txt + ")" ); // way to do this without JSON.parse
    for ( var e in obj )
    {
        var elem = obj[e];
        // and hacky document.write, but w.t.h., it's simple:
        document.write( elem.productId + "::" + elem.productDescription + "<br/>" );
    }
    </script>
    </body>
    </html>
    "junk.json" is, of course, your JSON just saved as a text file.
    Using eval instead of JSON.parse is not a good idea. Using eval is more vulnerable to attacks and is much slower.

  • #14
    Regular Coder d'Anconia's Avatar
    Join Date
    Jan 2010
    Location
    Tempe, AZ
    Posts
    149
    Thanks
    16
    Thanked 6 Times in 6 Posts
    Quote Originally Posted by Old Pedant View Post
    Well, *THERE* is your problem!!

    You do not *HAVE* any array!!!

    Pretend you created that same structure directly in JS code. Simplified, you would have:
    Code:
    var something = 
      {
         "0" : { 
                 "productId" : "7",
                 "price" : 53
               }
      };
    That is *NOT* an array. It is an *OBJECT*. It does *NOT* have a length property.

    So when you do this:
    Code:
        var reorderResponse = JSON.parse(ajax.responseText);
        ...
        for (var i = 0; i <= reorderResponse.length; i++)
        {
            ...
            var responseProductId = reorderResponse[i].productId;
    *BAM*! You are already dead.

    You need to, instead, do this:
    Code:
        var reorderResponse = JSON.parse(ajax.responseText);
        ...
        for ( var e in reorderResponse )
        {
            var elem = reorderResponse[e];
            ...
            var responseProductId = elem.productId;
    When in doubt, just plunk the JSON code into some JavaScript, directly, to find out what you have.
    I just tested this out and it seems that it is working. I do not fully understand why Javascript is unable to loop through the JSON object as if it were an array, especially when the top-dimension variables / keys are numbers (ie easily sortable). Can anyone elaborate on this in layman's terms?

    Thanks a ton, I will be able to use this syntax or something similar for future implementations of AJAX.

    Edit: Now can someone tell me why the new images are not being added to the product boxes? The product boxes were all created but no <a> or <img> tags within them it doesn't seem. It *is* possible to add or change an image source with Javascript, right?

    Also should I be giving each of the new product boxes a specific ID attribute? Or will that not be necessary?

    Edit #2: I might have to try using another browser. When I try to use the console in Google Chrome it has no luck altering images at all (including setting src to "" or a different image). Can someone else try using the console in Chrome and try altering one of the product images?

    http://ecommerce.danconia.us/index.php
    Last edited by d'Anconia; 03-20-2013 at 05:47 PM.
    Datagonia Web (My Portfolio)

    Powerful ideas for all lovers of personal and political freedom:
    Freedomain Radio
    Free Talk Live

  • #15
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,048
    Thanks
    0
    Thanked 251 Times in 247 Posts
    You appended the img object before its src is set.

    Code:
    var actualImg = document.createElement('img');
    imageLink.appendChild(actualImg); //<----you appended the <img> to the <a>
    actualImg.removeAttribute("style");
    var imgSrc = reorderResponse[i].imagePath;
    actualImg.src="products/images/" + imgSrc; //<----but you only set the img src here

  • Users who have thanked glenngv for this post:

    d'Anconia (03-20-2013)


  •  
    Page 1 of 2 12 LastLast

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •