I am going to bed soon, so I will not be on until the morning, but I have been struggling with trying to find a javascript/jquery method that solves my problem. I am trying to make a chat box feature where once a post is submitting it is then echoed back out and users on both ends can see it. I know that I need to use javascript and or jquery. Right now I am using a very inefficiency system:
<script language='javascript' type='text/javascript'>
setInterval( function() {
$('#responsechat').load('echogetconversation.php?username=<?php echo $username; ?>&otherchatuser=<?php echo $otherchatuser; ?>');
}, 100);
</script>
The only reason that I am using it is because it is the only way I know how to project new posts to both users. I was wondering if someone knew a way to do this. Once a post is submitted, it fades into a div and both users can see it, not only the user who submitted it, so it is like a facebook chat in a way. I have no idea about any possible solutions, and have done research, but I could not find any that i could get to work. Any help and/or insight to what I should do next would be appreciated.
What you are looking for is ajax long pulling, also called Comet (it's a silly pun). The basic idea is simple--instead of polling the server, you send your ajax request and the server blocks on it until it gets a new message.
"Blocking" here simply means it does not send a response. You get your request then first up a thread (is that what you would do in PHP? I've only ever used node.js for this) and wait until something changes before sending the response back to the client.
Once the client has a response, it sends another request immediately.
There is one other trick: requests can time out. This means that the server should send a response back after a certain time even if nothing has updated.
This methodology is good if you have to support older browsers; if you can ignore those and stick to newer ones, you can use "websockets".
There are libraries that help you use websockets or fall back on Comet. I think the most popular one is socket.io.
Coincidentally, if you're not tied to PHP, I really suggest using a different server. node.js is a great option--it is a natural fit for this sort of problem and you can write the server-side code in JavaScript, which you already know. Even Facebook--the bastion of PHP--used a different language (Erlang) for their chat backend.
So, in summary: use socket.io. If you can, try using a different backend, although PHP is fine too.
If you don't want to use another language you can simply do it by AJAX..
Just set an interval and update the PHP-generated div's html.. and when you send a message then the reply would be the updated div -html so that both you and the user can assure that their message is posted successfully.. There's a snippet of my own chat system code : look:
function updMsg() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
xmlhttp.open("GET","Msg.php?pg=1",true);
xmlhttp.send();
}
function sendMsg()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
msg=document.getElementById('msgfrm').value;
sender='<?php echo $name;?>';
xmlhttp.open("GET","Msg.php?msg="+msg+"&sender="+sender+"<?php if(isset($_GET['a']) && $_GET['a'] = 1) { echo "&a=1"; } ?>" ,true);
xmlhttp.send();
document.getElementById('msgfrm').value="";
xmlhttp.onreadystatechange=function()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
}
function interval() {
updMsg();
t=setTimeout(interval(),500);}
interval();
This code is actually only PHP and Javascript. It's not sufficient to include the whole jQuery Library just for using the AJAX capability. right?
Related
I am searching for this from yesterday, Do not know, I am unable to implement, or going in wrong direction.
My currently ajax function which is working with local server
function tooltipajax(r_ID)
{
var str ;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('span'+ r_ID).innerHTML = xmlhttp.responseText ;
}
}
xmlhttp.open("GET","accounteditajax.php?key=" +r_ID,true);
xmlhttp.send();
}
PHP code:
print("<tr bgcolor=\"#EEEEEF\">");
print("<td class='normal' id=\"serialno\" onMouseOver='tooltipajax(this.id)'>
<a class=\"tooltip\" >Serial Number <span id=\"spanserialno\"
class=\"custom info\"></span> </a></td>");
print("<td bgcolor = \"#FFFFFF\" ><b>$serial</b></td>\n");
print("</tr>\n");
How can I get data from another server?
xmlhttp.open("GET","accounteditajax.php?key=" +r_ID,true);
I want to get from
http://iphere/filename.php
If you use use jQuery like so, this works.
function tooltip_ajax(r_ID) {
$.ajax({
url: "http://iphere/filename.php?id=" + r_ID,
context: document.body,
success: function(data) {
if(data) {
$('span' + r_ID).html(data);
}
}
});
}
That's tested with a different server and it works.
In order to retrieve data from another server using AJAX, you will need to utilize JSONP. This is due to Cross-Domain restrictions on AJAX requests. To expand on this further, if you wanted to make an AJAX request from a page located at http://test1.com, to a page / script located at http://test2.com, you would not be allowed.
Check out this article for more information: http://www.jquery4u.com/json/jsonp-examples/
Basically, JSONP involves adding a temporary SCRIPT tag to the page, which CAN load external content. The URL for this SCRIPT tag contains data, and a callback function name. The JSONP should then respond with the data, enclosed in a call to that function. Of course, the one downside is that the target server must support JSONP requests.
One alternative is using a bridge PHP script locally, that utilizes CURL to make the request, and return the information to your page, via AJAX.
For a bit more information regarding utilizing CURL in PHP, take a look at this article: http://codular.com/curl-with-php
I am using AJAX in form of jQuery for my client side scripting and twitter bootstrap for the layout, also using php for my server side scripting.
But the problem is the application runs fine on all other web explorers apart from Internet Explorer, does anyone have an idea to why this is happening, I cant even open a drop down in IE and I've tried both version 8 and 9.
here is a basic example of my jquery call to the server
function check_module() {
var option = $('#modules option:selected').attr('value');
$.post('modulesDropDown_1.php', 'option='+option,
function(data){
var obj = jQuery.parseJSON(data);
console.log(obj);
var name = $("#modules option:selected").text();
$("#moduleCode").html(obj.allInfo.code);
});
return false;
}
i have a lot of these in my code, where the im calling to the server and returning it as json to the client... for instance i have a drop down which populates another drop down below soon as a value first drop down is chosen (AJAX), but the second drop down should then update the page based on the value but it just does not work in IE.
Older versions of IE use a different mechanism for creating AJAX requests. Try something like this:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
although since it doesn't run on IE 8 and 9 that might not solve it.
It would help to see a snippet of code.
(Example from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first)
I am sending data to a PHP site using the following code:
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp= new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","addEmail.php?email="+escape(email),true);
xmlhttp.send();
xmlhttp.close;
Is there any way of making sure that the addEmail.php is being run through the XMLHttpRequest so people cant simply go to www.domain.com/addEmail.php?email=some#thing.com to make the php site eat their email and run a thousand requests on the page? Thanks in advance
The users is always able to access the php script directly, but you can protect is a bit more by adding this check to the php script:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//CODE HERE
}
Additionally, like Eugen Rieck mentioned, you could send a token.
That is fundamentally impossible.
You need to limit the number of requests per IP address on the server.
The standard way to do this, is to send some sort of (time dependent) token with the page that contains the AJAX code, then send the token together with the AJAX call. Users who directly use the AJAX URL will not know the current token value.
I've been working out the best way to bridge javascript to get data from php with Ajax.
And all while trying to keep the lines of code to a minimum and with greatest speed.
I've come up with a way to pass AJAX a value by Object so it can be altered as if it was passed by reference and then send it back. But so far, I can only do this synchronous as the data will not be available until AJAX completes.
Point is:
I've been looking for an easy way access all of my PHP content with javascript.
Build a simple javascript(GetSomePHPstuff) API if you will.
As I am a novice at web programming, I would love to hear some input and feedback on this.
This is what I have come up with.
In this example, I am sending a text value from html through javascript to ajax to php and php sends it back to ajax back to javascript back to my html page.
Here is our simple HTML type file.
TEST.html
<script language="javascript" src="ajax.js"></script>
<input type="text" id="text"/>
<input type="button" value="Return Text"
onClick="alert(ajaxReturnText(document.getElementById('text').value));"/>
Here is the ajax/javascript file.
AJAX.js
function ReturnText(input, output){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
output.value = xmlhttp.responseText;
}
}
xmlhttp.open("GET","php.php?text="+input,false);
xmlhttp.send();
}
function ajaxReturnText(input){
var output = new Object();
ReturnText(input, output);
return output.value
}
And here is the PHP file
php.php
<?php
function ReturnText($text){
return $text;
}
if($text = $_GET["text"]){
echo ReturnText($text);
die();
}
?>
This cannot work asynchronously this way. You have to understand that this line:
output.value = xmlhttp.responseText;
is going to be executed after ajaxReturnText() is done if you define it asynchronously. If you defined synchronously then ajaxreturtext() will not proceed until the request is done. To me your problem is that the code must respect the foundamental rules, in your case this is that you have to remember to define what to do after ajax inside this the "update function here:
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
output.value = xmlhttp.responseText;
/*define what to do next here*/
}
So you never call code to be executed asynch directly but insted you call it from inside the proper function, see complete code:
<html>
<head>
<script type="text/javascript">
/*to be called synch*/
function ReturnText(input){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
/*here define what to be called asynch*/
ajaxReturnText(xmlhttp.responseText);
}
}
xmlhttp.open("GET","php.php?text="+input,true);
xmlhttp.send();
}
/*to be called asynch*/
function ajaxReturnText(input){
var output = new Object();
output.value =input;
alert(output.value);
document.getElementById('test').innerHTML=
"This is the value of the object: "+input;
}
</script>
</head>
<body>
<div id="test"></div>
<input type="text" id="text"/>
<input type="button" value="Return Text"
onClick="ReturnText(document.getElementById('text').value);"/>
</body>
</html>
If you want to experience more I have a class for it: see here
You can receive server-generated events asynchronously in realtime without any problem, I did it long time ago before any AJAX. Now this way called Comet. I used frames and script techniques. Now it's better to do with ajax, but here some problems you have to solve.
You can receive data in realtime using .onreadystatechange callback with .readyState==3.
This callback generated every time when new data come from server. You need to remember last .responseText size and read new data from this point to end, then store new size.
Problem number one:
IE generate exception when you try to read .responseText before event with .readyState==4. So server part must drop connection after every event to make readyState readable and force client recreate it again (see 'long polling'). If browser is not IE you don't need to recreate connection every time. But here we face problem number too.
Problem number two:
.responseText size. It can be very big if connection used for long time. So you need to implement (events or bytes send) counter on server or client and recreate connection by counter overflow.
One more problem - timeouts. You need to disable timeout on server (see set_time_limit()) and send something insignificant (space forexample) to browser when you have no events to prevent browser timeout.
Usually you need two channels to server: upload and download. You have upload channel with jQuery or another framework but I don't sure about download. I afraid you can't use readyState==3 technique with jQuery. May be APE Framework can do it?
I have a forum of sorts, and I want to automatically refresh the posts every so often. I am using Ajax when the page loads to start and later I will implement the auto refresh. The problem I am having is (I believe) inducing a Ajax request. I have an event handler for the Ajax request to take place when I click my header (for purposes of debugging). I won't post all of my code, just the most relevant sections here, but if you want you think there is probably a problem in my code elsewhere, feel free to check out www.ethoma.com/testhome.php which sends a request to www.ethoma.com/getposts.php.
Ajax requesting function:
function getPosts(category, page, sort)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("postcontainer").innerHTML=xmlhttp.responseText;
}
}
var queryString = "?category=" + category + "&page=" + page + "&sort=" + sort;
xmlhttp.open("GET","getuser.php" + queryString,true);
xmlhttp.send();
}
My PHP page should return the correct html code through an echo call. On a side note, it is okay to embed html tags within the code I return through my PHP page (novice question)?
If you think the problem is not in this code snippet, again feel free to browse those two pages. Thanks to everyone who views/answers this question -- everyone here is very helpful.
I've looked at the live version of your site and ran it with a breakpoint in onreadystatechange. The reason you don't see anything is that getuser.php 404's.
In particular the called URL is http://www.ethoma.com/getuser.php?category=[object%20HTMLAllCollection]&page=1&sort= (I'm quite sure the category is a bug) and yields 404, onreadystatechange is then called with readyState=2 and status=404