ad

Friday, 16 October 2015

Sending POST requests with AJAX for absolute beginners

First things frst, what is AJAX?
AJAX is a client side script that communicates with server without the need to refresh the web page - in other words it works asynchronously.

Why'd I need AJAX anyways?
What about when you wanna get data from server and put it into a dable without refresh? What about when you wanna check whether username alrady exists without refresh?

How do I send a GET request with AJAX?
Use get method, and a callback function inside that takes two parameters, first returns the page, second the sucess or failed result.
To test our script out, lets create two pages, index.html and data.php, we'll send GET request to data.php from index.html page, and echo whatever is returned. I'd write something in index.php file so I can see whatever has returned.

        $.get("data.php", function(data, text){
            document.write(data);
        } );


Run the above code inside <scirpt> tags and you should see whatever was in the index.php file. That's our basic GET request done.

Q. I'm trying to load a website but it returns 301 page moved permanently?
A. The website has been moved to different URL. Read my HTTP the very basics tutorial to learn more about HTTP and headers. If website has been moved to different URL, it should generally send a Location header to your client. Try that URL.


How do I send POST request to a page?
To send a POST request use the following, pretty much same syntax as GET method but we'll add some POST data, like username and password. Basically we're going to send username and password to data.php page which has following code. Usually you'd get validate POST data and tyr matching it against user and password in SQL DB:
    if( ($_POST["username"] == "cloudcomputing") and ($_POST["password"] == "jquery") ){
        echo "Correct username and password";
    }else{
        echo "Wrong username or password";
    }


Lets send it some data from index.html page. By the way, you can read more about this method here
http://api.jquery.com/jquery.post/

Lets send username and password.
        $.post("data.php", {
            username: "loudcomputing",
            password: "jquery"
        }, function(data, result){
            document.write(data);
        });     
   

Guess what is returns? Wrong username or password. Change sending password to cloudcomputing and it'll grant the access.

So that's pretty much to it, sending basic GET or POST request is where you start and and when you're familiar with it you start adding little things to secure it.. from there on it's all trial and error and basic knowledge of how HTTP protocol works.

No comments:

Post a Comment