#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2010
    Posts
    72
    Rep Power
    8

    php/JSON/jQuery - what am I doing wrong ?


    Can someone please tell me where I'm going wrong with my php/JSON/jQuery ?

    PHP code :
    PHP Code:
    $mostreadSelectSQL = (
    SELECT 
    pagevisit.pagenumber AS pagenumber, 
    COUNT(pagevisit.pagevisitid) AS pagecount 
    FROM 
    pagevisit 
    WHERE 
    (pagevisit.pagenumber > '1') && 
    (pagevisit.pagenumber < '300') 
    GROUP BY 
    pagenumber 
    ORDER BY 
    COUNT(pagevisit.pagevisitid) DESC, 
    pagevisit.createddatetime DESC 
    LIMIT 3
    "
    );
                
    $mostreadResult=mysqli_query($con,$mostreadSelectSQL);
                     
    while (
    $mostreadRow mysqli_fetch_assoc($mostreadResult)) { 
            
    $mostreadpagenumber $mostreadRow['pagenumber'];
    $mostreadpagecount $mostreadRow['pagecount'];
            

    $echo '
      { "mostread" : 
        [   
          { "pagenumber" : "'
    .$mostreadpagenumber.'",  
          "pagecount"  : "'
    .$mostreadpagecount.'" }
        ] 
      }
    '
    ;

    echo 
    $echo;
                  
    // closes while ($mostreadrow = mysqli_fetch_assoc($mostreadresult)) 
    jQuery code :
    Code:
    $.post etc ...,
    		   function(data,status){
    	  		var responsestr = data;
    	  		var responsestrtrimmed = data.replace(/^\s+|\s+$/g, '') ;
    			//var jsondata = JSON.parse(responsestrtrimmed);
    	  		if (responsestrtrimmed == 'error') {
    			  $("#most").hide();
    			} //CLOSES if (responsestrtrimmed = "error")
    			else { // this is json
    			  //var mostread1=(jsondata.mostread[1].pagecount);
    			  //$("#mostread1").html(mostread1);
    			  alert(responsestrtrimmed);
    			} // CLOSES else // this is json
    			return false;
    	}); // CLOSES $.post etc ...
    When this jQuery line (var jsondata = JSON.parse(responsestrtrimmed) is active, the value of the "mostread1" element is not modified and there is no javascript alert, but the rest of the page loads fine - when it is commented out, the javascript alert is as follows - please note the lack of commas.
    Code:
    {"pagenumber":"4","pagecount":"94"}{"pagenumber":"102","pagecount":"8"}{"pagenumber":"203","pagecount":"4"}
    I'm thinking that the lack of commas prevents proper JSON-parsing, but I'm unsure (1) whether this is the case, and (2) how to go about including them, as including one at the end of the following line would surely leave a hanging comma at the end, would it not ?
    PHP Code:
    "pagecount"  "'.$mostreadpagecount.'" 
    Can someone please help ?

    I would prefer to correct my own code than change to use a different approach, but advice as to improved ways of achieving my objective will be welcomed anyway, as I will then make a point of learning the new/improved method.
  2. #2
  3. No Profile Picture
    Super Moderator
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2009
    Location
    Hartford, WI
    Posts
    1,502
    Rep Power
    111
    Code:
    {"pagenumber":"4","pagecount":"94"}{"pagenumber":"102","pagecount":"8"}{"pagenumber":"203","pagecount":"4"}
    That is not valid for the JSON.parse() since parse will accept only 1 item as the first item. (Poor words, sorry.) The first item can be in an array manner and all, but you are providing 3 separate items in your post. Depending on your goal, you could perhaps just run a loop and have your script provide 1 of those items at a time.

    And just curiosity, how/where is 'mostread' defined?
    Code:
    jsondata.mostread[1].pagecount
    What is the output of 'data' before and after the line:
    Code:
    data.replace(/^\s+|\s+$/g, '')

    EDIT: Actually, if I caught the code correctly, you're not returning the value as you should be. The while() will only echo out 1 set, but since you have not displayed the '{ "mostread" : [' in your example, but have provided 3 items, you have not provided us with the code that is running. Since you want, I'm assuming, the multi-dimensional array, you will have to build that within the loop, and return it afterwards.

    A possible suggestion for a cleaner while() loop based on yours.
    PHP Code:
    while ($row mysqli_fetch_assoc($mostreadResult)) {  
      
    $return[] = array('pagenumber' => $row['pagenumber'], 'pagecount' => $row['pagecount']);
    }
    return 
    json_encode($return); 
    Last edited by Triple_Nothing; June 22nd, 2016 at 11:41 AM.
    He who knows not that he knows not is a fool, ignore him. He who knows that he knows not is ignorant, teach him. He who knows not that he knows is asleep, awaken him. He who knows that he knows is a leader, follow him.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2010
    Posts
    72
    Rep Power
    8
    Hi Triple_Nothing,

    Thank you for your reply. Apologies for the delay - I was formulating a reply to your first reply and then saw your edit when I went to send.

    Something was clearly amiss, as (a few minutes ago), the alerts started getting it together, and became as below:
    Code:
    { "mostread" : [ { "pagenumber" : "4", "pagecount" : "106" } ] }{ "mostread" : [ { "pagenumber" : "102", "pagecount" : "8" } ] }{ "mostread" : [ { "pagenumber" : "203", "pagecount" : "4" } ] }
    I'll test the code that you suggest after posting this reply. Only sending this reply now as I'm conscious that I'm slow to reply and don't want you to think that I'm unappreciative & not testing your suggested code. Will edit this reply once I've tested.

    EDIT : Your code works, and I'm now getting an array. Array is :
    Code:
    [{"pagenumber":"4","pagecount":"114"},{"pagenumber":"102","pagecount":"8"},{"pagenumber":"203","pagecount":"4"}]
    Could you possibly tell me how I should be parsing that into variables ?
    Last edited by foreverforever; June 22nd, 2016 at 12:37 PM.
  6. #4
  7. No Profile Picture
    Super Moderator
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2009
    Location
    Hartford, WI
    Posts
    1,502
    Rep Power
    111
    Whether intended or not, I love the rhyme... ^_^
    Something was clearly amiss, as (a few minutes ago), the alerts started getting it together, and became as below
    I tossed together a quick demo/sample page to somewhat mention the steps being taken.
    Demo/Sample Page: php/JSON/jQuery - what am I doing wrong ?
    No major rush on responses. I'm familiar with the quiet boredom of a forum vs. that of a chat.

    Comments on this post

    • foreverforever agrees
    Last edited by Triple_Nothing; June 22nd, 2016 at 01:29 PM.
    He who knows not that he knows not is a fool, ignore him. He who knows that he knows not is ignorant, teach him. He who knows not that he knows is asleep, awaken him. He who knows that he knows is a leader, follow him.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2010
    Posts
    72
    Rep Power
    8
    Rhyme was entirely down to untapped talent ... you should see my sonnets ... more Shakespearean than Shakespeare ... if only

    Thank you for the page of sample code - made everything just that little bit clearer, and all working now.

    I'm going to be adding extra queries to my page and may therefore muck it up again over the next few days. May I PM you to ask for further advice (if I do muck it up again) or should I post a new thread ?

    Many thanks.
  10. #6
  11. No Profile Picture
    Super Moderator
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2009
    Location
    Hartford, WI
    Posts
    1,502
    Rep Power
    111
    Feel free either way. Just a note on the side, since I'm not sure if it was truly the intended code, or just written as the idea...
    if(parsed == 'error') { cannot truly land like this. If JSON.parse() does error, it is not simply going to define 'parsed' with the string 'error'. (Unless I'm mistaken.)
    He who knows not that he knows not is a fool, ignore him. He who knows that he knows not is ignorant, teach him. He who knows not that he knows is asleep, awaken him. He who knows that he knows is a leader, follow him.

IMN logo majestic logo threadwatch logo seochat tools logo