A Review of AJAX under JQuery.

Ajax calls and components
If You Have a Friend on Facebook - Let them Know About This Item!!!!

Unusually for Review Raptor we’ve decided to do a review of a tech product / mechanism.  This is therefore at a lower level than our more traditional “product” reviews and programmers are more likely to benefit from this more than our product hunting visitors!

AJAX (which stands for Asynchronous Java and XML) is a technology which allows a web programmer to send information to a web server WITHOUT the need for issuing a FULL page request and re-load.  Broadly speaking, the underlying mechanism for the transmission of the data to the web server is the same as it is with a standard http GET or POST request – however the page within the browser does not need to be refreshed in order to either send or process any returned data.

First of all I think it’s worth noting that the XML part of AJAX is not really the standard use of the technology any longer.  You will more often see JSON encoded data being passed back to a calling function as opposed to XML format data.  So in theory – we can confidently call this methodology AJAJ!

Why is it beneficial to allow a web page to communicate with a web server?

In older versions of programming languages in popular use for web development (PHP, JavaScript for example) it was not possible for a page to perform two way communications with its serving host.  Once a page was present in a browser, the only way it could send information back to the server was to POST it to a target page or process (which – invariably was “itself”) and then re-load the page (again – mostly therefore reloading “itself” with the new data values).
This shortfall resulted in some of the most convoluted, non-standard, unstructured birds nest type code I have ever seen in my thirty plus years of coding experience.

Imagine the scenario – a common one at that, a shopping cart is on the screen and the customer changes the number of items to purchase (the quantity).  The page has to post the new quantity to itself, and then reload itself IN ITS ENTIRETY just to show the new “total order value”.  Do not underestimate this task in terms of the amount of duplication it has to perform to re-display existing data plus the new values within a standard templated environment.  Depending on the application, this results in file IO, Image and data transfers, repeat calculations and potentially much more.

Appalling as this situation was, programming as a skilled trade had become (and remains) so flooded by amateurs who represented the largest part of the global development “pool” BY FAR – that globally this method actually became the accepted NORM.  This staggering acceptance of such a flawed mechanism is absolute in history – there is no avoiding it – and even today – many years after the advent of AJAX – many developers still cling on to this old method and hail it as THE way to handle data transfers between functionality on a web page – the mind seriously boggles.

Now consider the AJAX mechanism.  The user can change the qty, the new qty can be passed by javascript (which then waits) to a server process which simply multiplies the unit price by the new quantity and returns the value to the waiting javascript.  The JS captures the returned value and pushes it to the users screen in an instant.  This can be applied to ANY item of data on ANY given input screen.

How do we make our AJAX calls then?

Like anything in I.T. these days, there are many ways of implementing the code and this depends on the application, coder style, error checking extents – to name just a few of the variables to consider.  Some would argue this is a good thing – there are those who subscribe to coder freedom and those who prefer standard fixed practices which tend to lend themselves to easier maintenance in the longer term.  For the purpose of this review, I will give a short demonstration of a simple call, process and response – and from this point you can make your own mind up on how you progress to implement, or take it further with newer factors such as “promise based” calls.

First of all, we need a “caller”.

<!DOCTYPE html>
<HTML>

<HEAD>
<META CHARSET=”UTF-8″>
<TITLE>Ajax Call – Lesson 1</TITLE>
<SCRIPT SRC=”https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js”></SCRIPT>
</HEAD>

<STYLE>
.container
{
display : block;
width : 30%;
position : fixed;
top : 50%;
left : 50%;
-webkit-transform : translate(-50%, -50%);
transform : translate(-50%, -50%);
text-align : left;
padding : 15px;
background-color : grey;
}

.grid-container {
display: grid;
grid-gap: 50px 100px;
}

.item1 {
grid-column-start: 1;
grid-column-end: 3;
}

</STYLE>

<BODY>
<DIV CLASS=”container”>
<P>Login Using Ajax to Pass the User Input to the Web Server.</P>
<DIV><INPUT TYPE=”text” ID=”useridId” VALUE=”” PLACEHOLDER=”User ID”></DIV>
<DIV><INPUT TYPE=”text” ID=”passwordId” VALUE=”” PLACEHOLDER=”Password”></DIV>
<BR>
<DIV><INPUT TYPE=”button” ID=”loginButton” VALUE=”Log In” onclick=”passInputToServer();”></DIV>
</DIV>

<DIV class=”grid-container”>
<DIV class=”item1″ id=’gtarg1′>1</DIV>
</DIV>

</BODY>

