JSON Object variable declare, assign values and manage for ajax calling


Declare a json object variable:


  <script type='text/javascript'>
	var JSONArrayOptions = {};
  </script>  

Assign some values at variable:


 <script type='text/javascript'>
    JSONArrayOptions['first_name'] = 'Ziyed';
    JSONArrayOptions['last_name'] = 'Uddin';  
 </script> 

Preparation for ajax calling:


  <script type='text/javascript'>
     //converts a JavaScript value to a JSON string
     var JSONArrayOptionsSerialized = JSON.stringify(JSONArrayOptions); 
     jQuery.ajax({
	 type: "POST",
	 url: 'put_your_url_here',
	 data: { json_string: JSONArrayOptionsSerialized},
	 dataType: "html",
	 success: function(data) {            
	    //Write your code here after success            
	 }
      });
      return false;
  </script> 

Use the variable for operation at user end:


  <script type='text/javascript'>
    if (typeof (JSONArrayOptions['first_name']) != "undefined" && JSONArrayOptions['first_name'] !== null) {
        //Do your operation by getting the value 
	alert(JSONArrayOptions['first_name']);
     }	
  </script> 

Advertisements