Category Archives: AJAX

Synchronous and Asynchronous

JavaScript itself is synchronous and single-threaded language. but you can write code in such a manner that function execution take a long time and can be interleaved with other operations.

First, let us use an analogy to understand Synchronous and Asynchronous.

Synchronous – You are in a Bus stop. When bus arrived, people will enter in a bus one by one. You cannot get into the bus until everybody in front of you gets in. and the same concept applies to the people standing behind you. This is Synchronous.

Executing something synchronously means, you wait for the task to finish before moving on to another task. Or we can say, two synchronous threads must be aware of one another, and one must execute in some way that is dependent on the other.

Asynchronous – Take household chores as an example. You put clothes to get washed and dry in a washer and dryer. Then you bake pizza in a oven. Meanwhile you are cutting veggies for salad. In this situation, couple of tasks are getting done at the same time. When the task is done. It will simply report back. This is asynchronous.

Executing something asynchronously means, you can move on to another task without waiting for the first task to get finished. The result of each task will be handled once the result is available. Or in other words, Asynchronous means two threads are totally independent, run parallely and neither one comes in each other way at the time of execution.

Try this code

// synchronous
console.log('First Task');
console.log('Second Task');
console.log('Third Task');

Output will be :-

First Task
Second Task
Third Task

The output will be First Task, Second Task, Third Task. As javascript execute one function at a time and will wait for the function to be done before moving to the “Second Task”

Now try this code. I am using setTimeOut method here. The function will be processed in the background, while your program is doing other things.

// asynchronous
console.log('First Task');
setTimeout(function(){
   console.log('Second Task');
}, 2000); 

console.log('Third Task');

Output will be :-

First Task
Third Task
Second Task

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. The setTimeout() method is asynchronous as it breaks the synchronous flow. This trick is used to execute the code after stacked events and fix timing-related problems.

AJAX (Asynchronous JavaScript and XML) requests are by default asynchronous, The XMLHttpRequest object is used to exchange data with a server behind the scenes. When the browser makes server requests. The response could take a little time. So you set up a function that will wait for the response to be sent back by the server, and react to it once the response is available. This whole process does not comes in the way of other functions.

  var xhttp;
      if (window.XMLHttpRequest) {
        // code for modern browsers
        xhttp = new XMLHttpRequest();
      } else {
        // code for old browsers (IE6, IE5)
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("ajax_demo").innerHTML = this.responseText;
        }
      };
      xhttp.open("GET", "fruits.txt", true);
      xhttp.send();
      xhttp.onload = function(){
        document.write(this.response);
      }; 
Share

Cesium – AJAX to update InfoBox ?


var viewer = new Cesium.Viewer('cesiumContainer');
var scene = viewer.scene;

