Tampilkan postingan dengan label Web. Tampilkan semua postingan
Tampilkan postingan dengan label Web. Tampilkan semua postingan

Minggu, 03 Desember 2017

AJAX with POST in Codeigniter (CI)

Hi there, I just learned how AJAX works. I learned from www.w3school.com, it is really a great web that one can learn everything about programming Web Application.

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:

  1. 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.
  2. 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.
  3. If POST is used, the content of the request has to be defined. Just use it like that.
  4. 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'];
}


Sabtu, 04 November 2017

add/remove HTML input dynamically with Javascript

Again, a posting to remind me again, in case I forget how to do this.
I'm in the middle of coding a web page for member's registration. Some member might have more than one phone number, so I want to have a webpage that the member can add the input form or remove it dynamically.

I use Codeigniter and Bootstrap to code.

So, here is a part of the HTML code:


<div class="form-group">
<div class="row">

<label class="col-sm-2 control-label text1">phone</label>

<div class="col-sm-1">

<a onclick="addTelp()">

<i class="icon_plus_alt2" style="float: right"></i>

</a>

</div>

<div class="col-sm-9">

<input type="text" class="form-control" name="telp[0]">

</div>

</div>
</div>
<div id="morephone">

</div>



the new input field will be put inside div with id "morephone".

Here is the javascript code to add new input field :


<script>
var i=1;
function addTelp()
{

var div=document.createElement('div');

div.className='form-group';

var attr="telp_"+i;

div.setAttribute('id', attr);

div.innerHTML='<div class="row" >\

<label class="col-sm-2 control-label text1"> </label>\

<div class="col-sm-1" >\

<a onclick="remove(this)" style="color:red" >

<i class="icon_minus_alt2" style="float: right"> </i>

</a>\

</div>\
<div class="col-sm-9" id="inti">\
<input type="text" class="form-control" name="telp['+i+']" id="idtelp'+i+'">\
</div>\
</div>';
document.getElementById('morephone').appendChild(div);
i++;
}
</script>

The sequence number for the id and the name of the input form is optional. I use it for my own purpose that I don't describe here.

Here is the generated HTML code from that function:

<div class="form-group" id="telp_1">
<div class="row">

<label class="col-sm-2 control-label text1"> </label>

<div class="col-sm-1">

<a onclick="remove(this)" style="color:red">

<i class="icon_minus_alt2" style="float: right"> </i>
</a>
</div>
<div class="col-sm-9">
<input type="text" class="form-control" name="telp[1]" id="idtelp1">
</div>
</div>
</div>


This is how I remove the input field:


<script>
function remove(input) {

var parent=document.getElementById('morephone');

node=input.parentNode.parentNode.parentNode

parent.removeChild(node);
}
</script>


Lets take a look at the third line of the function above.

node=input.parentNode.parentNode.parentNode

It was new for me and it took quite time to understand what was it. So here is the explanation:

Take a look at the generated HTML code. Onclick event is in HTML tag <a> and call a javascript function remove with a parameter "this". "this" refers to the tag <a>.

What I want to remove with the function "remove(this)" is one input field. That means I have to remove the whole generated HTML. To do that I have to get the tag <div> with id "telp_1", which is located 3 level above the <a>.

Now lets take a look again at this line:

node=input.parentNode.parentNode.parentNode

input refers to tag <a> where the function remove() called on mouse click.
input.parentNode refers to tag <div class="col-sm-1">
input.parentNode.parentNode refers to the tag  <div class="row">
input.parentNode.parentNode.parentNode referst to the tag  <div> with id telp_1 and this is what I want to have. Right now I will call it as an element Node.

The one who can remove a node is its parent. The parent is a node in one level above, that means the parent is <div> tag with id "morephone".

Selasa, 31 Oktober 2017

Session Data Lost after redirection in Codeigniter

I am using Codeigniter 3.0.6 and PHP 7.1.2. Problem that I faced is the session data lost after redirecting to another controller. After googled, this issues is kind of a bug in Codeigniter. I have tried many solution found in google and this link gives the solution that works for my case.

I did exactly the steps that are shown in that link :
  1. Go to system/libraries/Session/Session.php
  2. Comment session_start() by adding //. We want to relocate the sessionn_start().
  3. Find (using ctrl + f ) a comment that says "Security is king". Comment out all the line under that comment until the end of the function. In my case I commented out the line number 313 - 318.
  4. Go to the main index.php, it is the first index.php and located in the same directory with the sub-directories 'application', 'system', 'user_guide', etc. 
  5. Put 'session_start()' right after < ?php
Hope this can help you....

Senin, 30 Oktober 2017

Cross-Origin Resource Sharing (CORS) Problem in Codeigniter

Facing a problem with CORS while developing a web with Codeigniter, the console keeps giving this error message "...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource"

I browsed and tried many solutions posted in web, many failed to solve my problem. Finaly, I found a solution that works, at least for me. This is the link, where I found the solution. Link

So this is the solution:

Open "config.php" which is located in ../application/config/config.php .
Under Base Site URL, change existing configuration with this:

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);


This works like a charm....
Hope this can help you somehow...

