I have a bug in my code somewhere but can’t see what I have done wrong.
What I have is a hidden input of facebook user id’s which is populated via a jQuery UI autocomplete:
<input id="fbid" type="hidden" value="12345, 567890, ">
I then have a jQuery function which runs when the link is clicked to post to the walls of the friends.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '12345678', // App ID
channelUrl : '/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.login(function(response)
{
if (response.authResponse)
{
$("#send-voucher").click(function() {
// Post message to friend's wall
var opts = {
message : 'This is the message',
name : 'This is the name',
link : 'http://www.opticalexpress.co.uk',
description : 'This is the description',
picture : '/voucher_valid.png'
};
var referees = $("#fbid").val();
// remove last comma and space from the end of the string
referees = $.trim(referees);
referees = referees.substring(0, referees.length - 1);
var referee = referees.split(',');
referee.each(function() {
FB.api('/'+ referee +'/feed', 'post', opts, function(response)
{
if (!response || response.error)
{
alert('Posting error occured');
}
else
{
alert('Success - Post ID: ' + response.id);
$("#send-voucher").hide();
$("#voucher-sent").fadeIn('slow');
}
});
});
});
}
else
{
alert('Not logged in');
}
}, { scope : 'publish_stream' });
};
When I click to send the vouchers, the error is from the alert dialogue in my else statement above:
Posting error occured
I added in another alert to see why this was happening after the opening of the loop:
$.each(referee, function() {
referee = $.trim(referee);
alert(referee); // new alert for debugging
....
What this alert outputs surprised me as the value of referee is 12345, 567890 (same as the hidden input but with trailing space and last comma removed).
Therefore, jQuery doesn’t seem to be splitting it correctly but it runs the loop the correct number of times as the alert box pops up twice telling me the referee and then the error. (both alert boxes show twice just to clarify). Incase this was a coincidence I tried adding more id’s to the hidden input and can confirm that the alert boxes are showing the same amount of times as the number of id’s.
So I was wondering what I had done wrong since the loop runs the correct amount of times but the comma separated id’s don’t seem to be split at all.
There are a couple of problems with your code. As mentioned by others, you are looping an array using a non-existing
.each()method. You can use a standardfor()loop instead. Also it’s much more efficient stripping white space and excess commas using regular expressions.Here’s a simplified example, also available at http://jsfiddle.net/hJQ6W/