Tampilkan postingan dengan label AJAX. Tampilkan semua postingan
Tampilkan postingan dengan label AJAX. Tampilkan semua postingan

Kamis, 14 Desember 2023

javascript forEach on json object

 For everyone who is fucked up with forEach on JSON object. 

Find solution in this link

https://codedamn.com/news/javascript/how-to-fix-typeerror-foreach-is-not-a-function-in-javascript

or something like this

 

                        var myval = JSON.parse(results);


                        Object.entries(myval).forEach(entry => {
                            [key, value] = entry;
                            console.log(entry);
                        });

Jumat, 04 Februari 2022

Datatable : Adding a Row Dynamically and adding its atrribute

Ok, I had a problem to solve the problem I mentioned in the title of this post. 

So, I combined two solution from two sources (Actually I've browsed to several websites and discussions). 

These are my sources: Source 1, Source 2.

I use ajax to retrieve the data and then add them dynamically to the table. Then, I want to align the text to center and add onclick event on each row.

So here is my Table:


<div class="table-responsive">
	<table class="table table-striped table-bordered" 
    	id="transaction_detail" cellspacing="0" width="100%">
		<thead>
			<tr class="text-center align-middle">
				<th>Name</th>
				<th>email</th>
				<th>Phone</th>
				<th>Transactions</th>
				<th>Turnover</th>

			</tr>
		</thead>
		<tbody >

				
		</tbody>
	</table>
</div>


And here is my Ajax:


$.ajax({
  type:"POST",
  url:"/gettransaction",
  data:{customer_id: customerid},
  success:function(data){
	var jsondat = JSON.parse(data)  ;
	
	//clear the table's body
	$("#transaction_detail").DataTable().clear().draw();

	if(jsondat.length > 0){
		for(var i=0; i<jsondat.length; i++){
			
			var rowTab = $("#transaction_detail")
				.DataTable()
				.row
				.add([
				jsondat[i].customer_name,
				jsondat[i].customer_address,
				jsondat[i].customer_phone,
				jsondat[i].number_transaction,
				jsondat[i].turnover
			]);


			//use node() so that row is editable.
			var rowEdit = rowTab.node();

			$(rowEdit).attr("style", 
				"cursor:pointer; text-align:center");
			$(rowEdit).attr('onclick',
            	"showTrans("+jsondat[i].customer_id+")");

			//redraw the table after its modified
			rowTab.draw(false);
		}   

	}
  },
  error: function(){

  }
});


I hope it can help you somehow. cheers!!

Minggu, 30 Agustus 2020

Save PNG image from HTML5 Canvas (the correct way, proved working!!)

This post is kind of a continuation of my previous post 'Take A Picture From Webcam With HTML5'. I had then an issue how to save the image localy. The image taken from the webcam is saved in base64 encoded data with this format data:image/png;base64,AAAFBfj....[base64 encoded data]

After I googled around, the most solution that I found told me just seperate the base64 data from that format and decode it directly to save the image. Unfortunately, its not that easy!!!

shortly, I'll show you how to do it correctly. This solution is shown here. Thanks mas bro Fazlurr!! you are the best.

again, I developed the application using Codeigniter and the code I show here is the function to save the image localy. This function is called by an AJAX function. 



function saveImage(){
     $img = str_replace('data:image/png;base64,', '', $_POST['data']);
     $img = str_replace(' ', '+', $img);
     $data = base64_decode($img);
     $file = FCPATH.'/image/page/'.$_POST['name'].'.png';
     $success = file_put_contents($file, $data);
     echo $success ? '1' : '0';
}



the AJAX send  two POST data; the image data taken from canva and the name used for this image. Take a look at the third line, this line is the key. Other solutions found in google don't have this line, so most of them failed to save the image correctly. 

Well, the funny thing is that I know it works but I don't know what does that third line do, so dont ask me why this code works...ehehehe....

Senin, 27 April 2020

AJAX in JQuery

Again, it is just a quick post that helps me recall something that I forget easily. Here is the syntax for AJAX in JQuery. I have seen 2 types of AJAX syntax in JQuery, for me this syntax is much easier to understand.


$.ajax({
            type:"POST",
            url:"urlToAjax.php",
            data:{
              "data1":dat,
              "data2":dat2 
            },
            success : function(results) {
              console.log(results)
              //any code if succeed goes here 
            },
            error : function(res){
              console.log(res)
              //any code to generate error report goes here
            }
  });


The code above sends Request using POST.

That's all folks.

Sabtu, 20 Januari 2018

Check whether javascript function exists

if(typeof clearToday !== 'undefined'){
      clearToday();
}

above will check if function clearToday exists before the function executed.

Storing Javascript value into PHP

Short note!
I'm programming a web app for a health clinic and I just had a problem to give a notification sound for the doctor if new patient registered.

I use SSE to update the list of the queuing patients. The number of the queuing patients will be reduced if one patient is served and added if a new patient registered. The notification sound should be ringed once when a new patient registered.

The question is, where should I put the update function since I save the header, the side menu and the body (content) separately.

If I put the update function in the body, the problem is I have to put the update function in every page. Well it is actually not a problem, it is just funny to put the same function in every page.

So I decide to put the function in the header, since every page uses the same header. The problem is wherever I browse through the web app, the notification sound just may only be ringed once!!!! That means, I have to store the current number of the queuing patients as a session variable. That is the solution, but the problem is how I can do that since the Javascript updating the number..???!!!!

For the record, Javascript is client side and php is server side. So it is imposible to save Javascript value into PHP, if I do it via Javascript. That is the second clue. I have to pass the Javascript value to PHP somehow and let the PHP stores the value to a session variable.

So this is how I do that:

  1. Storing: Use AJAX to pass the Javascript value to PHP
  2. Storing: Since I am using MVC, I make a function in Controller just for storing the value to a session variable.
  3. Fetching: Make a Javascript function to fetch the value of the session variable and call it on loading windows. Storing PHP value into Javascript variable should not be a problem. 
  4. Fetching: Put the AJAX function inside SSE and call it if the number of queuing patient is added.

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'];
}