How to post a tweet using Codebird PHP from pop-up window - javascript

I am trying to allow visitors to my site to post a tweet with an image directly from the site. I am using Codebird PHP library to accomplish this. So far everything is working correctly, however there is no preview of the post before it gets posted to the user's account. Currently, it just posts directly to their account as soon as they click the button.
What I would like is to have it pop-up a small window where it will ask them to log in if they aren't logged in yet, or it will show a preview of the tweet and allow them to click the "Tweet" button if they are logged in like in this image:
Here's my PHP:
function tweet($message,$image) {
require_once('codebird.php');
\Codebird\Codebird::setConsumerKey("MYCONSUMERKEY", "MYCONSUMERSECRET");
$cb = \Codebird\Codebird::getInstance();
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$reply = $cb->media_upload(array(
'media' => $image
));
$mediaID = $reply->media_id_string;
$params = array(
'status' => $message,
'media_ids' => $mediaID
);
$reply = $cb->statuses_update($params);
}
tweet("Tweet tweet","assets/tweet.jpg");
And here's my Javascript/HTML:
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function(html) {
alert('Success!');
}
});
}
<button class="download-share" onclick="postTweet()">Download and Share</button>

In the button click, you need another function that open the popup along with a tweet button.
Add the click event listener as postTweet to the new tweet button.
I created a sample snippet. Check it below.
To show the real time preview, you need to add the keyup event listener to the textarea which should copy it's value and add it as the innerHTML of the preview pane.
function openTweet(){
document.getElementsByClassName("preview")[0].style.display="";
document.getElementById("tweetPr").innerHTML = document.getElementById("tweet").value;
document.getElementById("tweet").addEventListener("keyup",
function(){
document.getElementById("tweetPr").innerHTML = document.getElementById("tweet").value;
});
document.getElementsByClassName("download-share")[0].style.display="none";
}
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function(html) {
alert('Success!');
}
});
}
<div style="display:none;" class="preview"><textarea id="tweet"> </textarea><div id="tweetPr"></div><button onclick="postTweet();">Tweet</button></div>
<button class="download-share" onclick="openTweet()">Download and Share</button>

First things first, you(codebird) are using the twitter API to post to twitter, which makes use of the statuses/update endpoint in the API. This call is a server to server call, ie from the server where your files are hosted to the twitter server.
https://dev.twitter.com/rest/reference/post/statuses/update
There are 2 possibilities i see for you to accomplish what you have in mind
-first would be to use twitters web intent system with which you can send the tweet as a query string which would bring up the popup provided you have included the twitter js files
https://dev.twitter.com/web/tweet-button/web-intent
-second if thats not really your style then you could try something like what #ceejayoz mentioned making a new window created by you recreating the necessary inputs as shown in the picture and follow the same procedure you have now
Now to your question, Since you have an image the web intent option will not work, but if its a link with an image( twitter cards ) then i think the twitter bots should be able to read through the page and show you a preview in the popup provided you have the right meta tags on the linked page

Try use the function window.open
https://www.w3schools.com/jsref/met_win_open.asp
function postTweet() {
$.ajax({
type: "POST",
url: 'tweet.php',
data:{action:'call_this'},
success:function() {
success = true
}
});
if(success)
{
window.open('tweet.php', "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400")
}
}

Related

Ajax call to submit text into database don't work

