jquery passing array data to function - javascript

I have made a function to get the variable of onclick and pass it to the function, but I want it in different format:
$('.ajax').live('click', function() {
var Loading = 'Loading...';
var url = $(this).attr('href');
var container = '#myDivcontent';
looadContents(url,Loading,container);
return false;
});
and the function looks like :
looadContents(url,Loading,container) {
..
...
$(contaner).load(url);
...
..
}
I would like to have like array format or json data format when I call the function:
$('.ajax').live('click', function() {
looadContents({
url : $(this).attr('href'),
Loading : 'Loading...',
container: '#myDivcontent'
});
return false;
});
Any idea how can I do this?

If you pass the information like an object, you can simply access it as one:
function looadContents(options) {
$(options.container).load(options.url);
}
looadContents({ url: '...', container: '#...' });

This syntax works as expected.
function display(obj)
{
console.log(obj.name + " loves " + obj.love);
}
display({name:"Jared", love:"Jamie"});

Is this possibly what you are looking for?
function looadContents(o) {
alert(o.url);
alert(o.container);
}
looadContents({ url:"abc", container: "def" });

Use what's sometimes called an "options" object (what you refer to as "JSON data format" is simply a JavaScript object literal):
function loadContents(options) {
var url = options.url;
var Loading = options.Loading;
/* etc. */
}
You can also leverage this approach to provide default values for certain parameters:
function loadContents(options) {
var url = options.url || "http://default-url.com/",
var Loading = options.Loading || "Loading...";
var container = options.container || "#container";
$(container).load(url);
}

Try this
looadContents(input) {
//...
$(input.contaner).load(input.url);
//...
}

Related

How to preload JSON link?

I've got a function that needs to call a link (JSON format), the fact is that I would like to be able to preload this link to smooth and reduce the operation time when calling the function.
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
colorMe(data.target)
}
});
}
function colorMe(item){
globalItem = item;
request('http://blablabla/?format=json',findMaterial);
};
function findMaterial(data){
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};
function findMatchArea(areas){
jq310.each(areas, function(area) {
blablabla
The request function that I built just look if the link as been already called, so it's reloading it if true. And also send data from the link to the called function.
If you'r looking to load a static json file you should concider loading it on the top of your file. To do so you should store the datas in a global variable like that :
let datas;
request('http://blablabla/?format=json', (data) => {
datas = data
});
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
globalItem = data.target;
findMaterial();
}
});
}
function colorMe(item){
globalItem = item;
};
function findMaterial(){
const data = datas;
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};
I finally found a way to do it properly, here it is :
var mylink = 'https://fr.wikipedia.org/wiki/JavaScript';
function preloadURL(link){
var xhReq = new XMLHttpRequest();
xhReq.open("GET", link, false);
xhReq.send(null);
var jsonObject = JSON.parse(xhReq.responseText);
return jsonObject;
};
jsonObjectInv = preloadURL(mylink);
And I just point to my json variable to parse it (really faster)
function colorMe(item){
globalItem = item;
findMaterial(jsonObjectInv);
};
Problem solved

Set variable from function with possible ajax-load inside?

I have made my own script for loading content with AJAX if nor already loaded. Here it is:
/*
* AJAX Load Content
*/
var loaded_content_urls = {};
function get_content_from_url(url)
{
if (loaded_content_urls[url] === undefined)
{
$.ajax({url: url}).done(function(data)
{
loaded_content_urls[url] = data;
return data;
});
}
else
{
return loaded_content_urls[url];
}
}
And I wanna use it like this:
var loaded_html = get_content_from_url($(this).attr('href') + '?ajax');
But that won't work great since it can take a while for the content to be loaded and the variable above needs the value directly. So how should I do this?
I did a search about the issue but only found solutions where you always loads the content with AJAX. My code is special in that way that it first checks if the content already have been loaded. So I can't just have the AJAX function as return of the function.
Try using https://api.jquery.com/deferred.promise/
Your example code should like below:
var urlData = ''
function get_content_from_url (url) {
var _defer = jQuery.Deferred();
if( urlData === undefined){
$.ajax({url: url}).done(function(data){
urlData = data;
_defer.resolve(urlData);
});
} else{
_defer.resolve(urlData);
}
return _defer.promise();
};
$.when(get_content_from_url(url)).then( function( data) {
var loaded_html = data;
});
I will also suggest to use reject and fail method to handle error scenarios

An efficient way to call type specific functions

