Make ajax function as global

by Guna 2013-02-06 11:23:40

Hi,

We often use jquery ajax functions in our web projects. If we can make this ajax function as global one and pass only parameters to that function we can save lot of time. Have a look at this code,

<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>

<script type='text/javscript'>

//Global method for making ajax-request
function make_request(qdata){
$.ajax({
type : 'GET',
url : "http://mysite/handler.php",
cache : false,
data : qdata,
dataType : "json",

success : function(jresult){
process_data(jresult,qdata.q);
},

error : function(XMLHttpRequest, textStatus, errorThrown) { alert(errorThrown); }
});

}

function process_data(result,query){
if(result.process=='error'){
alert(result.errmsg);
return;
}

if(query=='auth')
alert('Your login successfull');

}

//parameter that has to be sent to the server
var qvar={ "ema" : "guna","pass" : "mypass", "q" : "auth" };

//make an ajax request
make_request(qvar);

</script>


if you need to make another ajax call with different parameters, you can just do:

//parameter that has to be sent to the server
var qvar={ "param1" : "value","param2" : "value", "q" : "test" };

//make an ajax request
make_request(qvar);


In the above example we are sending some values to "handler.php". This function always expects a json object as output from handler.php. handler.php should be coded similar to this one:

Incase the requested process is failed,

$result=array("process"=>"error","errmsg"=>"login failed");
echo json_encode($result);


When requested process success,

$result=array("process"=>"success");
echo json_encode($result);

Tagged in:

1625
like
0
dislike
0
mail
flag

You must LOGIN to add comments