Function as parameter in Jquery Ajax - javascript

Is it possible to put a function into a parameter for Jquery Ajax like below. dataType and data are given as functions. dataType returns a value of JSON if the returntype is JSON and text if isJson is false.
dataVal and dataVar are arrays containing the parameter names and values used to construct the data paramater. The result of the data: function would be a string as:
{dataVar[0]:dataVal[0],dataVar[1]:dataVal[1],.....,}
I'm getting an error when I try this, so, just wanted to know if this method was possible.
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
},
data: function () {
var dataString = '{';
for (var i = 0; i < dataVar.length; i++) {
dataString = dataString + dataVar[i] + ':' + dataVal[i] + ',';
}
console.log(dataString);
return dataString + '}';
},
success: function (res) {
dfd.resolve(res);
}
});
}
Edit
As per answers and comments, made the changes. The updated function is as below. This works:
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: isJson ? "JSON" : "text",
data: function () {
var dataString ="";
for (var i = 0; i < dataVar.length; i++) {
if (i == dataVar.length - 1) {
dataString = dataString + dataVar[i] + '=' + dataVal[i];
} else {
dataString = dataString + dataVar[i] + '=' + dataVal[i] + ',';
}
}
return dataString;
}(),
success: function (res) {
dfd.resolve(res);
}
});
}
And my original question is answered. But apparently, data is not getting accepted.
The return value of the data function is just treated as the parameter name and jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
So, my server is unable to pick up on the proper paramater name.

From the manual:
data
Type: PlainObject or String
So no.
Call the function. Use the return value.
data: function () { ... }();
// ^^ call the function

Not that way. But it will work with a little change:
(function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
})()
That should work. You just call the function immidiately after you created it. This way, dataType is a String and the script will work.
Same with data. Also use the (function(){})()-notation here

jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
No, your devtools display does. However, as you're data string does not contain a = sign, and you send the content as application/x-www-form-urlencoded, the whole body is interpreted as if it was a parameter name.
For sending JSON, you should:
use contentType: "application/json"
use data: JSON.stringify(_.object(dataVar, dataVal))1
to ensure valid JSON is sent with the correct header (and correctly recognised as such at the server).
1: _.object is the object function from Underscore.js which does exactly what you want, but you can use an IEFE as well:
JSON.stringify(function(p,v){var d={};for(var i=0;i<p.length;i++)d[p[i]]=v[i];return d;}(dataVar, dataVal))

You need to call the function with parenthesis like below:
function func1(){
//func1 code in here
}
function func2(func1){
//func2 code in here
//call func1 like this:
func1();
}
So, you can use like this:
data: function () {
//your stuff her
}(); // which mean you are having data()

Related

jQuery - use of a global function

