+ Reply to Thread
Results 1 to 8 of 8

Thread: Multiple AJAX Calls

  1. #1
    learning_brain is offline x10 Sophmore learning_brain is an unknown quantity at this point
    Join Date
    Apr 2010
    Location
    UK, Midlands
    Posts
    170

    Multiple AJAX Calls

    OK - this is weird and I hope I can get some help here.

    I have managed to integrate one AJAX call into a page, which uprates an image at database level and then responds with the current rating.

    Example page is at http://www.qualityimagesearch.com/vi...p?img_id=34706

    The js in this page is as follows:

    Code:
    <script type="text/javascript">
    
        var ajaxUprate;//create ajax variable
        
        //main funtion to create XMLhttp request from event call
        function ajaxUprateCall(str)//str is value from field
        {
            //try various browsers
            try{
            // Opera 8.0+, Firefox, Safari
            ajaxUprate = new XMLHttpRequest();
            } catch (e){
                // Internet Explorer Browsers
                try{
                    ajaxUprate = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    try{
                        ajaxUprate = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e){
                        // Something went wrong
                        alert("Your browser does not support HTTP requests.");
                        return false;
                    }
                }
            }
            
            //specify url to call + variable which will be called using GET
            var url="ajax/ajax_uprate.php";
            url=url+"?uplink="+str;//add value and assign to link
            
            
            ajaxUprate.onreadystatechange=stateChanged;//function to receive data from server
            ajaxUprate.open("GET",url,true);
            ajaxUprate.send(null);
        }
        
        function stateChanged()
        {
            if (ajaxUprate.readyState==4)//check if response is ready from server
            {
                var result = ajaxUprate.responseText;//retreive data from server
                //document.getElementById("AjaxOutput").value=result;//specify output in field
                document.getElementById("AjaxOutput").innerHTML = result;//specify output in div
            }
        }
    
        
    </script>
    Then I have a button with an event call as follows:

    Code:
    <a href="#nogo" onClick="ajaxUprateCall(<?php echo $row_Image['ID'];?>)"><img src="/images/thumb-up.png" width="50" height="50" border="0" /></a>
    The php it calls (with GET variable) is

    PHP Code:
    <?php
    require_once('../Connections/discountdomains.php');  
    mysql_select_db($database_discountdomains$discountdomains) or die('Could not select db. '.mysql_error());

    $ajaxuplink=$_GET["uplink"];

    $updatequery "UPDATE images SET SUIT = SUIT +1 WHERE ID LIKE '".$ajaxuplink."'";
    $updateresult mysql_query($updatequery) or die('Could not update. '.mysql_error());

    $selectsql="SELECT * FROM images WHERE ID LIKE '".$ajaxuplink."'";
    $selectresult mysql_query($selectsql) or die('Could not select. '.mysql_error());

    while(
    $row_Image mysql_fetch_array($selectresult))
      {
        
        include(
    '../includes/rating.php');//displays small thumb up icons according to rating

      
    }
    ;

    mysql_free_result($selectresult);
    ?>
    So far, this works great!! really pleased with that BUT...

    I want to do the same with a downrate button.

    I have duplicated the javascript ajax but changed all variable names from up**** to down****

    The button event calls a different but similar php page, which simply downrates the image.


    Now although the call is working with a db update, the responsetext doesn't work with the first call.

    Is there an issue outputing to the same div id?

    Any help would be appreciated.

    All files below

    ajax_downrate.txt
    ajax_uprate.txt
    view_image.txt

  2. #2
    learning_brain is offline x10 Sophmore learning_brain is an unknown quantity at this point
    Join Date
    Apr 2010
    Location
    UK, Midlands
    Posts
    170

    Re: Multiple AJAX Calls

    Sorry - just figured my mistake - the stateChanged function is being re-defined - just changed the names and it works great.

  3. #3
    lemon-tree's Avatar
    lemon-tree is offline x10 Minion lemon-tree has a spectacular aura about
    Join Date
    Nov 2007
    Posts
    1,420

    Re: Multiple AJAX Calls

    You could really integrate all of this into one call function, one php script and one callback. For example you have a function ajaxRateCall(imageId, rateDirection) calling a PHP script with ?uplink=imageId&dir=rateDirection and then one callback stateChanged() that displays the return. Basically, this is just more efficient as it means you are not writing the same thing multiple times with only very small variations.

    Also, you shouldn't really be using mysql_*; if you don't have PDO then at least use mysqli_*. Additionally, your script is wide open to SQL injection attacks, this is very serious and could be a weak-point that allows your data to be compromised. For example, with a simple custom variable on the $_GET['uplink'] I could force it update every row of the table or potentially drop the entire table! Another example, entering % (link) uprates every image in the table and is a weakness of using LIKE; if you know the id you should just be doing a straight = evaluation.
    Again, use PDO or mysqli as they are infinitely better at providing ways to prevent these attacks. This is very serious and if you are using similar coding practices in other parts of your site (No escaping of characters) then you can consider the entire thing potentially compromised. Ideally, now that you aware of this you should close off all access to your site until you have closed every hole that is a result from bad practices, as I fear my post my make your site a target.
    Also, don't do 'or die mysql_error()', as if there is an error then it tells the user far too much detail about your server. Instead, you should log the errors in the background and just return a polite 'An error occurred' to the user.
    There are a few other things in those scripts that are weak or insecure, but you need to rewrite them all completely anyway.
    Last edited by lemon-tree; 01-07-2011 at 11:24 AM.

  4. #4
    callumacrae's Avatar
    callumacrae is offline not alex mac callumacrae is just really nice
    Join Date
    Dec 2007
    Location
    Wellesbourne, England
    Posts
    5,162

    Re: Multiple AJAX Calls

    As lemon-tree said, don't use PDO!

    A couple tutorials I would recommend - this because Misson recommended it, and this cos I wrote it :D

    ~Callum
    I can customise your phpBB board. Send me a PM.
    lynxphp - info, tutorials and scripts
    "A forum post should be like a skirt; long enough to cover the subject but short enough to keep things interesting."

  5. #5
    learning_brain is offline x10 Sophmore learning_brain is an unknown quantity at this point
    Join Date
    Apr 2010
    Location
    UK, Midlands
    Posts
    170

    Re: Multiple AJAX Calls

    Quote Originally Posted by lemon-tree View Post
    You could really integrate all of this into one call function, one php script and one callback. For example you have a function ajaxRateCall(imageId, rateDirection) calling a PHP script with ?uplink=imageId&dir=rateDirection and then one callback stateChanged() that displays the return. Basically, this is just more efficient as it means you are not writing the same thing multiple times with only very small variations.
    Good idea - This was my first attempt at actually trying to understand ajax rather than c&p, so I'm still pretty new to the whole idea.

    Quote Originally Posted by lemon-tree View Post
    Also, you shouldn't really be using mysql_*; if you don't have PDO then at least use mysqli_*.
    Hmmm - never really read up on mysqli. I don't have PDO so I'll do some googling and find out what all the fuss is about.

    Quote Originally Posted by lemon-tree View Post
    Additionally, your script is wide open to SQL injection attacks, this is very serious and could be a weak-point that allows your data to be compromised. For example, with a simple custom variable on the $_GET['uplink'] I could force it update every row of the table or potentially drop the entire table! Another example, entering % (link) uprates every image in the table and is a weakness of using LIKE; if you know the id you should just be doing a straight = evaluation.
    Arrrrgghhhh - I even have a sanitising function but didn't put it in as I was only developing - whoops! - It's in now though!

    Good point about the LIKE... - this is now an equal as suggested - I wondered why other images were changing ;D

    Quote Originally Posted by lemon-tree View Post
    Again, use PDO or mysqli as they are infinitely better at providing ways to prevent these attacks. This is very serious and if you are using similar coding practices in other parts of your site (No escaping of characters) then you can consider the entire thing potentially compromised. Ideally, now that you aware of this you should close off all access to your site until you have closed every hole that is a result from bad practices, as I fear my post my make your site a target.
    Done! I believe there are only two potential holes and first was plugged anyway.
    Quote Originally Posted by lemon-tree View Post
    Also, don't do 'or die mysql_error()', as if there is an error then it tells the user far too much detail about your server. Instead, you should log the errors in the background and just return a polite 'An error occurred' to the user.
    There are a few other things in those scripts that are weak or insecure, but you need to rewrite them all completely anyway.
    I normally only put error messages in when developing - I've now removed them and thanks for the reminder.

    Quote Originally Posted by Alex Mac View Post
    As lemon-tree said, don't use PDO!

    A couple tutorials I would recommend - this because Misson recommended it, and this cos I wrote it :D

    ~Callum
    Thank you - shame PDO isn't enabled - I need to read up more on MYSQLi.
    Last edited by learning_brain; 01-07-2011 at 03:33 PM.

  6. #6
    lemon-tree's Avatar
    lemon-tree is offline x10 Minion lemon-tree has a spectacular aura about
    Join Date
    Nov 2007
    Posts
    1,420

    Re: Multiple AJAX Calls

    You should really take up a support ticket with your host: not having PDO is essentially forcing users into bad coding. I'm sure if you ask nicely they might take it into consideration.

    Good point about the LIKE... - this is now an equal as suggested - I wondered why other images were changing ;D
    That was happening because I was passing it a %, which in the LIKE comparison is a wildcard and means it'll match everything. This means the resultant script looked like this:

    Code:
    UPDATE images SET SUIT = SUIT +1 WHERE ID LIKE '%' <--This will match every row in the table and update all of them
    If you know that you are only looking to update one row then you should really set a limit on the query, like so:

    Code:
    UPDATE images SET SUIT = SUIT +1 WHERE ID = <your_id> LIMIT 1
    This will tell MySQL to stop the query after one row has been updated, even if there are multiple matches (Which there shouldn't be though on a ID search).

  7. #7
    callumacrae's Avatar
    callumacrae is offline not alex mac callumacrae is just really nice
    Join Date
    Dec 2007
    Location
    Wellesbourne, England
    Posts
    5,162

    Re: Multiple AJAX Calls

    Ouch, you need to get your host to enable PDO! (Or move hosts)

    ~Callum
    I can customise your phpBB board. Send me a PM.
    lynxphp - info, tutorials and scripts
    "A forum post should be like a skirt; long enough to cover the subject but short enough to keep things interesting."

  8. #8
    learning_brain is offline x10 Sophmore learning_brain is an unknown quantity at this point
    Join Date
    Apr 2010
    Location
    UK, Midlands
    Posts
    170

    Re: Multiple AJAX Calls

    Quote Originally Posted by lemon-tree View Post

    Code:
    UPDATE images SET SUIT = SUIT +1 WHERE ID = <your_id> LIMIT 1
    Done - good tip - Thanks

+ Reply to Thread

Similar Threads

  1. Replies: 2
    Last Post: 03-06-2010, 11:08 AM
  2. making multiple ajax request on one page
    By wizkid in forum Programming Help
    Replies: 2
    Last Post: 12-26-2008, 02:15 AM
  3. Geek Squad Prank calls!
    By Tyler in forum Off Topic
    Replies: 4
    Last Post: 08-22-2005, 05:14 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
x10hosting free hosting for the masses
dedicated servers