Pages

C3 Health Services

Visit Official Website 9278982994

Expert Healthcare at Your Doorstep

Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Friday, 4 April 2014

How to pass a Javascript Array to PHP file using AJAX and JSON?

How to pass a Javascript Array to PHP file using AJAX and JSON?

I have an array in javascript and I need to pass this array to a PHP by using AJAX call to that PHP file. I will get this array in PHP file and assign this javascript array to PHP array. Then I will find out the count of that PHP array elements and return it back to the javascript. I will convert JS array in JSON format by JSON.stringify. This is a very simple example on how to pass javascript array to PHP asynchronously. You can perform a lot of operations on this array which you have passed to PHP file but for simplicity I am just returning its count. Let's have a look at the following code snippet.

Javascript Array

var myJSArray = new Array("Saab","Volvo","BMW");

ProcessAJAXRequest() function wil pass JS array to PHP file using AJAX request and will show count of array elements returned by PHP file.

function ProcessAJAXRequest()
{
    $.ajax
    ({
        type: "POST",
        url: "myphpfile.php",
        data: {"myJSArray" : JSON.stringify(myJSArray)},
        success: function (data) 
        {
            alert(data); //count of array elements
        }
    });
}

myphpfile.php

<?php 
    $myPHPArray = json_decode($_POST["myJSArray"]);
    echo count($myPHPArray);
 ?>

Saturday, 23 November 2013

How to secure jQuery AJAX calls in PHP from hackers?

How to secure jQuery AJAX calls in PHP from hackers?

If you are making jQuery AJAX calls in your PHP website, please ensure that those jQuery AJAX calls are secure from website hackers. Your code should not be vulnerable to hackers. Below are some methods and steps which need to be taken to secure your jQuery AJAX calls to PHP files. I am writing this post because I had written a simple post "How to call PHP function from JavaScript function? Always use AJAX." without mentioning any security code. I got following comment on that post:

"Your code is very vulnerable. You're not filtering the $_POST variable at all. This opens yourself to HTML injection. A hacker could pwn your web site very quickly if you used this code. Careless examples like yours is exactly why so many web sites are hacked."

That's why this is my small attempt to make your jQuery AJAX calls secure. 

1. Use $_SERVER['HTTP_X_REQUESTED_WITH']

This is a basic check to see if the request is an Ajax request or not?

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&       strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
{
    //Request identified as ajax request
}

However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

2. Use $_SERVER['HTTP_REFERER']

if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
{
 //Request identified as ajax request
}

But not all browsers set it. So don't properly rely on it but yes, to some extent it can secure your webpage.

Nobody can AJAX your site from other domain, but always can connect and drieclty send http request, for example by cURL.

JavaScript running on another domain cannot access any page on your domain because this is a violation of the Same-Origin Policy. The attacker would need to exploit an XSS vulnerability in order to pull this off. In short you don't need to worry about this specific attack, just the same old attacks that affect every web application.

3. Generate Access Tokens

$token = md5(rand(1000,9999)); //you can use any encryption
$_SESSION['token'] = $token; //store it as session variable

You can create some token in cookies, that will be also seen from jquery request, but that solution can also be hacked.

4. Always check $_POST variables in your PHP file whether those are set or not? Whether there is valid value in $_POST or not before executing the actual PHP code.

Basic code snippet for securing your jQuery AJAX calls in PHP

Step-1 : Generate Token System For All Web-Service:

Generating Token :

<?php
  session_start();
  $token = md5(rand(1000,9999)); //you can use any encryption
  $_SESSION['token'] = $token; //store it as session variable
?>

Step-2 : Use it while sending ajax call:

var form_data = 
{
  data: $("#data").val(), //your data being sent with ajax
  token:'<?php echo $token; ?>', //used token here.
  is_ajax: 1
};

$.ajax({
  type: "POST",
  url: 'yourajax_url_here',
  data: form_data,
  success: function(response)
  {
    //do further
  }
});

Step-3 : NOW, Let's secure ajax handler PHP file with,

