I am writing a Javascript program which can query data from more than one servlets each sec. If it queries from one servlet, I know how to do it in xxx.js file:
var TPS_URL = "http://localhost:8888/tps";
var jQueryFunction = function()
{
$.ajax
({
type: "GET",
async: false,
url: TPS_URL,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
.......
}
});
};
setInterval(jQueryFunction,1000);
But now I have another servlet to query. How can I add another servlet into this js file? Just simply create another "TPS_URL_2" and "jQueryFunction_2", and do the same thing above?
var TPS_URL_2 = "http://localhost:9000/tps";
var jQueryFunction_2 = function()
{
$.ajax
({
type: "GET",
async: false,
url: TPS_URL2,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
.......
}
});
};
setInterval(jQueryFunction_2,1000);
??
Also, if I get a result from the first url and also another result from the other url, and I want to SUM them together, how can I do it?
set the URL as a parameter to the function and call this function as many times as you need
var jQueryFunction = function(xurl)
{
$.ajax
({
type: "GET",
async: false,
url: xurl,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "tpsHandler",
success: function(json)
{
.......
}
});
};
Call it like this
setInterval( function(){ jQueryFunction('some url') },1000);
Related
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");
});
});
how can I call ajax request or any function simple in new thread?
I know about async: false but my code has this structure:
1.user click on some item, and this fire click event
2.in event I call this function
var myData= {};
$.ajax({
type: "GET",
url: "...",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
success: function (s0) {
myData.s0= s0;
$.ajax({
type: "GET",
url: "sss",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
success: function (s1) {
myData.s1 = s1;
$.ajax({
type: "GET",
url: "...",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
success: function (s2) {
myData.s2= s2;
}
});
}
});
}
});
// I need call this function when all ajax are done.
myFunc(myData);
My current code works but causes the web freezes until data are not downloaded beaouse I have asyn: false but I do not know how to solve it asynchronously
Optimal solution for me is call this freezing and display loading gif until done.
Well there is no fix for UI freeze during a synchronous AJAX so you might want to try web workers but it has its own caveat .I would suggest you to use jquery promise so that you don't need to define separate success ,error callbacks .A promise is guaranteed to yield so at the end of chain either you will have values in myData or not but it won't hangup forever
//show loader
$.ajax({
type: "GET",
url: "...",
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
dataType: "json",
}).then(function( s0, textStatus, jqXHR ){
myData.s0= s0;
return $.ajax( {
type: "GET",
url: "sss",
async: false,
cache: false,
dataType: "json"} );
}).then(function( s1, textStatus, jqXHR ) {
myData.s1 = s1;
$.ajax( {
type: "GET",
url: "...",
async: false,
cache: false,
dataType: "json"});
}).then(function( s2, textStatus, jqXHR ) {
myData.s2= s2;
//hide loader
})
Read more
Change async:false to async:true on all ajax calls, show loading gif at the start of your function where you initialize myData and call the function you want to call when all data is loaded in the success function on the last ajax call (just after myData.s2 = s2)
This code gets a json object from another server.
How do I access the response outside of the function?
(function($) {
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'callback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
var data = json;
}
})
})(jQuery);
You can do something like this!
_outerMethod: function(data) {
//...do what you need to do
}, (function($) {
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'callback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
_outerMethod(json);
}
})
})(jQuery);
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/
I am unable to catch response from C# to jQuery using $.ajax. I get an error "SCRIPT ERROR". How can I catch response using JSONP? This is what i am using:
$.ajax({
async: true,
context: mrq,
cache: false,
type: "GET",
url: MYURL,
crossDomain: true,
dataType: 'jsonp',
data: MYDATA,
processData: false,
jsonp: "jsonREQ",
jsonpCallback: "onJSONPsuccess",
success: function (jsonText, textStatus) {}
});
As far as I understand, dataType: 'jsonp' means that as soon as it's returned it's put into the callback function as an argument. So, I'd try this:
onJSONPsuccess = function(response) {
// do something with response, e.g.
results = response["results"]
}
$.ajax({
crossDomain: true,
dataType: 'jsonp',
data: { /*params you're sending in*/ },
jsonp: "jsonREQ",
jsonpCallback: "onJSONPsuccess",
success: onJSONPsuccess
});
You say the server side is C# - are you using WCF? There's a great article here about it:
http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/
Basically you need to set up WCF (or whatever server-side code you're using) to return the json wrapped in a call to your callback function.
However, with jquery, you can simply add "?Callback=?" to your URL, change the dataType to 'jsonp', and forget about the rest of that stuff. You don't need the jsonp or jsonpCallback options set.
In contrast to a json request, the jsonp request will return your data not wrapped in a 'd' property, so your call back function is:
function(data) { var a = data.myProperty ... }
rather than
function(data) { var a = data.d.myProperty ... }
and the whole method is along the lines of:
var url = configuration.serviceUrl + "/" + method + "?callback=?";
var options = {
type: 'GET',
url: url,
data: args,
dataType: "jsonp",
contentType: "application/json",
success: function(data) {
if (callback != null) callback(data);
}
};
if (typeof errorCallback != 'undefined')
options.error = errorCallback;
$.ajax(options);