Senne Vandenputte Senne Vandenputte - 3 months ago 17
Javascript Question

Ajax code not executing

I am building a basic social network site with a function to create groups. All my code works perfectly, except for this little piece of code that declines or approves pending members. The following PHP code displays a list of the pending members in the specific group:

if (in_array($_SESSION['username'],$moderators)){
$addMembers = "Pending members";
for($x=0;$x<$pend_count;$x++){
$addMembers .= '<a href="'.$pending[$x].'">'.$pending[$x].'</a>';
$addMembers .= '<button onclick="approveMember('.$pending[$x].')">Approve</button>';
$addMembers .= '<button onclick="declineMember('.$pending[$x].')">Decline</button>';
}
}


The onclick events should trigger the following JS scripts:

function approveMember(u){
var ajax = ajaxObj("POST", "php_parsers/group_parser.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText;
if(datArray == "member_approved"){
alert ("Member approved!");
}
}
}
ajax.send("action=approve_member&u="+u);
}


function declineMember(u){
var ajax = ajaxObj("POST", "php_parsers/group_parser.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText;
if(datArray == "member_declined"){
alert ("Member Declined");
}
}
}
ajax.send("action=decline_member&u="+u);
}


The AJAX code executes a PHP script in the background to approve/decline a member and give a response 'member_approved' or 'member_declined', which should then trigger an alert in the JS.

Now, I have about 10 of these onclick event triggers to execute some AJAX code, which are all working fine, except these approveMember() and declineMember(). They just don't want to trigger my JS scripts and I can't find out why. I am sure the problem is not in the PHP script that should be executed in the background.

Answer

You need to quote your strings, while you're at it encode your attributes.

    $addMembers .= '<a href="'.htmlspecialchars($pending[$x]).'">'.htmlspecialchars($pending[$x]).'</a>';
    $addMembers .= '<button onclick="approveMember('.htmlspecialchars(json_encode($pending[$x])).')">Approve</button>';
    $addMembers .= '<button onclick="declineMember('.htmlspecialchars(json_encode($pending[$x])).')">Decline</button>';
Comments