In an HTML page, having two buttons (EDIT, DELETE), I do an AJAX call then I parse the returned JSON and I do perform an EDIT or a DELETE based on the returned ID. All this inside of a
$( document ).ready(function() {
...
$('button.icons8.icons8-edit-file').on("click", function(){
var key = $(this).attr('key');
$.ajax({
url: '/ede/' + key + '/json',
method: 'POST',
success: function (response) {
// PARSING THE JSON, EXTRACTING THE ID FROM IT
// AND PERFOMING THE EDIT
}
});
})
...
$('button.icons8.icons8-delete-file').on("click", function(){
var key = $(this).attr('key');
$.ajax({
url: '/ede/' + key + '/json',
method: 'POST',
success: function (response) {
// PARSING THE JSON, EXTRACTING THE ID FROM IT
// AND PERFOMING THE DELETE
}
});
})
...
});
What I would like to have is a global function what gets the key value, does the AJAX call and returns a value according to a pattern.
$( document ).ready(function() {
...
$('button.icons8.icons8-edit-file').on("click", function(){
var key = $(this).attr('key');
var value = GLOBAL_FUNCTION(key, pattern_edit);
// PERFOMING THE EDIT
})
...
$('button.icons8.icons8-delete-file').on("click", function(){
var key = $(this).attr('key');
var value = GLOBAL_FUNCTION(key, pattern_delete);
// PERFOMING THE DELETE
})
...
});
Where sould I put that GLOBAL_FUNCTION(p_key, p_pattern) fuction? Inside or outside of the ready function? How do I return the response from this global function? What if the result of parsing the response produces a list of values?
Where should I put that GLOBAL_FUNCTION(p_key, p_pattern) function? Inside or outside of the ready function?
You can put it anywhere in scope of all the places you want to call it. Global is one possibility but should be avoided where possible. Instead, I'd suggest namespacing your common functions in to their own object. This way you can then extract them to a separate JS file for easy re-use.
How do I return the response from this global function?
If the function is making an AJAX request you can't return anything, as the call should be asynchronous. You can work around this by providing a callback function to execute when the request completes.
With those points in mind, the code would look something like this:
// common.js
var common = (function() {
return {
global_function: function(key, callback) {
$.get('/ede/' + key + '/json', function(response) {
// perform common actions here, if needed..
callback && callback(response);
}
}
};
})();
// in your page:
$('button.icons8.icons8-edit-file').on("click", function() {
var key = $(this).data('key');
common.global_function(key, function(response) {
// Edit response.id...
});
});
$('button.icons8.icons8-delete-file').on("click", function() {
var key = $(this).data('key');
common.global_function(key, function(response) {
// Delete response.id...
});
});
It would also make sense to extract the delete and edit logic to the common library, but I'll leave that to you based on your own logic.
Finally, note the use of data() here, as creating your own non-standard attributes will make your HTML invalid. Use data-key instead.
You can put a function just in the jQuery ready state and use them in both callbacks. It's not really global, but it's in the right scope to use in both.
But GLOBAL_FUNCTION function can't return the value, because $.ajax is async. But you can pass a callback to the function, executed after finish.
And you can tell jQuery that the response is in JSON format, so it will parse it automatically for you.
$( document ).ready(function() {
function GLOBAL_FUNCTION(key, type, callback) {
$.ajax({
url: '/ede/' + key + '/json',
method: 'POST',
dataType: 'json,
success: function (response) {
// EXTRACTING THE ID FROM RESPONSE
var id = response.id;
if (type === 'edit') {
// PERFOMING THE EDIT
}
if (type === 'delte') {
// PERFOMING THE DELETE
}
// EXECUTE CALLBACK ON FINISH
callback(id, type);
}
});
};
$('button.icons8.icons8-edit-file').on("click", function(){
var key = $(this).attr('key');
GLOBAL_FUNCTION(key, 'edit', (id, type) => {
console.log(type + ' of id #' + id + ' finished');
});
})
$('button.icons8.icons8-delete-file').on("click", function(){
var key = $(this).attr('key');
GLOBAL_FUNCTION(key, 'delete', (id, type) => {
console.log(type + ' of id #' + id + ' finished');
});
})
});

Jquery/JavaScript - Strip out part of URL from window.location and use as a Variable

I have the below snippet which makes a call to my API and returns some JSON
var authorizationToken = "xxxxxxxxxxxxxxx";
function myapiRequest(endpoint, options) {
$.ajax($.extend({}, {
type: 'GET',
dataType: "json",
success: function(data) {
$('.Name').html(data.user.name);
$('.Email').html(data.user.email);
$('.Address').html(data.user.teams[0].name);
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
myapiRequest('/users/' + 'usersID' + '?include%5B%5D=contact_methods&include%5B%5D=teams'); //This is where my userID variable will be called
I would like to add something further like....
var currentLocation = window.location; // https://myapi.com/users/PLLFFR6
var usersID = PLLFFR6
To get the current windows URL and strip the user ID 'PLLFFR6' out and use that as a variable later on my URL always follows the same pattern, /users/ID is the ID part I want to use only
myapiRequest('/users/' + 'usersID' + '?include%5B%5D=contact_methods&include%5B%5D=teams');
If your URL is in the format https://myapi.com/users/PLLFFR6 then you can split the url based on / and take the last array element. Example below:
<script>
window.onload = function () { test(); }
function test() {
var url = "https://myapi.com/users/PLLFFR6".split("/");
url = url[url.length-1]
alert(url);
}
</script>
Do you just mean something like this...
var usersID = location.pathname.split('/').pop()
I'd also make use of the $.ajax data property for those query parameters, ie
myapiRequest(`/users/${usersID}`, { // or "'/users/' + usersID" if you don't like template literals
data: {
include: ['contact_methods', 'teams']
}
})

Javascript variable scope hindering me

I cant seem to get this for the life of me. I cant access the variable "json" after I calll the getJson2 function. I get my json dynamically through a php script, and that works. But then its gone. there is a sample that I use as a guide at The InfoVis examples where the json is embedded in the init function. i am trying to get it there dynamically.
<script language="javascript" type="text/javascript">
var labelType, useGradients, nativeTextSupport,animate,json;
function getJson2()
{
var cd = getParameterByName("code");
$.get("tasks.php?code="+cd, function(data){
return data;
})
};
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
(function() {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
debugger;
var Log = {
elem: false,
write: function(text){
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
debugger;
this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(){
json = getJson2();
//init data
var st = new $jit.ST({
//id of viz container element
injectInto: 'infovis',
//set duration for the animation
duration: 800,
//set animation transition type ..................
function getJson2()
{
var cd = getParameterByName("code");
$.get("tasks.php?code="+cd, function(data){
return data;
})
};
getJson2() doesn't return anything. The callback function to $.get() returns something, but nothing is listening for that return.
It sounds like you want synchronous loading instead. $.get() is just shorthand for this $.ajax() call: (See docs)
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
And $.ajax() supports more features, like setting async to false.
$.ajax({
url: "tasks.php?code="+cd,
async: false,
dataType: 'json',
success: function(data) {
// data !
}
});
Which means, getJson2 then becomes:
function getJson2()
{
var cd = getParameterByName("code");
var jsonData;
$.ajax({
url: "tasks.php?code="+cd,
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
return jsonData;
};
var myJsonData = getJson2();
Or still use $.get async style, and use callbacks instead.
function getJson2(callback)
{
var cd = getParameterByName("code");
$.get("tasks.php?code="+cd, function(data){
callback(data);
});
};
getJson2(function(data) {
// do stuff now that json data is loaded and ready
});
The $.get call is asynchronous. By the time you call return data;, the function has already long since returned. Create a variable outside of your function's scope, then in the $.get callback handler, assign data to that variable.
var json;
function getJson2(){
// ...
$.get(...., function(response){
json = response;
}
});
Alternatively, you could do a sychronous Ajax call, in which case returning your data would work (but of course would block script execution until the response was recieved). To accomplish this, see the asynch argument to jQuerys $.ajax function.
A jQuery $.get call is asynchronous and actually returns a promise, not the data itself.
An elegant way to deal with this is to use the then() method:
$.get(...).then(function(data){...});
Alternately, change your ajax settings to make the call synchronous.
$.get("tasks.php?code="+cd, function(data){
return data;
})
$.get is asynchroneous. So your value is never returned. You would have to create a callback.
The same question appears here:
Return $.get data in a function using jQuery

using the result from jQuery into C#

I have this function in jquery which has the result array and how can I get this result array to C# code. Can anyone help me regarding this.
function generateData() {
var result = $('#accordion').sortable('toArray');
}
You could do this asynchronously through a web method call from script, such that you define a web method appropriately, then call and handle the data and potential return value, as desired. For example:
Defining a web method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string HandleData(object[] data)
{
//handle data
return string.Empty;
}
Defining a reusable jQuery script method to handle web method calls:
function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
And, of course, the call itself:
ExecutePageMethod("Default.aspx", "HandleData",
["data", result], successCallback, failureCallback);
Naturally we now need to make sure our callback methods exist:
function successCallback(result) {
var parsedResult = jQuery.parseJSON(result.d);
}
function failureCallback(result) {
}
Use a hiddenfield to store the result..
<asp:HiddenField id="hfResult" runat="server" />
JQuery
$('hfResult').val(result);
C#
String result = hfResult.Value;
Note that a hiddenField only holds a string, so you might need to use some kind of seperator to seperate your array objects..

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