This might be a big question, but I find the Twitter developer website even more confusing than the Facebook developers site. So after finishing the Facebook API, I'd like to do some more research and find out how the Twitter API works.
What I want to do is make a basic application that could read and display a logged in users Twitter home feed, and publish a Tweet to their profile. But first things first, how do I read and show a users feed?
First off I'll have to authenticate a user and my application. Could anyone show me an example on that with code that I could read up on?
Then I'll have to read that users feed. This is done by sending a GET request to /statuses/user_timeline.json, but how do I do this in code? How do I receive the response, and lastly how can I display that to a user?
I know Facebook had an example on their webpage which walked you through step by step a process like this (with code), but do Twitter have anything like that? If not, could anyone who has a clue give me a little guide and some code?
Now, if you know/ have the time to respond further, I would like to know how I can publish something to a users stream. I assume it's done by sending a POST request to something, but I haven't read up on that yet. If you know, please feel free to add it to your answer. If not, no stress. Reading the stream is the most important.
So, thanks for taking the time to read through this and hopefully someone knows how to do this/ where to read up on this. Thanks in advance.
Aleksander
I use PHP to get a users tweets. I'm presuming it could be done with JS too.
Here is what I use:
function getTweets($userid,$x){
$url = "http://api.twitter.com/1/statuses/user_timeline/$userid.xml?count=$x";
$xml = simplexml_load_file($url) or die('Could not get tweets');
echo '<ul>';
foreach($xml->status as $status){
echo grabTweetData($status);
}
echo '</ul>';
}
function grabTweetData($status) {
$id = $status->id;
$user = $status->screen_name;
$text = twitterify( $status->text );
$timestamp = $status->created_at;
$date = substr($timestamp, 0, 10).', '.substr($timestamp, -4).' at '.substr($timestamp, 11, 5);
$tweet = '<a href="https://twitter.com/'.$user.'/status/'.$id.'"><li>';
$tweet .= '<div class="ttext">'.utf8_decode($text).'</div>';
$tweet .= '<div class="tdate">Posted on: '.$date.'</div>';
$tweet .= '</li></a>';
return $tweet;
}
function twitterify($ret) {
//links #tags and #users
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" >\\2</a>", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" >\\2</a>", $ret);
$ret = preg_replace("/#(\w+)/", "<a href=\"http://www.twitter.com/\\1\" >#\\1</a>", $ret);
$ret = preg_replace("/#(\w+)/", "<a href=\"http://twitter.com/search?q=\\1&src=hash\" >#\\1</a>", $ret);
return $ret;
}
If you're just getting started with APIs you should check out Temboo. Temboo makes APIs easier to work with by letting you experiment with thousands of API calls in your browser, and then generating source code for the API calls you want in the language of your choice (Java, iOS, Android, PHP, Ruby, Python, Node.js). You can also generate curl requests to the Temboo API if you're using Javascript.
Temboo's Twitter support, which will help you do everything you mentioned above, is here: https://www.temboo.com/library/Library/Twitter
(Full disclosure: I work at Temboo).
Related
I have a php code as shown below in which there is an if condition.
php:
if(mysqli_num_rows($result1) > 0){ // Line X
while($row = mysqli_fetch_array($result1)){
if($row['open'] == "true") {
if(!isset($_SESSION['admin'])) {
$message = "user " . $row['user_name'] . " is currently editing the form. Want to take over ?"; // Line B
echo "<script type='text/javascript'>if(confirm('$message')) { } else { };</script>"; // Line A
}
break;
}
}
}
I was able to integrate $message at Line B.
I am wondering what changes I should do at Line A so that I can integrate the following code in the curly braces of the if(confirm('$message') block:
$username = $_SESSION['user_name'];
$open="true";
$write="1";
$stmt=$connect->prepare("UPDATE trace_users SET write=0 WHERE write=1"); // revoke write access of all users
$stmt=$connect->prepare("UPDATE trace_users SET open=?, write=? WHERE user_name=?");
$stmt->bind_param('sss', $open, $write, $username);
$stmt->execute();
Unfortunately user1950349, this is a bit more complex than it may seem because your idea is closer to how a desktop app would where there is a message loop which allows the code to respond to user input. But with a webpage generated by php and sent over the internet, we do not have a message loop to work with. Thus, we have figure out a way to get the server and the user's computer to message back and forth without any additional webpage loads.
This is where AJAX would come into play; however, an explanation of how to use that for your use case would depend on how you implement AJAX. For instance, you might use jQuery or some other javascript library.
It is a good practice if you avoid mixing two different languages together.
When mixing these two the complexity of your code increases.
Since you need the answer here you go
echo "<script type='text/javascript'>if(confirm(" . $message . ")) { } else { };</script>";
Inside echo's double/single quotes(" / ') everything is considered as a string, so to access your PHP variable you need to use the concatenation method to use that PHP variable.
if(confirm(" . $message . "))
UPDATE
You need to follow the same steps, as described above. You need to use the string concatenations.
But that will be very complex and as well as very difficult to make debugging.
You can use a better approach using XHR request or you can design the PHP code in a better way to use it with your JavaScript code.
Good Morning all, firstly I must confirm this first. I am not a programmer but have basic knowledge of PHP etc from my teenage years. I am a commercial bee farmer that runs an eCommerce Magento website selling live bees & queens. As we are seasonal it is important our website functions correctly.
We recently changed our payment processor to UTP - Universal Transaction Processing whom offered us Magento to seamlessly integrate our payment for Debit / Credit cards. Unfortunately this has not been the case and our customers have been complaining they are unable to make payment.
After weeks of trying to replicate the issue I managed to replicate it consistently in IE 11 (Sorry I deal with people that use this!). It would load a blank page on transfer from my checkout page.
I widdled it down to the following code
echo "<script>document.onreadystatechange = () => {document.getElementById('redirect').submit();}</script>";
My understanding is IE11 has dropped support for this document.onreadystatechange
I modified the code to
echo "<script>document.getElementById('redirect').submit();</script>";
Now I don't believe this is an ideal solution as some browsers are transferring it too early before its read all the form data resulting in errors when payment page is reached.
Is anyone able to offer a solution to this? We are loosing so much custom, it is extremely important to us (being seasonal). Its our only opportunity to make money to survive through winter. This should be UTP's obligiation to fix but they are claiming there is NO issue yet I was able to replicate it multiple times on different platforms, I even set up a FRESH Magento install to prove it to them and they still deny any issue! I am going to and from a company denying there is anything wrong.
Would really appreciate some help in this mmater, here is the full code for this section.
public function redirectPayment() {
$this->log('Redirecting user for payment');
// Add hosted parameters to the generic order information
$session = $this->session->getData();
$req = array_merge(
$session[self::_MODULE]['req'],
array(
'redirectURL' => $this->getOrderPlaceRedirectUrl(),
'callbackURL' => $this->getOrderPlaceRedirectUrl(),
'formResponsive' => $this->responsive
)
);
// Comment session data
$this->log($this->commentSessionData());
$req['signature'] = $this->createSignature($req, $this->secret);
// Always clear to prevent redirects after
$this->clearData();
echo "<form id='redirect' action='" . self::HOSTED_URL . "' method='POST'>";
// Get session stored keys for a hosted request
foreach ($req as $key => $value) {
echo "<input type='hidden' name='$key' value='$value'/>";
}
echo "</form>";
echo "<script>document.onreadystatechange = () => {document.getElementById('redirect').submit();}</script>";
}
I'll try to be thorough and brief here. I am currently working in Joomla for the first time, but I've developed before. I am using Joomla 3.4. What I am trying to do:
A user signs up for our newsletter through a specific page that directs them to a coupon.
The next page shows them the coupon and has an email tag in the URL (i.e. &email='email')
I am trying to code within a module to parse out that email and send a copy of the coupon to that users email automatically.
I can't use a general automatic email when any user subscribes, because only users that sign up from that specific page will get the coupon. I have turned all text filtering off and am using basic module editor. When I save the module, the code shows just fine in the edit box. When I viewed the source of the page, that script tags would still be there, but the code would all be blank. I have now gone into phpmyadmin and can edit the module directly there. Now, the script is showing up just fine.
I've tried many different fixes, including adding a jQuery($) function load in order to bypass any issues with mootools. Wondering if it was an issue with Javascript, I cleared the script and made a simple alert("Testing..."); script that fired just fine on the page. This means that there must be something within my full script that is not working correctly. Any help or other ideas would be wonderful. I have spent over a day on this already and am at wits' end. Here's the code:
<script type="text/javascript">
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec (window.location.search))
$recipient = decodeURIComponent(name[1]);
}
$mailer = JFactory::getMailer();
$config = JFactory::getConfig();
$sender = array(
$config->get( 'config.mailfrom' ),
$config->get( 'config.fromname' )
);
$mailer->setSender($sender);
get('email');
$mailer->addRecipient($recipient);
$body = '<h2>Thank you for joining our mailing list!</h2>
'<div>Here is your coupon for a FREE 8" 1-topping pizza at Goodfellas!'
'<img src="http://www.goodfellas309.com/main/images/pizzacoupon.jpg" alt="pizza coupont"/></div>';
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setSubject('Your Free Pizza!');
$mailer->setBody($body);
$send = $mailer->Send;
if ( $send !== true ) {
echo 'Error sending email: ' . $send->__toString();
} else {
alert("An email with your coupon has been sent to you! Thank you for joining our mailing list!");
}
');
</script>
I have even attempted an inline PHP parse through Joomla with this code wrapping the javascript:
<?php
$document = JFactory::getDocument();
$document->addScriptDeclaration('
-Javascript here-
');
?>
I've always loved StackOverflow, and the answered questions have gotten me out of so many jams. I just can't find the answer to this anywhere. Thanks for your time!
Put the following inside your module.
<?php
// Get the email from the url
$jinput = JFactory::getApplication()->input;
$recipient = $jinput->get('email', '', 'string');
$mailer = JFactory::getMailer();
$config = JFactory::getConfig();
$sender = array(
$config->get( 'config.mailfrom' ),
$config->get( 'config.fromname' )
);
$mailer->setSender($sender);
$mailer->addRecipient($recipient);
$body = '<h2>Thank you for joining our mailing list!</h2>'
.'<div>Here is your coupon for a FREE 8" 1-topping pizza at Goodfellas!'
.'<img src="http://www.goodfellas309.com/main/images/pizzacoupon.jpg" alt="pizza coupont"/></div>';
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setSubject('Your Free Pizza!');
$mailer->setBody($body);
$send = $mailer->Send;
if ( $send !== true ) {
echo '<script type="text/javascript">Error sending email: ' . $send->__toString() . '</script>';
} else {
echo '<script type="text/javascript">alert("An email with your coupon has been sent to you! Thank you for joining our mailing list!");</script>';
}
Note: Depending on where you're putting this code you might need an extension like this one to make the php run.
Hopefully someone can assist with this question.
I am looking for simple JavaScript code that will update the a href link url and display it on a static HTML page, based on IP address from which the access request came.
The good thing is – the IP will be static and fixed, it will be the same number, which I already have.
In other words, if I access the same page from different IP addresses, the page will display different link url based on that.
While I might be wrong, my understanding is this can be scripted using ‘if else’ logic – if a specific IP address is detected and matched, the JS rewrites the link address.
Here is my logic below. Sorry, I don’t know much of the JavaScript syntax and used the construct below as a hypothetical example (its probably a total wreck since I didn't use the right syntax and whatnot), but this should give the general idea:
**if (location.referrer.ip('123.45.67.89.00') > -1)**
**document.write.href = 'xxx.com';**
**else if (location.referrer.ip('123.98.76.54.00') > -1)**
**document.write.href = 'yyy.com';**
**else**
**document.write.href = 'zzz.com';**
It is my understanding that since I will be using a single IP address in the formula, the following code can be omitted:
**else if (location.referrer.ip('123.98.76.54.00') > -1)**
**document.write.href = 'yyy.com/';**
Leaving only something like this
**if (location.referrer.ip('123.45.67.89.00') > -1)**
**document.write.href = 'xxx.com';**
**else**
**document.write.href = 'zzz.com';**
Again, this might not be the correct approach altogether and a way more sophisticated solution will be needed, therefore I hope that some of you with coding expertise can provide some assistance. Just to be clear - the script should NOT redirect the page but only update the url behind the link displayed on it instead.
I know there are several technologies already out there that can offer the solution, but my task is to get this running on the client side in the browser; I am not allowed to use server side technologies like Dot.NET, ASP, JSP, or anything other than JavaScript and static html.
Can someone please advice if this can be done this way? Basically, I just need to know if the approach I described above would work and if yes, what is the syntax for 'if' and 'else' lines.
Greatly appreciate any help, Thank YOU!
JK
I went looking for an answer to the same question just today and couldn't find anything. After a bit of tinkering I figured out a solution and registered on this site just to share it.
In my particular situation I was building my website to provide different href's based on the IP, but more specifically whether it was a local IP (192.168.x.x) or an external IP. Objective was to circumvent the NAT loopback problem (external IP address not accessible when connected to the same IP locally)
first off, we're going to use php so rename the file from extension .html to .php, then add this anywhere in your code and just replace the IP with whatever IP you're searching for
<?php
$ipaddress = getenv('REMOTE_ADDR');
if (fnmatch("192.168.*", $ipaddress)) {
echo 'This button is for local IP';
$link = 'http://192.168.2.40:8080';
} else {
echo 'This button is for external IP';
$link = 'http://www.myddns.com:8080';
}
?>
One weird thing I noticed about this is that I couldn't have the link be an image inside the above php tags, so I worked around that by including this after:
<img src="image/pic.png" onmouseover="this.src='image/picMouseOver.png'" onmouseout="this.src='image/pic.png'" border="0" alt="Link">
Note that this code works fine when loaded to a proper web server, but when just double clicking and testing directly in chrome it won't work. Just be aware of that (i.e. you will have to put it on your webserver or install php for windows to test it)
That answers your question... but on a related note I wanted to share something else.
So I have multiple domains that link to the same site, but wanted links to point to the same domain you came in on originally. So for that reason I was stuck using relative links and not the full URL (i.e. so if you found the website from www.website1.com, buttons wouldn't send you to www.website2.com\link.html)
I wanted to figure out how to make a relative link to a different port but learned it couldn't be done without hardcoding the domain. So I combined what I just did above with the instructions here:
Relative URL to a different port number in a hyperlink?
and wrote this method to change the URL just after the page loads, so hovering over the link or doing "Copy Link Location" will get the updated URL with the port number:
<html>
<head>
<script>
function setHref1() {
document.getElementById('modify-me').href = window.location.protocol + "//" + window.location.hostname + ":32400/web/index.html";
}
</script>
<?php
$ipaddress = getenv('REMOTE_ADDR');
if (fnmatch("192.168.*", $ipaddress)) {
// echo 'This button is for local IP';
$link = 'http://192.168.2.40:8080';
$id = '';
} else {
// echo 'This button is for external IP';
$link = 'http://www.myddns.com:8080';
$id = 'modify-me';
}
?>
</head>
<body onload="setHref1()">
</body>
</html>
edit:
You might also find this code to display visitors IP addresses interesting:
<html>
<head>
<title>What is my IP address?</title>
</head>
<body>
<?php
if (getenv('HTTP_X_FORWARDED_FOR')) {
$pipaddress = getenv('HTTP_X_FORWARDED_FOR');
$ipaddress = getenv('REMOTE_ADDR');
echo "Your Proxy IP address is : ".$pipaddress. "(via $ipaddress)" ;
} else {
$ipaddress = getenv('REMOTE_ADDR');
echo "Your IP address is : $ipaddress";
}
?>
</body>
</html>
source: http://www.cyberciti.biz/faq/how-to-determine-retrieve-visitors-ip-address-use-php-code-programming/
I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data