Using AJAX for GET data from other server on Mouse Over - php

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

Related

Page get stuck when using AJAX

I'm using AJAX to present calculation results.
I invoke a PHP file that returns the results, and then I present it on the web page.
Sometimes the calculation takes a long time, and the page gets stuck until the AJAX call has returns the results.
Is there a way to use ajax, and still get the ability to perform other actions on the web page, and don't have to wait until the AJAX call has returned.
I'm using this AJAX call function( a standard function as i know).
function GetCalculation(str)
{
var result ;
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)
{
result = xmlhttp.responseText ;
}
}
xmlhttp.open("GET","GetRouts.php?q="+str,false);
xmlhttp.send();
result = xmlhttp.responseText ;
return result;
}
Yes, just pass true as the third parameter to open, then process the result in the onreadystatechange event instead.
Ajax is async if you need your javascript to work with the data send by the request you need to wait for the callback. If you dont need to work with the data from the request ( for example animate something etc...) you can just write your code outside of this function.

Constructing a more efficient javascript user-based chat

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?

How to capture the output of a php from javascript

I have written few php files which sit in a server. The output of the php would be as follows:
172.xx.xx.xx/myphpfile.php?arg="abc"
Output
{
status: "ok",
result: "asdsdf"
}
My requirement is to call this php api (172.xx.xx.xx/myphpfile.php?arg="abc") from my javascript, parse the output and draw a chart in the page. To summarize the following are my doubts.
How to call a remote php file from javascript?
How to capture the output of a php file in a javascript?
Remote PHP? Due to the same origin policy you have to write the PHP so it emits JSONP. (That link also explains how to use it from JS).
Alternatively, and with more limited browser support, use CORS with XHR
First of all, javascript is client-side and php is server-side. The web servers outputs text to your browser and it doesn't know about server techniques used.
For fetching and manipulating the data, have a look at jQuery and jQuery ajax
Both can easily be done with javascript (and even easier with jQuery). If your resulting page is in JSON format (which it appears to be), you can simply do..
$.getJSON('172.xx.xx.xx/myphpfile.php', 'arg=abc', function(obj){
alert(obj.status);
});
More info: http://api.jquery.com/jQuery.getJSON/
If the API file is not on your server
If the API is not on the same domain as your page with the JS, you will need to create your own PHP page to read the remote file, and dump its contents locally to the domain.
getJson.php
die(file_get_contents('172.xx.xx.xx/myphpfile.php?arg='.$_REQUEST['arg']));
JS
$.getJSON('gtJson.php', 'arg=abc', function(obj){
alert(obj.status);
});
You have to use Ajax.
Avoid the classic method, prefer using a framework like jQuery or ExtJS, it will be easier and cross-browser.
http://api.jquery.com/jQuery.ajax/
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Ajax
Here is the code which I use
<script type="text/javascript">
//Global Variables
var xmlHttpFP;
if (window.ActiveXObject)
{
xmlHttpFP = new ActiveXObject("Microsoft.XMLHTTP");
}//End if
else
{
xmlHttpFP = new XMLHttpRequest();
}//End else
//Function To fetch Data From Server
function LoadFPSummary()
{
xmlHttpFP.open("GET","172.xx.xx.xx/myphpfile.php?arg='abc'");
xmlHttpFP.send();
document.getElementById("response").innerHTML = xmlHttpFP.responseText;
}
xmlHttpFP.send(null);
</script>
AJAX is the tool you need.
Read more here.
You have to move AJAX technology
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("172.xx.xx.xx/myphpfile.php?arg=abc",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Get from PHP</h2></div>
<button type="button" onclick="myFunction()">Load</button>
</body>
</html>

HTML / AJAX / PHP synchronous harmony? Could asynchronous ever work?

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?

Why is this Javascript not triggering an Ajax event?

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

Categories