session_start(); 
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') 
{
  //Request identified as ajax request

  if(@isset($_SERVER['HTTP_REFERER']) &&    $_SERVER['HTTP_REFERER']=="http://yourdomain/ajaxurl")
  {
   //HTTP_REFERER verification
    if($_POST['token'] == $_SESSION['token']) {
      //do your ajax task
      //don't forget to use sql injection prevention here.
    }
    else
   {
      header('Location: http://yourdomain.com');
    }
  }
  else 
  {
    header('Location: http://yourdomain.com');
  }
}
else 
{
  header('Location: http://yourdomain.com');
}

Wednesday, 20 November 2013

How to call PHP function from JavaScript function? Always use AJAX.

How to call PHP function from JavaScript function? Always use AJAX.

Recently, I was developing a web application in PHP. I get into the need of calling my PHP function from my Javascript function. This is the common thing when you are developing a web application in PHP and have to call a PHP code from Javascript to refresh only a certain portion of your web page with server results. Always use AJAX to achieve this functionality. Using AJAX you can call server side code / functions (your PHP code) from client side (Javascript). Below is the PHP and Javascript code snippet to illustrate this concept. 

This is very simple example on how to call server side functions of PHP from client browsers (Javascript)? In following example, I have a PHP file named myscript.php which has function named myfunction(). This function uses two $_POST variables and just echoes them. I have mydiv HTML div anywhere on my webpage which I want to refresh with the result which is returned from my PHP script. In my Javascript code, I am using AJAX to call my PHP script with parameters and POST method. The result which is getting returned, I am showing that in mydiv HTML div. 

Have a look at this very simple PHP AJAX example:

PHP code

<?php

myfunction();

function myfunction()
{
$myvar = $_POST['q']." how are you?";
$myvar2 = $_POST['z'];
echo $myvar."\n".$myvar2;
}
?>

HTML code

<div id="mydiv"></div>

Javascript code

var data =" hello world";
var data2=" hello all";
function run()
{
$.ajax(
{
                   url: 'myscript.php',
                data: {'q': data,'z':data2},
                   type: 'post',
                   success: function(output) 
                {
                          //alert(output);
                          document.getElementById("mydiv").innerHTML += output; //add output to div  
                }
}
          );
}

Saturday, 15 December 2012

Multiple File Upload Progress Bar Script using PHP, HTML5, jQuery and AJAX Plugins

Multiple File Upload Progress Bar Script using PHP, HTML5, jQuery and AJAX Plugins

Multiple File Upload With Progress Bar functionality is very common in online websites. Creating a multiple file upload progress bar script is very easy by using PHP, AJAX and jQuery. I will use AJAX Library from Github to create a script for multiple file upload and progress bar. This tutorial on multiple file upload will demonstrate step by step scripting for multiple file upload using PHP, jQuery and AJAX Plugin.

First, we will create a multiple file upload button using HTML and then we will put some CSS on this multiple file upload button to design it and make it more interactive. After creating multiple file upload button, we will add PHP script which will upload the multiple files and show the progress bar. Last but not the least, we will add AJAX Plugin for multiple file upload from Github in our working folder and then use that multiple file upload plugin in our javascript code. I have also done some error handling in my javascript code like a user can only multiple upload PNG, GIF and JPG files. You can impose extra checks as per your requirement. I am also showing the progress bar while multiple files are being uploaded.

Step 1: Create Upload Button using HTML

<div id="upload" >Upload File</div> 
<span id="status" ></span> 
<ul id="files"></ul> 

Step 2: Design Upload Button using CSS

#upload

    margin:30px 200px; padding:15px; 
    font-weight:bold; font-size:1.3em; 
    font-family:Arial, Helvetica, sans-serif; 
    text-align:center; 
    background:#f2f2f2; 
    color:#3366cc; 
    border:1px solid #ccc; 
    width:150px; 
    cursor:pointer !important; 
    -moz-border-radius:5px; -webkit-border-radius:5px; 
}

Step 3: Add PHP Multiple File Upload Script

Below is the PHP script for multiple file upload. This PHP script will show 'Success' message when all the files are uploaded successfully. If there is any error while uploading multiple files, the PHP script will report an error.

<?php 
$uploaddir = './uploads/';  
$file = $uploaddir . basename($_FILES['uploadfile']['name']);  
  
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file))
{  
  echo "success";  
}
else

    echo "error"; 

?> 