Selasa, 27 September 2016

HTML5 Server Sent Event in Codeigniter

There are many sources describing about SSE in HTML5 and also with the code that can be downloaded. One source that I can recommend to read is this. W3school also describes SSE in a short, simple and clear explanation.

But, there are not many websites that gives tutorial using SSE in Codeigniter. I'm working on a project using Codeigniter that requires SSE to display a dynamic data. It was quite difficult for me at the beginning to implement SSE in MVC-way, since all the codes that I got from some tutorials are not programmed in MVC-way. 

Maybe it is not the best way to implement SSE in Codeigniter, but at least it works. 

At the client side I have a javascript code shown below that allows client to "subscribe" a stream of data from the server. I send JSON data from server.

var source = new EventSource("❬?php echo site_url('c_sse/loaddata');?❭");
    
  source.addEventListener("message", function(e) {
   document.getElementById("status").innerHTML = "MESSAGE";showdata(e);
   }, false);
   
  source.addEventListener("open", function(e) {
   document.getElementById("status").innerHTML = "OPENED";
   }, false);

  source.addEventListener("error", function(e) {
   document.getElementById("status").innerHTML = e.readyState;
   if (e.readyState == EventSource.CLOSED) {
    document.getElementById("status").innerHTML = "CLOSED";
     }
   }, false);
 } else {
  document.getElementById("notSupported").innerHTML = "SSE not Supported";
 }
}
  
function showdata(Jdat)
{
 var data = JSON.parse(Jdat);
   
 document.getElementById("result").innerHTML = data.name;
}
 

The MVC style code is already seen in there. Check the EventSource above, that is the way I call the function "loaddata" inside controller c_sse.php.

At the server side, I started to code from the controller. The function that is responsible for sending the data (for example) called "loaddata". The most important thing of SSE in server side are the first three line with "header" in the code. Those should be placed in this function and they will cause Error if I put those in the Viewer. So, here is how the function "loaddata" looks like.


function loaddata()
{
 header("Content-Type: text/event-stream");
 header("Cache-Control: no-cache");
 header("Connection: keep-alive");
  
 $this-❭load-❭model('m_sse');
 while(true)
 {
  $data['mydata']=$this-❭m_sse-❭compute_dashboard_data();
  $this-❭load-❭view('sse_view_fast',$data);
  sleep(1);
 }
}


m_sse is the model for computing the data. In my case the return's value of the function 'compute_dashboard_data( )' is JSON data.

The one who is responsible to flush the data to Client is the viewer. Wrongly coded in the viewer can make the performance of SSE much slower. Firstly, I'll show the code resulting slow SSE. Oh ya, I forgot to mention the syntax. The real data should be put behind the "data:".

the source code for sse_view_slow.php:

print "data:".$mydata;
ob_flush();
flush();

If you implement that code, you'll have to wait couple seconds or maybe even couple minutes until the data shown.

Better use this code:

sse_view_fast.php

print "data:".$mydata.PHP_EOL;
print PHP_EOL;

ob_end_flush();
flush();

Actually, that is it for the programming. That is how I implement SSE in Codeigniter.


Sabtu, 01 November 2014

foreach-loop in php

Menjawab pertanyaan "foreach-loop". Perhatikan berikut:
------------------------------------------------------------
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
-------------------------------------------------------------
foreach bekerja dengan membaca satu-persatu index array. Pada kasus diatas,
loop 1 dia membaca $a[one]
loop 2 dia membaca $a[two]
dst.
untuk interpretasi "foreach ($a as $k => $v)". $a adalah nama arraynya, $k adalah variabel nama index array disimpan dan $v adalah variabel dimana nilai dari array $a index ke- $k disimpan.
Jadi output dari code diatas adalah
$a[one] => 1.
$a[two] => 2.
$a[three] => 3.
$a[seventeen] => 17.
Semoga bisa membantu.

Minggu, 02 Maret 2014

Codeigniter on Xampp

Catatan Pribadi: menggunakan Codeigniter pada Xampp.

Referensi: http://iamnewtocodeigniter.wordpress.com/tag/setting-up-codeigniter-on-xampp/

  1. Download XAMPP 
  2. Download CodeIgniter
  3. Unzip CodeIgniter dan rename foldernya
  4. Paste foldernya kedalam xampp/htdocs
  5. Jalankan xampp. 
  6. buka browser dan masukan pada url "localhost/testpro"
  7. halaman pembuka "welcome page" dari code igniter seharusnya terbuka sekarang. 

Senin, 28 Oktober 2013

Can't access phpmyadmin

Selalu, setelah install XAMPP langsung googling "can't access phpmyadmin". Dari pada ribet googling, bikin catatan pribadi aja di blog.

OK, setelah berhasil install XAMPP. Cari file httpd-xampp.conf
Linux: /opt/lampp/etc/extra/httpd-xampp.conf
windows:???? (belum tahu, hehehe...)

ubah isi salah satu bagian seperti dibawah ini

# since XAMPP 1.4.3

    AllowOverride AuthConfig Limit
    Order allow,deny
    Allow from all
    Require all granted


Setelah itu, restart xampp.
/opt/lampp/lampp restart