Setting dynamic fallback in jquery each with JSON data - javascript

I am trying to set a fallback function dynamically from an ajax jsonp call, but it doesn't seem to work - I am actually not quite sure if it is even possible - at least I believe I am doing it wrong.
I have this
var GetFacebookData = function (data) {
var dates = [{ "date_from": data.date_from, "date_to": data.date_to }]
$.each(data.datatypes, function (i, index) {
this.fbcallback[data.datatypes[i]["id"]] = function () {
LoadFacebookData(dates, data.datatypes["id"]);
}
$.ajax({
url: 'http://localhost:59380/' + data.datatypes[i]["urlfile"] + '.php?jsonp=fbcallback' + data.datatypes[i]["id"],
method: 'GET',
dataType: 'jsonp',
jsonp: 'fbcallback',
data: { "lpage": _bankArea, "hashed_token": CryptoJS.MD5("454545").toString(), "date_from": data.date_from, "date_to": data.date_to },
});
});
}
And I am calling the function with this
GetFacebookData({ date_from: _datefrom, date_to: _dateto, datatypes: [{ id: "moedsparnord", urlfile: "index" }, { id: "studiepakken", urlfile: "fb_studiedata" }] });
I am just getting
Uncaught TypeError: Cannot set property 'moedsparnord' of undefined
The whole concept is that I will need to run GetFacebookData multiple times with difference data to be executed.
/*** LOAD FETCHED DATA AS JSON ***/
var LoadFacebookData = function (dates, id) {
_dateLoader.hide();
$('.date-box form').slideUp(750, 'easeOutBack');
var pages = [];
this.loadcallback = function (data) {
var len = data["campaignData"].length;
$.each(data["campaignData"], function (index, value) {
$('#' + id + '-' + value["campaign"]["campaignId"]).find(".facebook").text(AddDecimal(value["campaign"]["campaignReach"]));
$('#' + id + '-' + value["campaign"]["campaignId"]).find(".facebook").attr("data-spend", value["campaign"]["campaignSpend"]);
if (index != len) {
pages[index] = [value["campaign"]["campaignId"], value["campaign"]["campaignSpend"]];
}
});
var string = $('#' + id + ' .total-facebook').text().replace(/,/g, '');
$("#" + id + " .total-facebook").countTo({
from: parseFloat(string),
to: data["totalReach"],
decimals: 0,
formatter: function (value, options) {
return value.toFixed(options.decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ".");
},
});
MSNLeadData([{ date_from: dates[0]["date_from"], date_to: dates[0]["date_to"] }, pages]);
StudieLeadData([{ date_from: dates[0]["date_from"], date_to: dates[0]["date_to"], pages }]);
}
$.ajax({
url: 'http://localhost:59380/loaddata.php?jsonp=loadcallback',
method: 'GET',
dataType: 'jsonp',
jsonp: 'loadcallback',
data: { "lpage": _bankArea, "hashed_token": CryptoJS.MD5("454545").toString(), "datatype": id },
});
}

Functions fbcallback['...'] should be global.
Try to use this code inside the loop.
...
var callbackName = 'fbcallback-' + data.datatypes[i]["id"];
window[callbackName] = function () {
LoadFacebookData(dates, data.datatypes["id"]);
}
...
$.ajax({
url: 'http://localhost:59380/' + data.datatypes[i]["urlfile"] + '.php',
method: 'GET',
dataType: 'jsonp',
jsonp: callbackName,
data: { "lpage": _bankArea, "hashed_token": CryptoJS.MD5("454545").toString(), "date_from": data.date_from, "date_to": data.date_to },
});
And inside of LoadFacebookData callback method should also be global (window.loadcallback).

Related

Select2 doesn't show the initSelection values

the jquery Select2(Version: 3.5.4) plugin doesn't show my initial value which I loaded on the initSelection function of the plugin. Here is my code:
$("#materialFieldTags").select2({
tags: true,
initSelection : function (element, callback) {
console.log(element);
console.log(callback);
var countryId = "3"; //Your values that somehow you parsed them
var countryText = "mater3";
var data = [];//Array
var tempJSONMat = {
materials: []
};
$.ajax({
url: "php/FormProcessing.php",
type: "post",
data: "main=" + "materialFault" + "&faultid="+ main.faultId,
dataType: 'json',
success: function(data){
data.forEach(function(column) {
//console.log(column);
tempJSONMat.materials.push({
"id" : column.material_id,
"text" : column.name
});
});
}
});
callback(tempJSONMat.materials[0]);
},
ajax: {
type: "POST",
url: 'php/FormFilling.php',
dataType: 'json',
data: function (params) {
return "main=" + "allMaterials" + "&searchterm=" + params;
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
};
})
};
},
cache: true
}
});
Can you take I look at my code? Because I can't see it!! I also have try the:
$("#materialFieldTags").select2("data",mydata);
After the initialization of the plugin, but I am getting the same result.
Finally, I found my mistake! It was define two element by the same id, by mistake! The data appeared on first one and I was looking the second one.

Second Jquery json getting fired before first Jquery being complete

