Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Quick AJAX/JSON problem

  • 21-03-2011 5:26pm
    #1
    Closed Accounts Posts: 27,857 ✭✭✭✭


    Yo,

    Quick question for ye

    I've got a test site that allows the user to enter text into a textarea, and then submit it to the database, using AJAX to post the data to a PHP script. I want the script to return both the id number used, and the timestamp.

    I have it working fine for when I'm just passing one or the other, I just echo it in the script and retrieve it from the responseText.

    But I gather if I want to pass both if them back in the same request, JSON is the way to go about it.....

    I've never used JSON before, so I'm just piecing it together as I go.

    Anywho, in my PHP script, I'm querying the database to insert the text from the form, and then selecting the timestamp, then returning the values with:

    [PHP]
    //...
    //PHP:
    $json = array();
    $json = $next_num;
    $json = $date;

    $encoded = json_encode($json);
    echo $encoded;
    [/PHP]

    Then I'm retrieving the responseText with:

    [PHP]
    //JAVASCRIPT:
    var responseArray = xmlhttp.responseText;
    alert(responseArray);[/PHP]

    This gives me the following (for example):
    {"num":55,"date":"2011-03-21 17:24:17"}

    Looks like all is good with the data. But when I try to access the elements, using the following, for example, it says "undefined":

    [PHP] alert(responseArray.num);[/PHP]

    Any suggestions? It's been annoying me, and it's such a minor issue because I don't really need to display the date all that much...... but it would be helpful to know, anyway :(

    Cheers


