For smart Primates & ROBOTS (oh and ALIENS ).

Blogroll

Wednesday, January 07, 2015

ajax in jquery

The simple way to use ajax in jquery is below:

$.ajax({
        type: 'GET', async: false, cache: false, timeout:5000, url: 'ajax_util.php?'+new Date().getTime(),
        data: { f_for: 'get_topic_by_lesson_id',lesson_id:1},
        dataType: 'json',
        success: function (data) {    
            $.each(data.get_topic, function(idx, obj) {
                var topic_id=obj.topic_id;
                var topic_nm_val=obj.topic_nm;
            $('#topic_nm').append('<option value="' + topic_id + '">' +topic_nm_val+ '</option>'); 
            });
        }
    });

The problem is that here we are passing type, async,cashe timeout,data and dataType each time. so can we short cut it? yes we can shortcut it as below:

var variableAndValue={f_for: 'full_test',class_id:class_id,subject_id:subject_id };
var data=myajaxGetJSON('ajax_util.php?'+new Date().getTime(),variableAndValue);

Definition of  myajaxGetJSON function is as below:

function myajaxGetJSON(url,f_for) {
     var result="";
     $.ajax({
        type: 'GET', async: false, cache: false, timeout:5000, url: url,
        data: f_for,
        dataType: 'json',
        success: function (data) {
        result = data;    
        }
    });
    return result;
}
In above function you can use POST instead of GET method.

How use above function?

var class_id=1;
var  subject_id=1;
var variableAndValue={f_for: 'get_emp',class_id:class_id,subject_id:subject_id };
var data=myajaxGetJSON('ajax_util.php?'+new Date().getTime(),variableAndValue);
$.each(data.list_of_emp, function(idx, obj) {
//////   the obj variable is holding all the data
        var q_id=obj.q_id;
        var question_parts=obj.question_parts;
        var question_path=obj.question_path;
        var mark=obj.mark;
});

What about in the 'ajax_util.php'  

$f_for=$_GET['f_for'];
if($f_for=="get_emp") {
        $class_id=$_GET['class_id'];
        $subject_id=$_GET['subject_id'];
        $rs=$full_test->get_one_full_book_random($class_id,$subject_id,$marks,$not_ids);
        // The $rs is holding the data result set from mysql
        $rows = array();
        while ($row = $rs->fetch_array(MYSQLI_BOTH)) {
            $rows[]=$row;
        }
        print '{"list_of_emp":'. json_encode($rows).'}';
}






Share:

0 comments:

Post a Comment

How to make center align child div

 How to make center align child div?   Suppose you have 2 Div tag. And want the make inner tag center <div id="d1">      ...

Ads Inside Post

Powered by Blogger.

Arsip

Blog Archive