I'm writing a user interface in javascript, it will take data from the HTML and pass it through an API using javascript. I am trying to take the data and pass it to a function without writing a bunch of if statements. However some actions have the actions are the same names in other controllers. So I have a nested namespace, now I can't get to the nested function. Hopefully someone can help.
Everything before this works fine.
var apiHandler = {
user: {
login: function(){
console.log("test");
}
}
};
function callAPI(apiObject){
//console.log(apiObject);
var apiData = JSON.stringify(apiObject);
$.ajax({
type: "POST",
url: 'https://dev.tragicstudios.com/clients/trego/api/index.php',
data: {'enc_request':apiData},
dataType: 'json',
success: function(data){
var apiFunction = apiObject.controller+"."+apiObject.action;
console.log(apiFunction);
apiHandler["user.login"]();
return data;
}
});
}
Just use the controller and action part as separate keys, instead of combining them:
apiHandler[apiObject.controller][apiObject.action]();
For this specific example, instead of:
apiHandler["user.login"]();
Try
apiHandler["user"]["login"]();
Related
I am using the Map() functionality in ES6 to create a list of keypair values, making an ID number to a boolean value. I want to pass this Javascript object to an MVC 4 Controller.
Here's my Javascript:
var bankHolidays = new Map();
$('.bank-holiday-switch').each(function () {
var id = $(this).attr('id');
var isChecked = $(this).is(':checked');
bankHolidays.set(id, isChecked);
});
$.ajax({
url: '/AdminPanel/Settings/SaveBankHolidays',
type: 'POST',
data: { bankHolidays: bankHolidays },
success: function (result) {
alert("Success");
}
});
I can console.log() the map object and see that it's being created as intended. However, when I pass it to this MVC Controller:
[HttpPost]
public JsonResult SaveBankHolidays(Dictionary<int, bool> bankHolidays)
{
// DO stuff
}
..no error is thrown, but it just says the bankHolidays dictionary has 0 values in it. I can call other Actions in that Controller without issue. I have tried many different combinations of Dictionary<string, bool> to no avail.
Can somebody tell me what I am doing wrong?
In a http negotiation, xhr in this case, we must send strings, so you need some string representation of Map(), the best option, in my opinion, is to use a JSON stringify in some way, because the parse of JSON have a broad support among server side code:
var bankHolidays = new Map();
bankHolidays.set(1, 2);
bankHolidays.set(3, 4);
var result = JSON.stringify([...bankHolidays]);
console.log(result)
In your code something like :
$.ajax({
url: '/AdminPanel/Settings/SaveBankHolidays',
type: 'POST',
data: JSON.stringify([...bankHolidays]),
success: function (result) {
alert("Success");
}
});
In backend you have to parse the response, see this.
I currently have an AJAX call out to a PHP file that works, that is the following:
//Load map from database
function getMap(){
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
};
getMap().done(function(r) {
if (r) {
loadedMap(JSON.parse(r.mapArray), JSON.parse(r.mapProperties)); //call loadedMap(r) if loading a map from DB
} else {
console.log("No data");
}
}).fail(function(x) {
console.log("error");
});
That works within a single javascript file that successfully passes r.mapArray and r.mapProperties to my main loadedMap function.
I'm trying to learn about the IIFE Javascript Module model, and split my work up into separate files.
So, I currently have main.js:
(function() {
// let's get our map
var gameMap = mapGen.getMap().done();
console.log(gameMap);
})();
and mapGen.js:
var mapGen = function() {
return {
getMap: function() {
return $.ajax({
url: "getMap.php",
type: "POST",
dataType: 'JSON',
});
}
};
}()
If I console.log(gameMap), I see the responseText JSON object with my data. I just can't seem to access it. console.log(gameMap.responseText) is undefined. as is gameMap.responseJSON (though I see both of them in the console).
Looking the code over it looks as the the separation of the files was not the issue and that looks to be implemented correctly. The issue is with how you are handling the AJAX request. The function mapGen.getMap() actually returns a jqXHR Object as opposed to the response that you are trying to access.
Just as you had in your previous file, you will need handle the response of your request.
(function() {
// let's get our map request
var gameMap = mapGen.getMap();
gameMap.done(function(r){ ... }).
fail(function(x){ ... });
})();
You will be able to access the response data you are looking for within the done() function.
I solved a synchronous problem with ajax that way to use deferred function.
I get as an response now big object with statusResponse etc etc inside.
My JSONP Objects are also successfully stored in responseJSON Object. How Can I extract it or save it in another variable ?
var web = new webService();
web.init(app.info);
and here the class
function webService() {
this.init = function(app) {
var d = this.connect(app).done(function(){});
console.log(d);
}
this.connect = function(app) {
console.log(app);
return $.ajax({
url: 'working url',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000
});
}
}
.done() is going to be called when the data has returned (but through a parameter). So, make sure you add a parameter to your callback function then inspect it for whatever you want out of it.
this.connect(app).done(function(mydata){
// mydata = the response object
// grab whatever information you want from it here.
});
I have this working code:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']'),
complete: function (mydata) {
//do something with it
}
});
That successfully posts back any checked checkboxes and all textboxes. But now I want to add some arbitrary data as well to this. But not sure how to format it. Basically i want to simply add my own name=value pair "test=1" so that on the callback I see it like the others. But no matter what I try, I can't see to get the syntax correct in the format it expects. not sure if I should be adding it inside the jQuery() wrap or outside.. I've tried serializing, encodeURIComponent, basic string "&test=1"
Any ideas?
Your best bet is to build the parameters outside of the AJAX call, like so:
var params = jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']');
params.test = 1;
params.test2 = 2;
Then in your AJAX call, simply use:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: params,
complete: function (mydata) {
//do something with it
}
});
EDIT: Typically when using jQuery to collect input, I tend to use the .each function, like so:
var params = new Object();
$.each('input[name^=option]', function() {
if ((this.type === 'checkbox' && $(this).is(':checked')) || this.type === 'text' && this.value !== '') {
params[this.name] = this.value;
}
});
Then if you wish to add parameters, you'd do so either after this, or right after creating your new object.
I forgot I asked this previously. It was answered correctly so I'm sharing the link:
How can I pass form data AND my own variables via jQuery Ajax call?
I am attempting to create a glossary tooltip for a website that finds keywords from a json file that is being created by sitecore. I need to get the "Text:" parts from the json file and make then a variable in my jquery so they are the keywords that are found and wrapped with the appropriate tags. I had it working to the point where i could get console to log that there were 2 entries in my json file but that's it.
Here is my sample json code:
[{"Id":"ef339eaa-78e1-4f9e-911e- 096a1920f0b6","Name":"Glossary","DisplayName":"Glossary","TemplateId":"b27d2588-3d02-4f5f-8064-2ee3b7b8eb39","TemplateName":"Glossary","Url":"/Global-Content/Glossary/Glossary","Version":1,"Created":"\/Date(1343987220000)\/","CreatedBy":"sitecore\\rgoodman","Revision":"ae8b3ae0-d0ca-4c4a-9f27-a542a31ab233","Updated":"\/Date(1348137810133)\/","UpdatedBy":"sitecore\\admin","Text":"Glossary","Content":"A bit of test content for the glossary"},{"Id":"3fa51ad4-cfb6-4ff1-a9b5-5276914b2c23","Name":"Abraham","DisplayName":"Abraham","TemplateId":"b27d2588-3d02-4f5f-8064-2ee3b7b8eb39","TemplateName":"Glossary","Url":"/Global-Content/Glossary/A/Abraham","Version":1,"Created":"\/Date(1348148640000)\/","CreatedBy":"sitecore\\admin","Revision":"231284ec-9fb9-4502-ad79-a5806479ecba","Updated":"\/Date(1348148779656)\/","UpdatedBy":"sitecore\\admin","Text":"Abraham","Content":"This is a lincoln person"}]
But I suppose this is not of any use as it is just the "Text:" part i am looking to return.
Here is my jquery:
function getData(url) {
var data;
$.ajax({
async: false,
url: '/_assets/js/glossary.json',
dataType: 'json',
success: function(data.Text){
data.Text = response;
}
return(response);
});
}
function HighlightKeywords(keywords)
{
var el = $("body");
$(keywords).each(function()
{
var pattern = new RegExp("(" +this+ ")", ["gi"]);
var rs = "<mark href='#' class='tooltip'>$1</mark>";
el.html(el.html().replace(pattern, rs));
});
}
HighlightKeywords(data.Text);
Essentially i need to return the "Text:" bit of json where data is on the HighlightKerywords function. Where am i going wrong?
Any help would be much appreciated. Thanks
Your function is not syntactically formatted properly. Your return must go inside of the success function in the synchronous example, and not randomly placed in the ajax object..
function getData() {
$.ajax({
async: false,
url: '/_assets/js/glossary.json',
dataType: 'json',
success: function(data){
//HighlightKeywords(data.Text);
//or
return(data.Text);
}
});
}
Ajax is Asynchronous communication, you can't insert its response into a global variable and expect to be able to work with it.
You need to do all the work on the data.text in the success function.
success: function(response){
HighlightKeywords(response.Text);
}