var handlerA = new Cesium.ScreenSpaceEventHandler(scene.canvas);
  handlerA.setInputAction(function(click) {
    var pickedObject = scene.pick(click.position);
    if (Cesium.defined(pickedObject)) {
      $.ajax({

        type: 'GET',
        url: 'InfoBox.php',
        data: (pickedObject.id.id).val(),

        success: function(result) {
          pickedObject.id.description = "The temperatur of " + result.town + " is " + result.temp + " degrees...";
        }
      }); 
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

pickedObject.id is the entity.

Share

Perl Interview Questions?

What is use of ‘strict’ in perl ?
The module strict restricts ‘unsafe constructs’, according to the perldocs
When you enable the strict module, the three things that Perl becomes strict about are:
• Variables ‘vars’
• References ‘refs’
• Subroutines ‘subs’
Strict variables are useful. Essentially, this means that all variables must be declared, that is defined before use. Furthermore, each variable must be defined with my or fully qualified

What is scalars in perl ?
The most basic kind of variable in Perl is the scalar variable. Scalar variables hold both strings and numbers, and are remarkable in that strings and numbers are completely interchangable. For example, the statement
$priority = 9;
sets the scalar variable $priority to 9, but you can also assign a string to exactly the same variable:
$priority = ‘high’

Perl difference between lists and arrays ?
A list is a fixed collection of scalars. An array is a variable that holds a variable collection of scalars.
Array operations, which change the scalars, reaaranges them, or adds or subtracts some scalars, only work on arrays. These can’t work on a list, which is fixed. Array operations include shift, unshift, push, pop, and splice.
You can change an array element, but you can’t change a list element.

What is the use of ‘defined’?
defined EXPR
defined

Returns true if EXPR has a value other than the undef value, or checks the value of $_ if EXPR is not specified.
If EXPR is a function or function reference, then it returns true if the function has been defined.

Return Value
• 0 if EXPR contains undef
• 1 if EXPR contains a valid value or reference

#!/usr/bin/perl
$var1 = "This is defined";
if( defined($var1) ){
  print "$var1\n";
}
if( defined($var2) ){
  print "var2 is also defined\n";
}else{
  print "var2 is not defined\n";
}
This will produce following result
This is defined
var2 is not defined
Share

What is ajax synchronous and asynchronous?

Synchronous – Script stops and waits for the server to send back a reply before continuing. There are some situations where Synchronous Ajax is mandatory.

In standard Web applications, the interaction between the customer and the server is synchronous. This means that one has to happen after the other. If a customer clicks a link, the request is sent to the server, which then sends the results back.

Because of the danger of a request getting lost and hanging the browser, synchronous javascript isn’t recommended for anything outside of (onbefore)unload event handlers, but if you need to hear back from the server before you can allow the user to navigate away from the page, synchronous Javascript isn’t just your best option.

Synchronous AJAX function Example using GET.

    function getFile(url) {
  if (window.XMLHttpRequest) {
    AJAX=new XMLHttpRequest();
  } else {
    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (AJAX) {
     AJAX.open("GET", url, false);
     AJAX.send(null);
     return AJAX.responseText;
  } else {
     return false;
  }
}

var fileFromServer = getFile('http://www.phpmind.com/om.txt');

Synchronous AJAX function Example using POST.

function getFile(url, passData) {
  if (window.XMLHttpRequest) {
    AJAX=new XMLHttpRequest();
  } else {
    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (AJAX) {
    AJAX.open("POST", url, false);
    AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    AJAX.send(passData);
    return AJAX.responseText;
  } else {
     return false;
  }
}

var fileFromServer = getFile('http://www.phpmind.com/data.php', sendThisDataAsAPost);

Asynchronous – Where the script allows the page to continue to be processed and will handle the reply if and when it arrives. If anything goes wrong in the request and/or transfer of the file, your program still has the ability to recognize the problem and recover from it.
Processing asynchronously avoids the delay while the retrieval from the server is taking place because your visitor can continue to interact with the web page and the requested information will be processed with the response updating the page as and when it arrives.

Share

What is Ajax?

Ajax (sometimes called Asynchronous JavaScript and XML) is a way of programming for the Web that gets rid of the hourglass. Data, content, and design are merged together into a seamless whole. When your customer clicks on something on an Ajax driven application, there is very little lag time. The page simply displays what they’re asking for.

Ajax is a way of developing Web applications that combines:

  • XHTML and CSS standards based presentation
  • Interaction with the page through the DOM
  • Data interchange with XML and XSLT
  • Asynchronous data retrieval with XMLHttpRequest
  • JavaScript to tie it all together
Share

How to send bulk email through email software?

If you’re sending an email campaign to thousands or millions of user using some software then you’re going to need a reliable mail server. Most of the shared servers are not going to allow you send more email. There are a lot of restrictions and host may impose email sending restrictions which makes it impossible to send.

There are ways to send –
1. You can send emails out application your web host’s mail sending engine. This advantage is accomplished if you’re sending only a few hundred emails per month, about as soon as you go over this, your host will not allow you to send more. This option is good for sending email using online php tools so many are available please check with google 🙂
2. You can buy your own committed server from service provider like RackSpace.com or netatlantic.com (we are using this!) and configure it to send emails. We send 60000 emails per month without any issue, they have easy to use web interface. We just create newsletter test and send to our subscribers. It works perfectly.

3. Most effective option is using third party mail server like SMTP.com. Even if you are using shared server you can use there service if you have tones of email to send. Don’t forget to negotiate for discount if you are using there partners software!!

Share

How to delete a folder with PHP?

To delete a file, or a folder and its contents i have compiled a recursive algorithm.
Hope this will be useful for all of you.

read()) {

      // Skip pointers

      if ($entry == '.' || $entry == '..') {

      continue;

      }
       
      // Recurse
      rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);

      }
       
      // Clean up
      $dir->close();

      return rmdir($dirname);

      }

?>
Share