I have a page where users can put comments below photos, everything works fine in php, comments go to the database and displayed below the photo.
Now I'm trying to make it work with ajax but I have some troubles.
I have an javascript document with this:
$(document).ready(function(){
$("#btnSubmit").on("click", function(e){
var update = $("#activitymessage").val()
$.ajax({
method: "POST",
url: "./ajax/save_comment.php",
//data: { update: update}, - first version, not correct
data: { activitymessage: update},
datatype: 'json'
})
.done(function(response) {
console.log("ajax done");
console.log (response.message);
var ht = "<li>" + update + "</li>";
$("#listupdates").append(ht);
});
e.preventDefault();
});
});
The php page (save_comment.php) where I tell what to do with the input text:
<?php
spl_autoload_register(function ($class) {
include_once("../classes/" . $class . ".class.php");
});
$activity = new Comment();
if (!empty($_POST['activitymessage'])) {
$activity->Text = $_POST['activitymessage'];
try {
//$activity->idPost = $_GET['nr'];
//$activity->idUser = $_SESSION['user_id'];
// with this it works, but not yet correct
$activity->idPost = 66;
$activity->idUser = 3;
$activity->SavePost();
$response['status'] = 'succes';
$response['message'] = 'Update succesvol';
} catch (Exception $e) {
$error = $e->getMessage();
$response['status'] = "error";
$response['message'] = $feedback;
}
header('Content-type: application/json');
echo json_encode($response);
}
There is also the file Comment.class.php with the 'Comment' class and the function SavePost(). This works without ajax, so I assume the function is correct.
What works
the comment (var update) is printed on the screen into the list.
The console says : "ajax done"
What don't work
The input text don't insert into the database (and disappears when page refresh)
The console says: "undefined" (there must be something wrong with the 'response I use in this function)
I hope you guys can help me out. Thanx
update
I changed the: data: { activitymessage: update} line in the js file, and set manually values for the $activity->idPost = 66; $activity->idUser = 3; And everything works !
Only one thing I want to get fixed
the values of the $_GET['nr'] and $_SESSION['user_id'] are now set manually. Is this possible to get these automatic?
The $_GET['nr'] is the id of the page were the photo is and the comments. In this way I can make a query that returns all comments for this page.
The $_SESSION['user_id'] is the id of the user,so I can echo the username and profile photo.
You are sending data with the key being update not activitymessage
Change data to:
data: { activitymessage: update}
Or change $_POST['activitymessage'] to $_POST['update']
Also you have no $_GET['nr'] in url used for ajax. Nothing shown would help us sort that out but you would need the url to look more like:
url: "./ajax/save_comment.php?nr=" + nrSourceValue,
Not sure why you need to use $_GET['nr'] and don't use $_POST for that also and and nr property to data object being sent

Building query string GET vars dynamically

I'm head below water on this, using Laravel I have a search page of which ajax calls a url and updates the html for filter by the way of html links which contain get vars ($(this).attr('href'); which contains ?var=test sent via ajax) to return filtered results. As ajax this doesn't update the url I'm using history.replaceState to update that.
Now here's my issue, the links which be shown as buttons (using BS) - so my link href will include the ?thisbuttonvar=whatever BUT if that get var already exists then the link href should not include ?thisbuttonvar=whatever it should remove it
I have created a function to try to handle this as follows (sorry I can't get it to paste properly):
function href_append_query($param) {
parse_str($_SERVER["QUERY_STRING"], $query_array);
if (array_key_exists(current(array_keys($param)), $query_array))
{
$key = current(array_keys($param));
if ($param[$key] == $query_array[$key])
{
unset($query_array[$key]);
}
}
else
{
$query_array = $query_array + $param;
}
$query = http_build_query($query_array);
return '?' . $query; }
The issue with this is when I do a
#foreach ($category->subCategories()->get() as $sub_category)
<li><a class="search-filter" href=<?=href_append_query(['sub_category' => $sub_category->sub_category_url])?>>{!! $sub_category->sub_category !!}</a></li>
It works for the first link, but all the rest of my href's come back the same (as the first one that enters the function)
Can anyone assist in getting this function to work so the foreach link has the appropriate href OR an entirely different "easier" way all together :)
My jQuery if it helps paint a better picture
$(document).on("click", '.search-filter', function(e) {
e.preventDefault();
$('#spinner-modal').modal('show');
$('#spinner-modal p').html('<b>Searching,</b> please wait...<br />');
query = $(this).attr('href');
history.replaceState(null, null, query);
$.ajax({
type: "GET",
url : query,
success : function(data, status){
$('#job-results').html(data);
$('#spinner-modal').modal('hide');
},
error : function(status){
console.log(status);
},
});
});

jquery ajax - setinterval to auto refresh only part of script

I have a simple chat system on my website. When I click on a user in the messages list, the data gets pulled from the database with AJAX. This script loads the PHP content of the chat:
function toggleMail(other) {
jQuery.ajax({
url: "fetch_message.php",
data:'other='+other,
type: "POST",
success:function(data){
$('#message').show();
setInterval(function(){
var scrollpos = $('#messages').scrollTop();
$('#message').html(data);
$('#messages').scrollTop(scrollpos);
}, 1000);
}
});
My PHP script fetch_message.php contains something like this:
//--Some PHP code --
<div class="mail_header"><?php xxx ?></div> //with some information about the chat
<div class="mail_messages"><?php xxx ?></div> //with the conversation itself
<div class="mail_replybox"><?php xxx ?></div> //with the textarea to respond to the chat
I want to auto refresh the chat every 1 second. The problem is that it not only refreshes the conversation itself, but also the mail_header and mail_replybox, which should of course not happen. The mail_header and mail_replybox need data from the PHP code so they are all located in the same PHP script.
Does anyone know how I can get this to only refresh the middle part, i.e. the conversation and not the other divs? I have been working on this for days and can't get it to work...
You have the setInterval at the wrong place: the server request is not repeated, and so the same data is put in the message element over and over again.
To only refresh the chat part, you could provide an argument in your server request (i.e. to PHP) so that it knows whether to produce the header, messages and replybox or just the messages.
Suggested PHP code changes:
<?php
if (!isset($_POST['refresh'])) { // check absence of new argument
?>
<div class="mail_header"><?php xxx ?></div>
<div class="mail_messages"><?php xxx ?></div>
<div class="mail_replybox"><?php xxx ?></div>
<?php
} else { // only refresh messages:
echo xxx; // only chat content, without the <div class="mail_messages">
}
?>
Then in your JavaScript:
function toggleMail(other, refresh) { // second parameter added
// define arguments to pass in the request:
var data = { other: other };
if (refresh) data.refresh=1; // define new request parameter
jQuery.ajax({
url: "fetch_message.php",
data: data,
type: "POST",
success:function(data){
var scrollpos = $('#messages').scrollTop();
if (refresh) { // only populate chat
$('#message .mail_messages').html(data);
} else { // populate the whole lot
$('#message').html(data).show();
}
$('#messages').scrollTop(scrollpos);
// Send new refresh request in 1 sec:
setTimeout(function(){
toggleMail(other, 1)
}, 1000);
}
});
}
The original call to toggleMail can stay like it is, with just the first argument.

How to return json value from php page to html page by ajax and how to show result on html page

I m validating email id in php and ajax, and want to return value from php page to html in JSON format.
I want to keep that return value in php variable for the further use.
I'm doing these all in codeigniter, and I want to show .gif image while my AJAX is processing. (Pre loader image)
AJAX/Javascript/jQuery:
function checkEmail(value_email_mobile) {
if (value_email_mobile !== '') {
//alert('te');
$.ajax({
type: "POST",
url: url_check_user_avail_status,
data: "value_email_mobile=" + value_email_mobile,
success: function(msg) {
alert(msg);
//$('#psid').html("<img src='images/spacer.gif'>");
// $('#stat').html(msg);
//
//$('#sid').sSelect({ddMaxHeight: '300px'});
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
}
PHP/Controller:
<?php
function check_email_or_mobile($param)
{
$ci = CI();
$value = $param['email_or_mobile'];
$query = "SELECT user_email , mobile FROM tb_users WHERE user_email = '$value' or mobile = '$value'";
$query = $ci->db->query($query);
if ($query->num_rows() > 0)
{
if (is_numeric($value))
{
return $res = "This mobile number is not registerd";
}
else
{
return $res = "This Email id is not registerd";
}
}
}
This is just to give you an example on how it will work.
First off, (obviously) there must the a preloader image ready inside the document. This must be hidden initially.
Second, before triggering the AJAX request, show the loading animated GIF.
Third, after the request if successful. Hide the image again inside your success: block inside the $.ajax().
Consider this example: Sample Output
PHP:
function check_email_or_mobile($param) {
// your functions, processes, blah blah
// lets say your processes and functions takes time
// lets emulate the processing by using sleep :)
sleep(3); // THIS IS JUST AN EXAMPLE! If your processing really takes time
$data['message'] = 'Process finished!';
// with regarding to storing, use sessions $_SESSION for further use
$_SESSION['your_data'] = $data_that_you_got;
echo json_encode($data); // use this function
exit;
}
// just a simple trigger for that post request (only used in this example)
// you really dont need this since you will access it thru your url
// domain/controller/method
if(isset($_POST['request'])) {
check_email_or_mobile(1);
}
HTML/jQuery/AJAX:
<!-- your animated loading image -->
<img src="http://i600.photobucket.com/albums/tt82/ugmhemhe/preloader.gif" id="loader" style="display: none;" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- <script type="text/javascript" src="jquery.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
// before the request, show the GIF
$('#loader').show();
$.ajax({
url: document.URL, // JUST A SAMPLE (url_check_user_avail_status)
type: 'POST',
data: {request: true},
dataType: 'JSON',
// data: "value_email_mobile=" + value_email_mobile,
success: function(response) {
// After a succesful response, hide the GIF
$('#loader').fadeOut();
alert(response.message);
}
});
});
</script>
My assumption is, since this is just a simple email checking, this wont really take a chunk of time. The other way is to fake the loading process.
success: function(response) {
// After a succesful response, hide the GIF
// Fake the loading time, lets say 3 seconds
setInterval(function(){
$('#loader').fadeOut();
alert(response.message);
}, 3000);
}
Let us know what part of your code is not working?
1) Check if the request flow is hitting the function checkEmail? PHP has inbuilt JSON converting utility json_encode. You could start using that.
2) If you want to store this on the server for further use, you could think about usage like
a) Storing it in Database (If really needed based on your requirements. Note: This is always expensive)
b) Session - If you would want this info to be available for all the other users too.
c) Or keep it in the memory like any of the caching mechanisms like memcache etc
3) For displaying the busy display,
// Before the below ajax call, show the busy display
$.ajax({
});
// After the ajax call, hide the busy display.
You could do this using JavaScript / JQuery on your choice.
I remember using
JSON.parse(data)
to convert JSON ino a javascript object.
Jquery has its own JSON parser btw. Something like $.JSONParse(data)

