Reputation: 2023
I have a loop of li items that I send to a jquery post and inside that php file I'm trying to post to twitter. but for some reason only the only one that actually posts is 2nd item in the loop because it doesn't contain special characters.
<ul id="twitter-preview" class="list-group">
<li id="post-1">this is my "first line" of the ul list...</li>
<li id="post-2">and this is my 2</li>
<li id="post-3">last line just as a "happy face" like so :) and it broke too</li>
</ul>
$('#btnSend').on('click', function(){
var preview_size = $("#twitter-preview li").size();
var tweet = '';
for(i= preview_size; i > 0; i--)
{
tweet = $('#post-' + i).html();
postTweet(tweet);
}
});
function postTweet(value)
{
$.post( "sendtweet.php", {"tweet" : value }, function() {});
}
so that sendtweet.php file does this:
$tweet = strip_tags($_POST['tweet']);
require_once('includes/TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "xxx",
'consumer_key' => "xxxx",
'consumer_secret' => "xxx"
);
$twitter = new TwitterAPIExchange($settings);
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$requestMethod = 'POST';
$postfields = array(
'status' => $tweet );
$twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
I have no idea why the second "li" element posts to twitter and the first and third don't and i get no errors from the console..
EDIT: I just tested and the problem is if the string has double quotes or any html code it breaks, that's why its sending the line without it. So how should I send a string with html code and for it not to break?
EDIT2: here's an example of what works and what doesn't:
Doesn't work when the text is:
This is just "a test" of a string that wouldn't not work because of the "special" characters...
But this does:
This line would post just fine because i dont use any special characters.
Upvotes: 0
Views: 113
Reputation: 9614
You're not concatenating the values to your tweet variable
You need to escape the string, I found this function below here on SO, Escaping Strings in Javascript
function addslashes( str ) {
return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
$('#btnSend').on('click', function(){
var preview_size = $("#twitter-preview li").size();
var tweet = '';
for(i= preview_size; i > 0; i--){
tweet += addslashes($('#post-' + i).html());
postTweet(tweet);
}
});
Upvotes: 1