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.
Related
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")
}
}
Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );
So this one problem has taken me on a wild goose chase for a week or so now and I am really hoping that the problem will finally be able to be solved tonight. I'm not at all experienced with Ajax or JS so I really struggle here and am still learning. Here is what I hope to achieve...
I have a basic PHP messaging system in messages.php showing all messages between two users within a DIV which automatically adds a scroll bar when you receive more messages. Here is my DIV which does this:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
/// PHP MESSAGE SCRIPT
</div>
</div>
When you send a reply, it uses this Ajax script to send that data to be processed on system/reply_system.php if it notices you are talking to an automated account, it will also send the data to system/sars_system.php to be processed, this works fine for adding, and sending back messages...
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
}
</script>
The nice gent who helped me with this script has informed me that I need to receive data back from system/sars_system.php and system/reply_system.php which basically look like this:
<?
require 'db.php';
$message = $_POST['message'];
$conversation_id = $_POST['conversation_id'];
$sarssystem = $_POST['sarssystem'];
$user_id = $_POST['user_id'];
$usr_message = str_replace("'","\\'",$message);
mysqli_query($conn,"INSERT INTO ap_messages (message_id, message, sender_id, time_sent, time_read, conversation_id)
VALUES ('','$usr_message','$user_id', NOW(), NOW(), '$conversation_id')");
mysqli_query($conn, "UPDATE ap_conversations SET time = NOW() WHERE conversation_id = '$conversation_id'");
echo json_encode('success');
?>
But I am having a real big problem trying to figure out how to do that or what data I even need to send back or how I go about coding that in to the current script? If this all works, the final aim is to automatically initiate sending the scroll bar to the very bottom of the page every time this Ajax script runs?
The ajax looks right because it is ready to receive data. In the php you can set the data to whatever you need, it could be the results of the database call. Here's a small example of sending some data back to the ajax script.
$data = array(
'status' => 'ok',
'message' => 'Customer account saved',
);
return json_encode($data);
If you know how to get whatever data you need on the server you can encode it and return it to the client.
The success method will run on the ajax object. It is passed the data and you can reference and manipulate/use it. Your code looks like it is already prepared for this:
success: function(data) { // <-- this is the data in json format from the server
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
I am running a longpolling script to grab data from the database. It was working fine until moving my script to an MVC.
I have viewed the chrome developer tool and it's showing nothing in there, but the page just carries on loading, and when I go to refresh it won't load, I have to shut down my xampp server or close my browser... Here's my script:
class SystemController extends Controller
{
public function lastbid()
{
set_time_limit(0);
// main loop
while (true) {
//get the product info
$getbidresult = ProductModel::bidprice(Request::get('item'));
// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = Request::get('timestamp');
// get timestamp of when file has been changed the last time
$lastbid = isset($getbidresult->timestamp) ? $getbidresult->timestamp : 0;
// if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
if ($last_ajax_call == null || $lastbid > $last_ajax_call) {
// put last bid info into an array
$result = array(
'bidamount' => isset($getbidresult->amount) ? System::escape($getbidresult->amount): 0,
'timestamp' => System::escape($lastbid)
);
// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
echo $json;
// leave this loop step
break;
} else {
// wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
sleep(10);
continue;
}
}
}
}
This is how I am grabbing the data with JS.
function getContent(timestamp)
{
var queryString = {
'timestamp': timestamp
};
$.ajax(
{
type: 'GET',
url: '<?php echo Config::get('URL'); ?>system/lastbid?item=<?php echo System::escape($recentitem->id); ?>',
data: queryString,
success: function(data)
{
var obj = jQuery.parseJSON(data);
$('#bidprice-<?php echo System::escape($recentitem->id); ?>').html(obj.bidamount);
getContent(obj.timestamp);
}
});
}
$(function()
{
getContent();
});
$(document).ready(function() {
});
I've looked in apache logs with no avail unless I am looking in the wrong place. Does anything in the code look out of place, It doesn't to my knowledge but I may be overlooking something.
I have the script in a foreach, so I can initiate the div, for each product.
Edit, viewed apache and mysql logs and it showing nothing. Could it be a memory leak?
I think I have fixed it with the help of someone from an external website. It was to do with the sleep()
I have fixed it using:
session_write_close();
I will do more testing to see how it hold up before reporting back. With the reason why etc.
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)