how to create a javascript rusable class to pass parameters to ajax - javascript

im new in JS,im looking for a way to create a class or function,reusable everywhere in my code,just pass it parameters and get the result,because currently I am doing like this:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": tmpString }),
success: function (result) {
})}
I write this every time I need, and im sick of it,

function sendAjaxCustom(DataType,Type,Url,Ctype,Data){
$.ajax({
dataType: DataType,
type: Type,
url: Url,
contentType: Ctype,
data: Data,
success: function (result) {
return result;
})}
}
You can call this function in JS like
var result = sendAjaxCustom("json","POST",'#Url.Action("power","Ranking")',"application/json; charset=utf-8",JSON.stringify({ "regionalManager": tmpString }));
you will have the result in result variable.

You can create a function like this
function ajax(url, data) {
$.ajax({
dataType: "json",
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
})}
}
Pass the url if it's dynamic and the object data on the second parameter.

Just create a simple function with your variables that need to change between calls and return the $.ajax result from there.
function ajaxWrapper(url, data, callback) {
return $.ajax({
dataType: 'json',
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: callback
});
}
When you want to call it:
ajaxWrapper('http://www.google.com/', { hello: 'world' }, function(result) {
console.log(result);
});
With the callback it's much more reusable, since you can use this anywhere and change what you do on completion of the function wherever you use it.

A simple solution is to return an object and pass it to the ajax and if some change is required then you can update the properties of the object before calling the ajax service
function commonAjaxParams() {
return {
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
//and so on that are common properties
}
}
//now in your application first call the function to get the common props
var commonParams = commonAjaxParams();
//change or add an parameter to your liking
commonParams.type = 'GET';
commonParams.success = function(){...} //if this action is need
commonPramss.error = function(){...}
//now call you ajax action
$.ajax(commonParams)

There is another way in which you may call the ajax function and you may get success, fail response return.
The benefit is you manage success or fail response independently for each ajax request.
$(document).ready(function() {
function ajaxRequest(dataType, requestMethod, dataURL, jsonData) {
return $.ajax({
dataType: dataType,
type: requestMethod,
url: dataURL,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData)
});
}
var jsonData = {
"regionalManager": "jason bourne"
};
ajaxRequest(
"json",
"POST"
"#Url.Action('power','Ranking')",
jsonData)
.success((data) {
console.log("success");
}).error((err) {
console.log("error");
}).done(() {
console.log("done");
});
});

Related

Ajax post doesn't pass any data to MVC controller

This:
$.ajax({
url: '/Merchant/SaveDirty',
type: 'POST',
dataType: 'json',
data: ko.toJSON(dirtyItems),
contentType: 'application/json; charset=utf-8',
success: function (data) {
// get the result and do some magic with it
//var message = data.Message;
alert(ko.toJSON(dirtyItems));
}
});
...currently calls this:
[HttpPost]
public void SaveDirty(string json)
{
}
...but when I hit the breakpoint in SaveDirty, no data is passed. I've verified that ko.toJSON(dirtyItems) returns a JSON string in the javascript. What am I doing wrong?
Thanks!
#KillingsWorth, is there any specific reason for which you are posting a JSON string? If not then, you could create a class corresponding to dirtyitems type and in your controller method you can accept a list of dirtyItems.
Class DirtyItem
{ // dirty item properties }
[HttpPost]
public void SaveDirty(List<DirtyItem> dirtyItems)
{
}
you can use the following:
$.ajax({
url: '/Merchant/SaveDirty',
type: 'POST',
dataType: 'json',
data: JSON.stringify(dirtyItems),
contentType: 'application/json; charset=utf-8',
success: function (data) {
///
///
}
});
But if you are using knockout.js in your applicantion then you should do the following:
$.ajax({
url: '/Merchant/SaveDirty',
type: 'POST',
dataType: 'json',
data:JSON.stringify(ko.mapping.toJS(dirtyItems)),
contentType: 'application/json; charset=utf-8',
success: function (data) {
// get the result and do some magic with it
//var message = data.Message;
alert(ko.toJSON(dirtyItems));
}
});
This should works:
$.ajax({
url: '#Url.Action("SaveDirty", "Merchant")'
type: 'POST',
dataType: 'json',
data: JSON.stringify(dirtyItems),
contentType: 'application/json; charset=utf-8',
success: function (data) {
// get the result and do some magic with it
//var message = data.Message;
alert(ko.toJSON(dirtyItems));
}
});

How to kill or cancel an asynchronous call in javascript?

I'm sending the following request to an MVC controller:
var datum = { param1: value, param2: value, param3: value };
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: getAbsolutePath() + "Controller/MethodName",
dataType: "json",
data: JSON.stringify(datum),
success: function (response)
{
var result = response;
}
});
Sometimes response takes too much time. I'm looking for a way to kill or cancel this request. How can I achieve this?
jquery .ajax returns normalized XMLHttpRequest, just use its abort method:
var xhr = $.ajax(params);
xhr.abort();
My suggestion, use the timeout property:
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: getAbsolutePath() + "Controller/MethodName",
timeout: 100000, //cancels automatically after 100 seconds
dataType: "json",
data: JSON.stringify(datum),
success: function (response)
{
var result = response;
}
});
You can use .abort() to cancel the request:
var xhr = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: getAbsolutePath() + "Controller/MethodName",
dataType: "json",
data: JSON.stringify(datum),
success: function (response) {
var result = response;
}
});
xhr.abort();
https://api.jquery.com/jQuery.ajax/
you could use timeout property for ajax to cancel the request if it takes too much time
Refer http://api.jquery.com/jQuery.ajax/