Step 4: Add jQuery and Javascript to your code

First of all, you have to include jQuery Multiple File Uploader Plugin from GitHub. Here is the link: https://github.com/valums/file-uploader

$(function(){ 
    var btnUpload=$('#upload'); 
    var status=$('#status'); 
    new AjaxUpload(btnUpload, { 
        action: 'upload-file.php', 
        //Name of the file input box 
        name: 'uploadfile', 
        onSubmit: function(file, ext){ 
            if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){  
                  // check for valid file extension  
                status.text('Only JPG, PNG or GIF files are allowed'); 
                return false; 
            } 
            status.text('Uploading...'); 
        }, 
        onComplete: function(file, response){ 
            //On completion clear the status 
            status.text(''); 
            //Add uploaded file to list 
            if(response==="success"){ 
                $('<li></li>').appendTo('#files').html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success'); 
            } else{ 
                $('<li></li>').appendTo('#files').text(file).addClass('error'); 
            } 
        } 
    }); 
}); 

Multiple File Upload Progress Bar Script Explanation:

To use the AJAX Upload library we need to initialize the AjaxUpload object and provide it with parameters. The first parameter is the id of the button element on which the user will click and second is the server side script that’ll handle file upload. The second parameter can accept an array of various options to give you more control over the process.

And that’s exactly what I have done:

1. The action field is the path to server side script,

2. name is the name of file input box(hidden) which will be used for upload. If you change this value, make sure to change the server side script corresspondinly.

3. onSubmit lets you perform some function before the file is uploaded e.g. you can check the file extension like i’ve done above or show a status message.

4. onComplete lets you perform some action after the upload is complete e.g. I’ve shown the uploaded image to the user.

And if you want to limit the number of files that a user can upload at a time, simply use this.disable() within onSubmit or onComplete to disable the upload button after checking for some condition.
 
Note: The file upload using AJAX is not true ajax as it uses hidden iframe to upload the form data but his whole process is transparent by using the AJAX Upload library and gives a feel of AJAXified file upload.

Friday, 8 June 2012

How to abort an AJAX call using jQuery?

There may be situations where you need to cancel a running AJAX request before it ends. It's usually in cases where the user might perform an action, which sets of an AJAX request, several times within a short time period.

A good example of this is auto-complete functionality for a search box, where you might try to help the user by finding related search terms based on their current input, by making an AJAX request each time they press a key in the search field. In that case, it's very likely that the user types faster than your AJAX request can be performed and therefore you would want to abort any non-finished requests, before starting the next one.

Consider the following example:

<input type="button" name="btnDoRequest" value="Start" onclick="PerformSimpleCalculation();" />
<script type="text/javascript">

function PerformSimpleCalculation()
{
        $.get("/tests/calc.php", function(data, textStatus)
        {
                alert(data);
        });
}
</script>

It requests a PHP script which is doing a very complicated calculation (as you will see from the result), which means that it usually takes ~3 seconds to finish. Now, try the example and push the button several times after each other. The same "calculation" will be performed multiple times and the result will also be displayed multiple times (with a 3 second delay).

Fortunately, a call to the get() method and pretty much any other jQuery AJAX method, returns an object which, among others, contains an abort() method. We can save this reference and then call the abort() method on it if needed. Have a look at this slightly modified example:

<input type="button" name="btnDoRequest" value="Start" onclick="PerformAbortableCalculation();" />
<script type="text/javascript">

var calculationRequest = null;

function PerformAbortableCalculation()
{
        if(calculationRequest != null)
                calculationRequest.abort();
        calculationRequest = $.get("/tests/calc.php", function(data, textStatus)
        {
                alert(data);
        });
}
</script>

We start off by defining a common variable for containing the request reference. In the PerformAbortableCalculation() method, we assign the return value of the get() call to this variable, but before we do so, we check to see if it's null (the method hasn't been used yet) and if not, we call the abort() method on it. If you try this example and click several times, you will see that no matter how many times you click the button, it only executes the callback function once.

Tuesday, 15 May 2012

11 Commonly used AJAX Frameworks

