So this is my summary that I learned so far.
Usually we use AJAX to query something from server without reloading the page. In this example I want to show how I can send two data to be processed in the server using POST.
Oh, I forget to mention that I'm using Codeigniter.
So here is the code in the client looks like if I use POST (in Viewer):
<script>
function test_ajax()
{
url = 'get_jsondata';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState==4 && this.status == 200)
{
alert(this.responseText);
}
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("var1=hallo&var2=halli");
}
</script>
First, take a look at the variable url. It has value of 'get_jsondata'. This value will call URL of (in my case, since I'm still working on local) http://localhost/myweb/index.php/c_home/get_jsondata. That means I have to prepare a function called 'get_jsondata' in Controller 'c_home'.
Second, take a look at the variable 'xhttp'. This variable is an object of XMLHttpRequest(). The real execution of the AJAX request is when calling the function 'send'. What the code does above is:
- define the callback function on 'onreadystatechange'. If the readystate change, the function will be called. I read in w3school, the function will be called 4 times.
- open specifies the type of request. the third parameter says whether the function should be asynchronous (true) or synchronous (false). If it is asynchronous, the browser will not wait for the response and continue process the web. On the other hand, if it is synchronous, the browser will wait for the response before processing the next step.
- If POST is used, the content of the request has to be defined. Just use it like that.
- Send the request with defining the variables and their values in string and separated with '&'.
In PHP, the function will look like this (Controller). Like I mentioned before, the function's name should be 'get_jsondata'.
function get_jsondata()
{
echo $_POST['var1']." ".$_POST['var2'];
}
Tidak ada komentar:
Posting Komentar