<SCRIPT>
// This function takes the input variables from the screen, and passes them to
// a PHP script which is on the server. The PHP script expects two variables
// and processes them before returning here.
// When it returns, it returns to the callback function in success (where it can process the response)
// or the callback function in error – where there is no response from the remote script – only an error.
// The point to note, is that within the success function, we can check the scripts response (ajaxResponse)
// the “ajaxResponse” variable (named by us) holds the data created by the remote script – YOUR messages.

function passInputToServer()
{
useridToSend = $(‘#useridId’).val().trim();
passwordToSend = $(‘#passwordId’).val().trim();

$.ajax
({

// Prepare and call.
url : “ajaxProcess.php”, // the name of the remote script to execute.
type : ‘POST’, // the method of transfering the data.
dataType : ‘JSON’, // the format of the data coming back from the remote script.
data : {inputUserId : useridToSend, inputPassword : passwordToSend}, // the list of variables to pass up

// Process once the called script is complete.
success : function (ajaxResponse)
{
if (ajaxResponse.status === 0) // Everything Ok.
{
$(‘#gtarg1’).html(“<span>” + ajaxResponse.textMessage + “</span>”);
alert(“Data is Ok – ” + ajaxResponse.textMessage);
}
else if (ajaxResponse.status === 1) // Failed on server side validate.
{
alert(“Data was Bad – ” + ajaxResponse.textMessage);
}
else
{
alert(“Unknown Error – The Remote Script Executed But Returned An Unrecognised Response.”);
}
},
// An actual ajax error – not an error with the user data.
error : function (jqXHR, txtStatus, perror)
{
if (jqXHR.status != 0)
{
alert(“AJAX Call Failed – The Remote Script Did Not Execute.”);
}
}
});
}

</SCRIPT>
</HTML>

and now we need our target script – the script which is called on the fly by the caller above.

<?php
/*
* Called by ajaxCaller.html
* Takes two parameters, if either are blank or not passed, return 1 for Error.
* If both have a value in them, it returns 0 for OK.
* A text message for the user is returned in any outcome.
*/
$returnStream[“status”] = 1;

if (!isset($_POST[“inputUserId”]))
$returnStream[“textMessage”] = “You have not passed a userid.”;
else if (!isset($_POST[“inputPassword”]))
$returnStream[“textMessage”] = “You have not passed a password.”;
else if ($_POST[“inputUserId”] == ”)
$returnStream[“textMessage”] = “You have not entered a userid.”;
else if ($_POST[‘inputPassword’] == ”)
$returnStream[“textMessage”] = “You have not entered a password.”;
else
{
$returnStream[“status”] = 0;
$returnStream[“textMessage”] = “Congratulations – you entered a userid and a password.”;
}

echo json_encode($returnStream);

?>

I apologise for the lack of indentation – however wordpress has decided it is not required and removes it when displaying it.

As you can see from the above code – AJAX is “wrapped” by the popular javascript library JQuery.  I do recommend using this as there are one or two nasty cross-browser issues within the underlying XHR object processing which are smoothed out by JQuery and this therefore eliminates a lot of the repetitive checking you would need to do yourself.

You can see for yourself that the process is simplicity incarnate when compared to generating and sending the entire screen again JUST FOR THE SAKE of a simple message.  The message returned (with a JSON Encode you will notice) is simply inserted into the screen element as follows :-

$(‘#gtarg1’).html(“<span>” + ajaxResponse.textMessage + “</span>”);

Again – rather than using document.getelementbyid() etc etc – we use JQuery to reference our item which is identified as having an ID of gtarg1 – then executing the html method on it – passing in our message formatted with a span.  Simples.

The ONLY pitfall (and it’s not really a pitfall – more like “be careful”) is that the application will need to be designed with the fact that AJAX is meant to be used asynchronously.  In other words, when I mentioned above that the javascript is waiting – it is – in fact – waiting via a callback, it has NOT hung the browser.  Therefore for longer duration remote processes the developer must have a strong understanding asynchronicity and whether it is better to send and “wait” or send and “next step” (i.e. implement a back end queuing system for requests which can be reported back to the user later in terms of their progress).

All in all – as a developer AJAX is by far the better way of handling data between screens and processes in a real-time web environment such as an e-commerce web site or other system involving process flow of any kind.  If you are being guided down the old route of full page refreshing – then you are – infact – being misguided and should look again at what you are trying to achieve!

AJAX

AJAX
10

AJAX and JQuery

10/10

    Pros

    • - Ease of AJAX Use
    • - Bug Free
    • - Structure of Code

    Cons

    • - You have to work to learn it
    • - Unlucky if you are lazy
    If You Have a Friend on Facebook - Let them Know About This Item!!!!

    Leave a Reply

    Your email address will not be published. Required fields are marked *