I have two javascript function which populate some data using jquery json. Both working fine but problem is that second function getting called before first one execute. My code is :
$(document).ready(function () {
loadSubject();
getTopic();
});
function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
alert('22222');
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
success: function (data) {
var subjectDivs = "";
var divs = "";
var i = 1;
$.each(data, function (index, value) {
divs = "";
// Some code here
i = i + 1;
});
subjectDivs = subjectDivs + divs;
alert('11111');
$('#cCount').val(i);
document.getElementById('accordion').innerHTML = subjectDivs;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
function getTopic() {
var c = $('#cCount').val();
alert(c);
for (var i = 1; i <= c; i++) {
var subId = $('#hdn_' + i).val();
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Topic', UserRecId: 0, ParentId: subId },
dataType: 'json',
success: function (data) {
var topicDivs = "";
var divs = "";
tDivs = '';
$.each(data, function (index, value) {
divs = '';
divs = '<div class="row">';
divs = divs + '<div class="subject">' + value.Name + '</div>';
divs = divs + "</div>";
topicDivs = topicDivs + divs;
});
$('#sDiv_' + i).html(topicDivs);
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
}
This is not the way how ajax get executes. If you put two jquery ajax requests one by one then they will execute in sequence by it is not necessary that second request will be executed after first request completes or response of first request is received.
If you want this to happen then there are two ways
1. Use async:'false'
This makes a request to wait until response is recieved before executing next statement in javascript.
What does "async: false" do in jQuery.ajax()?
2. Use callbacks
Write the second function which you want to execute in success or complete callback of your first ajax request.
jQuery ajax success callback function definition
Try adding return statement before $.ajax({}) within both loadSubject and getTopic , to return jQuery promise object , which can be handled at deferred.then
function loadSubject() {
return $.ajax()
}
function getTopic() {
return $.ajax()
}
loadSubject().then(getTopic);
function a() {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.resolve(1)
}, 2000)
}).promise().then(function(data) {
console.log(data)
})
}
function b() {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.resolve(2)
}, 2000)
}).promise().then(function(data) {
console.log(data)
})
}
a().then(b)
You have to add async:false in your first ajax request, it stop next execution till first ajax request will complete its execution.
So your first function like this
function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
jQuery.support.cors = true;
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
async:false,
success: function (data) {
var subjectDivs = "";
var divs = "";
var i = 1;
$.each(data, function (index, value) {
divs = "";
// Some code here
i = i + 1;
});
subjectDivs = subjectDivs + divs;
alert('11111');
$('#cCount').val(i);
document.getElementById('accordion').innerHTML = subjectDivs;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
Call second function from first ajax success function
$(document).ready(function () {
loadSubject();
});
function loadSubject() {
// code here
$.ajax({
url: 'http://220.45.89.129/api/LibraryApi',
type: 'Get',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
dataType: 'json',
success: function (data) {
//code here
getTopic(); // Second function calling
},
error: function (e) {
alert(JSON.stringify(e));
}
});
}
Now when first function is executed successfully then second function will be called.

What is the simplest way to get a Wiktionary definition working in my Chrome extension?

This person has a very simple translation script working on the Wiktionary API.
How would I go about modifying this to return some dictionary definitions for English words?
http://jsfiddle.net/karlb/PxfrJ/11/
function show_result(data) {
$("#result ul").text('');
$.each(data.query.pages, function(page_id, page) {
if (page.iwlinks === undefined) {
$("#result ul").append('no results');
return false; // break
}
$.each(page.iwlinks, function(i, el) {
var trans = el['*'];
trans = trans.replace('Special:Search/', '').replace('_', ' ');
$("#result ul").append('<li>' + trans + '</li>');
});
});
$("#result").fadeIn('fast');
}
function translate() {
$("#result").fadeOut('fast');
$.ajax({
url: 'http://' + $('#from').val() + '.wiktionary.org/w/api.php',
data: {
action: 'query',
prop: 'iwlinks',
format: 'json',
iwlimit: 30,
iwprefix: $('#to').val(),
titles: $('#word').val()
},
dataType: 'jsonp',
success: show_result
});
return false;
}
$('form').submit(translate);
$('#word').focus();

Handling json data using jQuery sent by using Newtonsoft.Json

I have tried searching all possible matches of my problem and also have tried a couple of solutions but unfortunately none worked
My backend code:
Person p;
foreach(DataRow dr in dt.Rows)
{
p = new Person();
p.id = Convert.ToInt16(dr["Id"]);
p.name = dr["Name"].ToString();
p.phone = Convert.ToInt64(dr["Phone"]);
pList.Add(p);
}
string ans = JsonConvert.SerializeObject(pList, Formatting.Indented);
jQuery.ajax
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Alert output
[
{
"id": 1,
"name": "Bhavik",
"phone": 9601109585
},
{
"id": 2,
"name": "Xyz",
"phone": 1234567890
},
{
"id": 3,
"name": "Abc",
"phone": 9876543210
}
]
console.log(list.Person.length); returns undefined and hence does not enters the for loop.. So to work out with it.. and why is it necessary to specify contentType while dataType already exist.. Also can I use $.getJSON instead of $.ajax.
You should change your code to be var list = {"Person": data.d}; to reflect what you're alerting.
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data.d };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Also this should be a GET request not a post, then you would be able to use $.getJSON.

Uncaught TypeError: Object has no method autocomplete and its blocking to populate dialogue box to delete

I'm sorry similar post is already there in the community, But i'm finding it strange. Its working fine but it affected my other views and not allowing other view pages to populate any dialogue boxes..
I tried to fix it by wrapping it in function() like this
$('#_auto').autocomplete(function(){
But, with this i'm not getting jason values in the _auto textfield and getting unexpected token error with following line.
can anyone help me to solve this please.
source: function(request,response){
this is my code:
$(function () {
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
var sval = $('#_auto').val();
//alert(sval);
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': sval,
},
dataType: 'json',
success: function (data) {
console.log(data);
var dta = [];
orgdetails = [];
//response(data.d);
for (var i in data) {
dta.push(data[i].name);
orgdetails[data[i].name] = data[i].id;
}
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
});
Many Thanks
I think the for loop should be
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
Fiddle.
Another observation, You can get the current searched term using request.term rather than $('#_auto').val()
Complete code:
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': request.term,
},
dataType: 'json',
success: function (data) {
console.log(data);
orgdetails = {};
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});

Categories