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.

Kamis, 09 April 2020

Creating JSON data in Javascript

Quick post about how to create JSON data in javascript.
I want to POST some inputs via AJAX but I want send them just in one variable, don't ask me why. I just want to do it that way.

here is my HTML code

<input id="name" type="text">

<input id="phone" type="text">

<input id="address" type="text">

I want send them as JSON data, here is how I do it:


var obj = new Object();
obj.name = document.getElementById('name').value;
obj.phone= document.getElementById('phone').value;
obj.address= document.getElementById('address').value;

var myData = JSON.stringify(obj);


That's it. the variable myData is the json data.