Comments

  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    Hey Dave,

    Never done this before, but looks like you must decode the string first?

    [php] alert(dump(json_decode(responseArray)));[/php]

    Try accessing elements like:

    [php]
    $jsonObj = json_decode($responseArray);
    echo $jsonObj ->{'date'};
    [/php]


  • Closed Accounts Posts: 27,857 ✭✭✭✭Dave!


    Ah you're using PHP to decode it, you're supposed to be able to use JSON to pass data from PHP (and other languages) to JavaScript and vice versa... that's what I was hoping to do!

    Could probably mix in some PHP too and do it your way, but I'd rather not if possible!

    Cheers though


  • Closed Accounts Posts: 27,857 ✭✭✭✭Dave!


    Ahh, figured it out!!! :D Lovely!

    FYI:

    [PHP] var responseArray = xmlhttp.responseText;

    var JSONobject = JSON.parse(responseArray);
    alert(JSONobject.num);
    alert(JSONobject.date);
    [/PHP]


    :)

    Cheers Webmonkey!


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    Oops sorry about that. Yeah I started using PHP there, forgot what I was doing ha. But I think it could be similar thing with Javascript?


  • Closed Accounts Posts: 27,857 ✭✭✭✭Dave!


    Since the thread has served its purpose, I might as well just fire another query in here :D Not directed at you Webmonkey, but if you have any insights, chip in

    Ya know how on Twitter, if new tweets come in while you're looking at the page, a message appears at the top of the page, something like "20 new tweets available", which you can click and it displays them? I'm trying to recreate something similar to that.

    I'm googling around, and it seems something called 'Period/periodical Updater' does the job...

    Can I just set an interval of (say) 1 minute, and then every minute call a function like checkTweets() ?

    It'd be a JS thing


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 105 ✭✭damoth


    Yep, do it in JS.

    Have a look at the javascript setTimeout() method.

    In particular look at the infinite loop example on this page: http://www.w3schools.com/js/js_timing.asp
    You could use something like that to check for updates every x seconds...


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    Yep Javascript. You should check out some JS libraries like JQuery.


  • Closed Accounts Posts: 27,857 ✭✭✭✭Dave!


    Alright I've got that some of it working... I've got the timer working fine, and at the moment what I've got it doing is, when the page first loads, it calls a getCount() function, which counts the number of entries in a table in the database and stores the number in a variable. Then after X number of seconds, the function is called again and a second variable gets the current number of entries. The two variables are compared, and if the numbers are not the same, then we know an entry has been added or removed.

    Next step...

    1. How on earth do I now check what records are new or not? :( I'll have to maybe create an array of the id's that are in the table currently displayed, and then somehow compare them to the records in the DB... This is turning into a greater task than I thought! Any helpful functions I should know about?

    2. My 'counting' technique isn't perfect, because if one record is added, and another is removed, then both counts will be the same even though two changes have been made. Any suggestions?


  • Moderators, Society & Culture Moderators Posts: 9,689 Mod ✭✭✭✭stevenmu


    The easy way out is to just render everything again, in your twitter example you are probably only going to want to display the last 10 tweets or perhaps all tweets for the last hour/day etc, so doing this means new entries will automatically be included and expired/deleted entries will automatically be removed.

    Failing that your idea with the arrays is probably best, simply loop over all of the IDs returned from the DB, if the current ID doesn't exist in the array then render it and add it to the array.


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    Dave! wrote: »
    Alright I've got that some of it working... I've got the timer working fine, and at the moment what I've got it doing is, when the page first loads, it calls a getCount() function, which counts the number of entries in a table in the database and stores the number in a variable. Then after X number of seconds, the function is called again and a second variable gets the current number of entries. The two variables are compared, and if the numbers are not the same, then we know an entry has been added or removed.

    Next step...

    1. How on earth do I now check what records are new or not? :( I'll have to maybe create an array of the id's that are in the table currently displayed, and then somehow compare them to the records in the DB... This is turning into a greater task than I thought! Any helpful functions I should know about?

    2. My 'counting' technique isn't perfect, because if one record is added, and another is removed, then both counts will be the same even though two changes have been made. Any suggestions?
    Do you not use Auto incrementing unique primary keys for your records? if so, you simply have to select * from database where id > last highest id and if results are returned, then you know there are new entries.

    Before - after
    id - id
    -- - --
    5 - 7
    4 - 6
    3 - 5
    2 - 2
    1 - 1

    Select * where id > 5
    result:
    2 new posts even when we removed 4 and 3.


  • Advertisement
  • Closed Accounts Posts: 27,857 ✭✭✭✭Dave!


    Webmonkey wrote: »
    Do you not use Auto incrementing unique primary keys for your records? if so, you simply have to select * from database where id > last highest id and if results are returned, then you know there are new entries.

    Before - after
    id - id
    -- - --
    5 - 7
    4 - 6
    3 - 5
    2 - 2
    1 - 1

    Select * where id > 5
    result:
    2 new posts even when we removed 4 and 3.
    Good shout, didn't think of that

    However... that will work for new entries that have been added, but what if records are deleted?

    Maybe I'm getting dragged in two different directions here.

    1. If I just go with the Twitter-type idea, then it'd probably be just the new entries that I need worry about, and your suggestion would work fine, I reckon I could do that easily enough. AFAIK in a Twitter feed, any tweets that have been deleted will only disappear once the page is reloaded?

    2. The other direction I'm being dragged in is just a regularly updated table. After the minute or so has elapsed, an updateTable() function is called, which compares the table to the database, and then fades out (jQuery) the rows that are no longer there, and fades in the new ones.

    Maybe I'll just stick with #1 for now, that's cool enough. But any suggestions on #2?

    Thanks

    ps. I'm hoping this will help me get a job! I'm in the running for a junior/graduate role using the same technologies, and I was thinking if I get this working I can stick it online and send the URL in to try and swing things in my favour...


  • Closed Accounts Posts: 27,857 ✭✭✭✭Dave!


    Well I got #1 working :) My PHP script returns the new rows, and then I just add them to the table with:
    var response = xmlhttp.responseText;
    	$(".pu_table_body").prepend($(response).fadeIn(800));
    

    Now gonna see what's the best way to handle deleted rows.

    It might be best to use seperate functions for checking for added and deleted rows, and calling them from another function, ie.
    function updateTable() {
      checkAdded();
      checkDeleted();
    }
    

    I'll see if arrays is a good solution


Advertisement