beginner - AJAX false and true difference? - php

function loadxmldoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.php?fname=sakthi&lname=karthiga",false);
xmlhttp.send();
}
ajax_info.php
<?php
echo( "hello"."<br>".$_GET["fname"].$_GET["lname"]);
?>
in this code i change the ajax status as FALSE but stil working same as TRUE
can u tell whats the difference b/w TRUE and false? if i change false what will going on serverside

I suppose that you are talking about the third parameter of the open function. It indicates whether the request should be asynchronous or not. In both cases the exactly same request will be sent to the server. The difference will be on the client. If you use asynchronous (which is the recommended for AJAX) the client browser will not freeze during the execution of the request and the send method will return immediately. Once the execution on the server finishes, the callback you subscribed to will be invoked.
If you set the parameter to false the send method will block and freeze the client browser during the entire execution of the request to the server. This completely defeats the whole purpose of AJAX but it is used by some people that want to use the results of the request outside of the success callback. Do not do the same mistake.
I would very strongly recommend you to always use asynchronous AJAX requests (true) and not blocking calls.

Related

Using AJAX for GET data from other server on Mouse Over

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

How to detect php server timeout on ajax request?

I want to know that suppose you did an ajax request to a page that runs PHP code. The page outputs some data (using flush() method or otherwise) but because of a 30second timeout or some other error, the php request ends.
Now when the request ends, I want to find out about it on client side and restart the request.
i.e suppose I have something like this
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==3 && xmlhttp.status==200){
document.getElementById("A").innerHTML=xmlhttp.responseText;
}
else if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("A").innerHTML=xmlhttp.responseText;
//plus some additional code to end the process
}
else if(xmlhttp.status== SOMETHING /*WHAT DO I ADD HERE TO KNOW THAT THE SERVER HAS TIMED OUT OR SOMETHING SO I CAN RESTART THE XMLHTTP CYCLE */){
//code to resend xmlhttp request.
}
}
One strategy I used was to set a timer in JS, and then clear it if the call was successful.
var myTimer = setTimeout(stuffToDoOnFailure, 6000); // 6 secs
ajaxCall(function callBack() {
clearTimeout(myTimer);
});
EDIT:
Of course, if the ajax call succeeds after 6 secs, you might end up with both stuffToDoOnFailure and callBack being executed, so you want to handle that case somehow. That depends on your app, though.

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.

Why am I having ajax communication issue?

I've trying to send some infromation to a php file and display the result returned. First of all I'm not receiving any results from php file i.e. no value in xmlhttp.responseText. Instead of responseText, I tried putting 'something else' which made no difference. But when i comment out //if (xmlhttp.readyState==4 && xmlhttp.status==200), the result briefly appears.
What have I done wrong?
Ajax code looks like this:
var div = 'display';
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
writeBack (div, xmlhttp.responseText+'something else', 'red');
}
}
xmlhttp.open("POST","update_profile2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("rr="+id);
Php code:
..
if(isset($_POST['rr']))
{
die('connection made');
}
..
Every problem I've ever had with AJAX is usually caused by trying to submit an AJAX request using a 'submit' button in a form. If you are doing that, make sure you stop the .submit() .... Also, if you use jQuery, your AJAX code will look sooooo much better :)
As others users say with jquery the code looks much better.
However I am quite sure your problem is with this line:
xmlhttp.open("POST","update_profile2.php",true);
The request above access directly the update_profile2.php and gets back the entire content of the php page, not the output elaborated by the page.
This is way you access the page without asking the web server (with the php engine) to serve it for you. And of course the http call fails so the condition && xmlhttp.status==200 blocks the execution of the next instruction that fills in the div.
use instead:
xmlhttp.open("POST","http://localhost/update_profile2.php",true);
This will send a ajax http request to apache, il will run the php page and returns the answer of the page!

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?

Categories