There are hundreds of AJAX Frameworks available. Most commonly used frameworks are jQuery, MooTools, Prototype, ASP.NET AJAX, Apache Wicket, Dojo Toolkit, DWR (Direct Web Remoting), Spry Framework, YUI (Yahoo User Interface) and Google Web Toolkit.

Here is a small description of these frameworks:

1. jQuery:  The jQuery library is providing many easy to use functions and methods to make rich applications. These functions are very easy to learn and even a designer can learn it fast. Due to these features jQuery is very popular and in high demand among the developers. You can use jQuery in all the web based applications irrespective of the technology.

2. MooTools: MooTools (My Object-Oriented Tools) is a lightweight, object-oriented, JavaScript framework. It is released under the free, open-source MIT License. It is used on more than 5% of all websites, and is one of the most popular JavaScript libraries.

3. Prototype: Prototype is a JavaScript Framework that aims to ease development of dynamic web applications. It features a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the codebase of choice for web application developers everywhere.

4. ASP.NET AJAX: The ASP.NET AJAX Control Toolkit is an open-source project built on top of the Microsoft ASP.NET AJAX framework. It is a joint effort between Microsoft and the ASP.NET AJAX community that provides a powerful infrastructure to write reusable, customizable and extensible ASP.NET AJAX extenders and controls, as well as a rich array of controls that can be used out of the box to create an interactive web experience.

5. Apache Wicket: Apache Wicket, commonly referred to as Wicket, is a lightweight component-based web application framework for the Java programming language conceptually similar to JavaServer Faces and Tapestry.

6. Dojo Tookit: Dojo Toolkit is an open source modular JavaScript library (or more specifically JavaScript toolkit) designed to ease the rapid development of cross-platform, JavaScript/Ajax-based applications and web sites.

7. DWR (Direct Web Remoting): DWR is a Java library that enables Java on the server and JavaScript in a browser to interact and call each other as simply as possible.

8. Spry Framework: The Spry Framework is an open source Ajax framework developed by Adobe Systems which is used in the construction of Rich Internet Applications. Unlike other pure JavaScript frameworks such as the Dojo Toolkit and Prototype, Spry is geared towards web designers, not web developers.

9. YUI (Yahoo User Interface) Library: It is a set of utilities and controls, for building richly interactive web applications using techniques such as DOM scripting, DHTML and Ajax BSD.

10. Google Web Toolkit: Google Web Toolkit is an open source set of tools that allows web developers to create and maintain complex JavaScript front-end applications in Java. Other than a few native libraries, everything is Java source that can be built on any supported platform with the included GWT Ant build files. It is licensed under the Apache License version 2.0.

11. ZK Framework: ZK is an open-source Ajax Web application framework, written in Java, that enables creation of rich graphical user interfaces for Web applications without the application developer having to write JavaScript and with little required programming knowledge.

Thursday, 3 May 2012

Difference between AJAX and jQuery

AJAX is a JAVASCRIPT TOOL whle JQUERY is a JAVASCRIPT LIBRARY.

AJAX is a denomination of several programming techniques. AJAX is not a specific technology but a combination of varying technologies to provide a new functionality. AJAX is not a new programming language, but a new way to use existing standards.Whenever you request a new set of data from web site, it clears the whole page and loads the new one. AJAX is used to circumvent this behavior and allow new data to be retrieved without modifying the whole page.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

jQuery is a javascript framework that makes working with the DOM easier by building lots of high level functionality that can be used to search and interact with the DOM. By using we can make Ajax calls.

jQuery is a lightweight javascript library that ease the writting of javascript by levelling the differences between browsers and giving a common, simplified syntax. jQuery performs some commonly desired things so that author's don't need to reinvent some common wheels. jQuery focuses more on interactions with HTML elements. jQuery simplifies HTML document traversing, event handling, animating, and AJAX interactions for rapid web development. jQuery Libraries can be downloaded jquery.com.

jQuery handles Front End tasks while AJAX handles backend (server calls)

jQuery does all the work on the front end, therefore you would need to have a full understanding of it in order to properly set-up your page. You would not need to learn the exact mechanisms of AJAX in order to utilize it as jQuery gives you an AJAX command to retrieve whichever data you need from the server.

AJAX and jQuery are often used together

