PDA


View Full Version : AJAX sample problem


jasharen
02-24-2008, 01:56 AM
I'm having a problem with an AJAX example I've thrown together. It works to update the DB, however the push back to the browser is not working. This is just a crude example where I'm trying to test.

HTML file
<html>
<head>
<script type="text/javascript">


if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}

function addfav(linkid) {
http.abort();
http.open("POST", "ajaxlinks.php?do=addfav&l=" + linkid, true);
http.onreadystatechange=(My_AJAX_Reciever);
http.send(null);
}
function removefav(linkid) {
http.abort();
http.open("POST", "ajaxlinks.php?do=removefav&l=" + linkid, true);
http.onreadystatechange=(My_AJAX_Reciever);
http.send(null);
}
function My_AJAX_Reciever()
{
if (http.handler.readyState == 4)
{
document.getElementById('foo').innerHTML = http.handler.responseText;
}

}

</script>
</head>
<body>
<form>
<input value="Add Fav" type="button" onclick="addfav(4)" />
<input value="Remove Fav" type="button" onclick="removefav(4)" />
<div id="foo"></div>
</form>

</body>
</html>


And the PHP file:


<?php

// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################
define('THIS_SCRIPT', 'AJAX_LINKS');


// ######################### REQUIRE BACK-END ############################
require_once('./links_global.php');

if ($_REQUEST['do'] == 'removefav')
{
$linkid = $_REQUEST['l'];
$db->query_write("DELETE FROM " . TABLE_PREFIX . "adv_links_favorites WHERE userid = " . $vbulletin->userinfo['userid'] . " AND linkid = '$linkid'");

echo '1';

}
if ($_REQUEST['do'] == 'addfav')
{
$linkid = $_REQUEST['l'];
$checkfav = $db->query_first("SELECT linkid FROM " . TABLE_PREFIX . "adv_links_favorites WHERE userid = '" . $vbulletin->userinfo['userid'] . "' AND linkid = '$linkid'");

if (!$checkfav['linkid'])
{
$db->query_write("INSERT INTO " . TABLE_PREFIX . "adv_links_favorites (userid, linkid) VALUES ('" . $vbulletin->userinfo['userid'] . "', '$linkid')");
echo '2';

}

}
echo '3';
?>


The favorites table is updated, however the echo is not coming back to the browser. Any idea's on what I'm doing wrong?

jasharen
02-26-2008, 01:22 AM
Problem solved, just had to combine AddFav and RemoveFav into one function with a single call and everything works perfectly.