How to authenticateā€Ž a user in Joomla via AJAX / JQuery

I would like to be able to authenticate a user in Joomla via an AJAX call so I can create the error effect if the login is incorrect and redirect the user if it is correct.
I would prefer to do it through the JQuery's .ajax API.
Also, do I need to somehow initialize JQuery or it is there already you just have to use "JQuery" instead of the "$"?
Try this,
You can use Joomla's login options for Ajax login authentication.
collect your user name and password via post and set to the array.
$options = array();
$options['remember'] = JRequest::getBool('remember', false);
$data['username'] = JRequest::getVar('username', '', 'method', 'username');
$data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
$credentials = array();
$credentials['username'] = $data['username'];
$credentials['password'] = $data['password'];
$app = JFactory::getApplication();
$error = $app->login($credentials, $options);
if (!JError::isError($error)) {
// login success
}
else{
//Failed attempt
}
The above code section can be write inside any of your controller function if you have any custom component. If your are using Joomla3.x you can use com_ajax for this task .
var data = "";//set your user name and password
jQuery.ajax ({
type: "POST",
url: "index.php?option=com_ajax&task=loginauth",
data: data,
success: function(data) {
}
});
When you include the jQuery library in your application then just access it with jQuery
'$' is used for moo-tools in Joomla.For including jQuery library you can just edit the template file templates/yourtemplate/index.php
Hope its helps..

Categories