AJAX can’t be utilized with simple HTML since HTML doesn’t allow the page to be changed after it has fully loaded. In order to use AJAX, you would need a client side scripting language that allows you to detect the actions of the user and modify elements on the page accordingly. jQuery does that exactly, that is why both are often used together to present web pages that a user can interact with easily without repetitive loading.

Problem with AJAX and jQuery

Although the use of jQuery and AJAX makes the browsing experience a lot better for the user, the effect to the server hosting these files are not as desirable. Every time you make another AJAX request, a new connection to the server is made. Too many connections can sometimes be difficult for the server to cope with. Most hosting companies have made steps in order to prevent overloads since jQuery and AJAX are truly here to stay.

Summary:

1. jQuery is a lightweight client side scripting library while AJAX is a combination of technologies used to provide asynchronous data transfer.
2. jQuery and AJAX are often used in conjunction with each other.
3. jQuery is primarily used to modify data on the screen dynamically and it uses AJAX to retrieve data that it needs without changing the current state of the displayed page.
4. Heavy usage of AJAX functions often cause server overload due to the greater number of connections made.

Friday, 6 April 2012

Preventing Caching in AJAX URLs

If we have the one page performing multiple requests and those requests are using the GET method then we have a slight problem with some browsers.

Browsers try to reduce the amount of data that needs to be retrieved from the server by caching what has already been retrieved on your computer. A subsequent request for the same data will grab the cached copy rather than going back to the server to get it.

Unfortunately some browsers will do this with your AJAX request even though the information on the server may have changed in the meantime.

There are two ways that we can fix this - one in the Javascript and on in the server side code.

Solution 1:

The Javascript solution is to update the URL being passed so that we pass a different value each and every time. We do this by adding a dummy variable to the end of the URL in the query string and assign it a different value each time that a request is made. The easiest way to do this is by adding the microsecond value of the current time which will be different unless your visitor manages to make two requests in the same microsecond.

url = url+'?dummy='+ new Date().getTime();

Doing this means that the URL is different for each request and so the cached copy doesn't get used. As the server side processing doesn't need the dummy field, it just ignores it and processes exactly the same as if it weren't there.

Solution 2:

The better solution though is to update the server side processing itself. What you need to do is to add a header into the response that instructs the browser not to cache the information in the first place. How you do this depends on the server side language you are using.
The PHP version of the extra line you need is:

header('Cache-Control: no-cache'); 

Going deep, put the following response headers in the page (using the PHP header() function):

<?php
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

Thursday, 5 April 2012

AJAX - A quick revision

AJAX
1. AJAX = Asynchronous JavaScript and XML
2. AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.
3. Examples of applications using AJAX: Google Maps, Google Suggest, Gmail, Youtube, and Facebook tabs. AJAX was made popular in 2005 by Google, with Google Suggest.
4. AJAX is based on internet standards, and uses a combination of:
            1. XMLHttpRequest object (to exchange data asynchronously with a server)
            2. JavaScript/DOM (to display/interact with the information)
            3. CSS (to style the data)
            4. XML (often used as the format for transferring data)
 5. AJAX applications are browser and platform-independent!
Disadvantages
1. Javascript dependency. It will not work if javascript is blocked.
2. View source is allowed and anyone can view the code source written for AJAX.
3. Debugging is difficult.
4. Complexity of the code makes it difficult for web developers.
5. Search engines would not be able to index an AJAX application.
6. Bookmarking and Back Button functionality of browser is affected.
The XMLHttpRequest Object (and ActiveXObject)
1. The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
2. All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera)  support the XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).
3. Properties: open, send, onreadystatechange, readystate, status, responseText, responseXML
GET vs POST
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
            1. Sending a large amount of data to the server (POST has no size limitations)
            2. Sending user input (which can contain unknown characters), POST is more robust and secure than  GET
ReadyState
Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
Note: The onreadystatechange event is triggered four times, one time for each change in readyState.
Status
200: "OK"
404: Page not found
Kinds of Response:
1. responseText
2. responseXML
Note: While sending XML request to server, header of the request must be mentioned as
xmlhttp.open("GET","result.xml",true);
xmlhttp.onreadystatechange=myfunction;
request.setRequestHeader(“Content-Type”,”text/xml”);
xmlhttp.send();

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.