AJAX POST JSON value

I have AJAX POST, the result is JSON:
$.ajax({
type: "POST",
url: "../../api/test",
data: JSON.stringify(source),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var upload = JSON.stringify(result);
console.log(upload);
}
});
The upload result is:
{"Link":0,"Title":"d","Description":"dada","Keywords":"dad"}
How can I get the value of Title?
Do not stringify the result, just use result.Title.
As you already have JSON string, It's simple as a pie!
All you need to do is to call the property you want from the variable you assigned your result to.
for example:
var post_response;
$.ajax({
type: "POST",
url: "../../api/test",
data: JSON.stringify(source),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
post_response = JSON.stringify(result);
console.log("Title: "+post_response.Title);
}
});
hope this helps.

proper way to fill js variables via ajax request

At the moment i am using the follwing way to fill my global js variables with data which is obtained by json:
var tranlationJson =
$.ajax({
type: "GET",
url: "translation.xml",
contentType: "text/xml",
dataType: "xml",
success: function (dataSource) {
tranlationJson=ToJasonParser(dataSource);
}
});
Is there a more clever way? I need those variables filled because in the scrips which are loaded later i use their content.
You can make tranlationJson an object instead of variable like this:
var tranlationJson = {
init: function(){
$.ajax({
type: "GET",
url: "translation.xml",
contentType: "text/xml",
dataType: "xml",
success: function (dataSource) {
this.data = ToJasonParser(dataSource);
}
});
}
then call init function like this:
tranlationJson.init();
then you can access Json response data like this:
tranlationJson.data.something;
Demo

Functions with Variable Arguments in javascript/jQuery

I need and advice.
This is my issue, I have "N" functions.
var FirstOne = function(){
return $.ajax({
type: "POST",
url: hrefUrl,
data: JSON2.stringify(option),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(status){
},
success: function(data){
}
});
};
var SecondOne = function(){
return $.ajax({
type: "POST",
url: hrefUrl,
data: JSON2.stringify(option2),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(status){
},
success: function(data){
}
});
};
.............
var NOne = function(){
return $.ajax({
type: "POST",
url: hrefUrl,
data: JSON2.stringify(optionn),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(status){
},
success: function(data){
}
});
};
all these function arr pushed in an object which is this .
var funcObject= [FirstOne(), SecondOne(), ....... NOne() ];
after I am waiting when all Ajax functions are done with and and after I am fine.
$.when.apply($, funcObject).done(function (a1, a2, ...an) {
// ..... here already doesn't matter
});
my issue is here:
function (a1, a2, ...an)
I want to have instead function arguments an object because I do not know how many function is going to be.
So i can edit function object, which is cool $.when.apply($, fucArr), problem is to use variable numbers of arguments .
PS: Maybe I can use "apply" or "call" for these arguments as well?
Can someone give me an idea here. Thanks A lot guys!!!
You can access all arguments passed to a method using the arguments keyword eg:
function () {
Console.log(arguments); //arguments is an array
}
The apply method can be used to use these arguments in another function call:
function () {
someFunction.apply(this, arguments);
}

Categories