Multiple AJAX Calls

learning_brain

New Member
Messages
206
Reaction score
1
Points
0
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/view_image.php?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:
<?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

View attachment ajax_downrate.txt
View attachment ajax_uprate.txt
View attachment view_image.txt
 

learning_brain

New Member
Messages
206
Reaction score
1
Points
0
Sorry - just figured my mistake - the stateChanged function is being re-defined - just changed the names and it works great.
 

lemon-tree

x10 Minion
Community Support
Messages
1,420
Reaction score
46
Points
48
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:

callumacrae

not alex mac
Community Support
Messages
5,257
Reaction score
97
Points
48
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
 

learning_brain

New Member
Messages
206
Reaction score
1
Points
0
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.

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.

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

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.
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.

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:

lemon-tree

x10 Minion
Community Support
Messages
1,420
Reaction score
46
Points
48
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).
 

callumacrae

not alex mac
Community Support
Messages
5,257
Reaction score
97
Points
48
Ouch, you need to get your host to enable PDO! (Or move hosts)

~Callum
 
Top