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
Related
I have an Ajax call that works fine, but I am now trying to polish the code a bit
$.ajax({
url: wbURL,
dataType: "xml",
contentType: "text/xml; charset=\"utf-8\"",
type: "POST",
headers: '#"HEADER DATA',
data: dataPacket,
success: dealWithResonse,
error: dealWithError
});
what I am now trying to do is replace the success and error function names with variables so I can use it for other jobs.
var SuccessFunctionCall = dealWithResonse;
var ErrorFunctionCall = dealWithError;
$.ajax({
url: wbURL,
dataType: "xml",
contentType: "text/xml; charset=\"utf-8\"",
type: "POST",
headers: '#"HEADER DATA',
data: dataPacket,
success: SuccessFunctionCall,
error: ErrorFunctionCall
});
But my program stops at this point, assumingly as it can't find a function called
ErrorFunctionCall.
can I use a variables vaule instead of an actual function name?
Thank you in advance
You may define those functions as global and assign them to what you want:
var SuccessFunctionCall = function(){dealWithResonse()};
var ErrorFunctionCall = function(){dealWithError()};
and call them as members of window:
success: window[SuccessFunctionCall](),
error: window[ErrorFunctionCall]()
Finally I have to say that I am not sure why you want to assign functions to variable names. You may define those functions directly and call them as you need.
You should define those functions in your variables as shown below:
$(document).ready(function(){
var SuccessFunctionCall = function dealWithResonse(){
console.log("success");
};
var ErrorFunctionCall = function dealWithError(){
console.log("error");
};
$.ajax({
url: 'http:test',
dataType: "xml",
contentType: "text/xml; charset=\"utf-8\"",
type: "POST",
headers: '#"HEADER DATA',
data: '',
success: SuccessFunctionCall,
error: ErrorFunctionCall
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
Try this
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");
});
});
A web-service is available at http://www.cs.sun.ac.za/rw334/products.php?
limit=12&skip=0
I want to get the data in there into a Javascript array. I've searched around and I think I should start like this?
$.ajax({
type: "GET",
url: "http://www.cs.sun.ac.za/rw334/products.php?limit=12&skip=0",
data: {id:id, name:name,url:url},
contentType: "application/json",
dataType: "json",
success: ??
}
});
How should I continue to get this data from the .php file into a Javascript array?
product = [];
$.ajax({
type: "GET",
url: "http://www.cs.sun.ac.za/rw334/products.php?limit=12&skip=0",
dataType: "json",
success: function(data) {
$(data.products).each(function(i, products){
product[products.id] = products.name;
});
console.log(product);
}
});
Here is my script:
$.ajax({
type: "Get",
url: "Sample.js",
datatype: 'json',
data: JSON.stringify({ key:key }),
success: function (data) {
var sample = data.name;
$("#html").html(sample);
},
error: function () {
alert("Error");
}
});
This is my Sample.js file:
{ "name": "user" }
When I run this code I get a blank screen. This is my script using getJSON():
$.getJSON("Sample.js", function (data) {
var sample = data.name;
$("#html").html(sample);
})
This produces "user" perfectly. What is the problem with $.ajax code?
In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.
As the jQuery documentation states:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Try modifying the dataType param.
change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/
Remove JSON.Stringify and change Get to GET
$.ajax(
{ type: "GET",
url: "Sample.js",
dataType: "json",
data: {key:key },
success: function (data)
{ var sample = data.name; $("#html").html(sample); },
error: function () { alert("Error"); }}
);
i am currenty using jquery plugin to read a data file (data.html)
data.html has below format
[10,20,30,40,50]
my jquery data request and the javascript to return values is below
function test(){
var result=$.ajax({
url:'data.html',
type:'get',
dataType:'text',
async:false,
cache:false
}).responseText
return result;};
var my=test();
alert(my[0])
i want to get these values in the array format i.e i want my[0] to be value 10, but instead i get "[".
If i use eval function
my=eval(test());
i can get 10, but is there any other better way to store the returned ajax calls into an array instead of string?
Thanks
i tried the below answer and i am bit puzzled, the follow code results in myArray is null (in firebug), but i put async:false then it works. why do i need async:false to store the values into array ? (http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req)
jQuery.extend({getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;}
});
return result;}});
myArray=$.getValues("data.html");
alert(myArray[1]);
You don't need eval. Just indicate the proper dataType: 'json':
function test() {
return $.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
async: false,
cache: false
}).responseText;
}
var my = test();
alert(my[0]);
or even better do it asynchronously:
function test() {
$.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
}
});
}
test();
I think jquery $.getScript('data.html',function(){alert("success"+$(this).text())} might be simpler. I have not had time to try it so if I'm on right track, improve this answer, if not I'm happy to learn now...