this is my situation:
I have a Field.js file which contains a bunch of classes (made with this plugin) each corresponding to a datatype on the page.
An example of a class:
$.Class("Types_UserId_Js",{
init_done : false,
validate : function (value){
return true;
}
},{
container : "",
UserIdDisplay : function (){
var associations = [];
var uid = 0;
$( container ).find(".userid_display").each(function(index,el){
uid = $( this ).find(".userid_value").val();
url = siteurl + "/dname?";
$.ajax({
type: "POST",
url: url,
data: ajaxData,
dataType: "json",
success: function(result, status){
associations[uid] = result;
}
});
});
},
init : function ( container ) {
if(container.length > 0 && !Types_UserId_Js.init_done){
this.container = container;
this.UserIdDisplay();
Types_UserId_Js.init_done = true;
}
};
});
(It's a dummy class for now).
I also have some html code that renders the types UI, in a standard format.
In the end, I have a page with a bunch of different types of inputs, and they all need their specific init function to be called in order to render properly.
What I did up to now is simply invoke EVERY init function in the Field.js file, like so:
$( document ).ready(function(ev){
var cont = $("#container");
var uid = new Types_UserId_Js(cont);
var text = new Types_Text_Js(cont);
// And so forth
});
I'd really like to know if there is a more efficient way to call every init function in the file without having to call them individually.
The Field.js is part of the main framework, and it is maintained by a third party developer so, while I can and do edit it to my leisure, I'd prefer to keep the generic structure that they imposed.
Thank you,
I think you'd need some mapping field <-> function. You can add data-attributes to the fields with the name of the fields init function. Then you can just loop over your fields, get the value and execute the function.
Check the following snippet:
// helper function borrowed from http://stackoverflow.com/a/12380392/4410144
var getFunctionFromString = function(string) {
var scope = window;
var scopeSplit = string.split('.');
for (i = 0; i < scopeSplit.length - 1; i++) {
scope = scope[scopeSplit[i]];
if (scope == undefined) return;
}
return scope[scopeSplit[scopeSplit.length - 1]];
}
var myFunction = function() {
console.log('myFunction');
}
var myOtherFunction = function() {
console.log('myOtherFunction');
}
$('input').each(function() {
var initFunction = getFunctionFromString($(this).data('function'));
initFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-function="myFunction" />
<input data-function="myOtherFunction" />

Class method in javascript is not a function

The answer must be obvious but I don't see it
here is my javascript class :
var Authentification = function() {
this.jeton = "",
this.componentAvailable = false,
Authentification.ACCESS_MASTER = "http://localhost:1923",
isComponentAvailable = function() {
var alea = 100000*(Math.random());
$.ajax({
url: Authentification.ACCESS_MASTER + "/testcomposant?" + alea,
type: "POST",
success: function(data) {
echo(data);
},
error: function(message, status, errorThrown) {
alert(status);
alert(errorThrown);
}
});
return true;
};
};
then I instanciate
var auth = new Authentification();
alert(Authentification.ACCESS_MASTER);
alert(auth.componentAvailable);
alert(auth.isComponentAvailable());
I can reach everything but the last method, it says in firebug :
auth.isComponentAvailable is not a function
.. but it is..
isComponentAvailable isn't attached to (ie is not a property of) your object, it is just enclosed by your function; which makes it private.
You could prefix it with this to make it pulbic
this.isComponentAvailable = function() {
isComponentAvailable is actually attached to the window object.
isComponentAvailable is a private function. You need to make it public by adding it to this like so:
var Authentification = function() {
this.jeton = "",
this.componentAvailable = false,
Authentification.ACCESS_MASTER = "http://localhost:1923";
this.isComponentAvailable = function() {
...
};
};
Another way to look at it is:
var Authentification = function() {
// class data
// ...
};
Authentification.prototype = { // json object containing methods
isComponentAvailable: function(){
// returns a value
}
};
var auth = new Authentification();
alert(auth.isComponentAvailable());

How to replace function params?

I'm using the following code to make ajax call where the form data is passed as params.
//ajax call
function restServiceCall(origin,destination,tripType,dateDepart,dateReturn){
dataString = 'origin='+ origin + '&destination=' + destination + '&tripType='+tripType;
$.jsonp({
"url": flightURL,
callbackParameter:jsonpCallBack,
data: dataString,
beforeSend:function(){$('#loadingdiv').show()},
"success": function(data) {
if(data.error != null){
$('#errtitle').html('<h2 class="pgtitle">Error !! '+data.error+'</h2>').show();
$("#displaydiv,loadingdiv").hide();
}else{
renderData (data,dateDepart,dateReturn);
}
},
"error": function(xOptions, textStatus) {
$('#errtitle').html('<h2 class="pgtitle">Sorry the service you are looking for is currently unavailable</h2>').show();
$("#displaydiv,loadingdiv").hide();
}
});
}
Besides making the call from form I also use it in the following function wherein I just need to pass either the dateDepart/dateReturn as params.
//for pagination
$('.pagenation a').bind('click',function(){
var numDays = 7;
var self = $(this);
var dateTemp = self.parents(':eq(1)').attr('id')=="onewaytripdiv"? parseDate(dateDepart):parseDate(dateReturn);
if(self.hasClass('left')){
var tempDepDate = removeNumOfDays(dateTemp,numDays);
}else{
var tempDepDate = addNumOfDays(dateTemp,numDays);
}
var changedDate = tempDepDate.getDate()+' '+cx.monthNamesShort[tempDepDate.getMonth()]+' '+tempDepDate.getFullYear();
if(self.parents(':eq(1)').attr('id')=="onewaytripdiv"){
dateDepart = changedDate;
}else{
dateReturn = changedDate;
}
restServiceCall(origin,destination,tripType,dateDepart,dateReturn);
});
I would like to remove the params in the function call, as the params may vary. Please suggest an alternative to pass the params.
How about passing an array of parameters instead? And then pass another value, such as an integer to indicate to the function what to expect in it's parameter array.
e.g
restServiceCall(myParams, 0);

Categories

Resources