use ajax success:function(data) on document ready jquery function - javascript

I am loading responsive calendar in document ready :
eventList=disp();
$(".responsive-calendar").responsiveCalendar({
events:eventList //json object data
});
function disp(){
//getArr();
//alert(data1); //not working
stb = '{';
edb = '}';
dt = ["2015-09-13","2015-10-22","2015-10-02"]; // dynamically to be created from ajax data
ct = [2,5,6]; // dynamically to be created from ajax data
ev = dt.length;
var ddt = stb;
for(var i=0; i<ev;i++){
ddt += '"' + dt[i] + '":{"number":'+ct[i]+'},';
}
mString = ddt.substring(0,ddt.length-1)
ddt = mString+edb;
return JSON.parse(ddt);
}
function getArr() {
$.ajax({
url:"../JLRFile.php",
success:function(data) {
data1 = data;
}
});
}
Here in disp() I need dt and ct to load from ajax data function, can any one provide proper solution, I called ajax function in disp() but its not working.
Please provide proper solution

eventList = getArr();
$(".responsive-calendar").responsiveCalendar({
events: eventList //json object data
});
function disp(data1) {
alert(data1); //getting now
stb = '{';
edb = '}';
dt = ["2015-09-13", "2015-10-22", "2015-10-02"]; // dynamically to be created from ajax data
ct = [2, 5, 6]; // dynamically to be created from ajax data
ev = dt.length;
var ddt = stb;
for (var i = 0; i < ev; i++) {
ddt += '"' + dt[i] + '":{"number":' + ct[i] + '},';
}
mString = ddt.substring(0, ddt.length - 1)
ddt = mString + edb;
return JSON.parse(ddt);
}
function getArr() {
$.ajax({
url: "../JLRFile.php",
success: function (data) {
data1 = data;
disp(data1);
}
});
}

Related

Multiple onblur elements gives error

I am try to call a function onblur of my three elements in my table
but i am getting this error in my console
"((m.event.special[e.origType] || (intermediate value)).handle || e.handler).apply is not a function".
So onblur these elements i want to call my function.Please do have a look at my code once.
Apologies for my bad handwriting here .I am new to javascript
jq.ajax({
url: '/soap/ajax/36.0/connection.js',
dataType: 'script',
success: function() {
jq(document).ready(function() {
// call tookit dependent logic here
jq('#gbMainTable').on('blur', 'tr.dr td[name="v4"] select','tr.dr td[name="v6"] select','tr.dr td[name="v7"] input', function()
{
var thisInput = this;
console.log('thisInput.value',thisInput.value);
var thisInput1 = jq(this);
var thisRow = thisInput1.parents('tr.dr:first');
console.log('thisRow',thisRow);
var agentInput1 = thisRow.find('td:eq(7)');
console.log('agentInput1',agentInput1);
var finds1 = agentInput1.find('select');
console.log('finds1',finds1);
var agentInput2 = thisRow.find('td:eq(8)');
console.log('agentInput2',agentInput2);
var finds2= agentInput2.find('input');
if(agentInput1.text()!=='' & thisInput.value=='Programmable Cntrls/Welders/AC Drives/Soft Starts'){
exampleFunction('Programmable',agentInput1.text(),agentInput2.text());
console.log('YES');
}
else if(agentInput1.text()!=='' & thisInput.value=='Electro Mechanical'){
exampleFunction('Electro-Mechanical',agentInput1.text(),agentInput2.text());
}
});
});
},
async: false
});
function exampleFunction(Warranty,Years,charge) {
var state = { // state that you need when the callback is called
output : null,
startTime : new Date().getTime()};
var callback = {
//call layoutResult if the request is successful
onSuccess: doThis,
//call queryFailed if the api request fails
onFailure: queryFailed,
source: state};
sforce.connection.query(
"SELECT InOut__c,PlantPct__c,T37Pct__c,TotalPct__c,Type__c,Warranty_Code__c,Years__c FROM WarrantySpecialLine__c where InOut__c = '" +charge+"' and Years__c = '"+Years+"' and Type__c = '" +Warranty +"'",
callback);
}
function queryFailed(error, source) {
console.log('error: '+error);
}
/**
* This method will be called when the toolkit receives a successful
* response from the server.
* #queryResult - result that server returned
* #source - state passed into the query method call.
*/
function doThis(queryResult, source) {
if (queryResult.size > 0) {
var output = "";
// get the records array
var records = queryResult.getArray('records');
// loop through the records
for (var i = 0; i < records.length; i++) {
var warrantySpecial = records[i];
console.log(warrantySpecial.PlantPct__c + " " + warrantySpecial.TotalPct__c + " " +warrantySpecial.T37Pct__c );
}
}
}

ajax call returning null

I have this small script (fiddle) in charged for reading some blog XML. The problem is that it simply stopped working a few days ago. It seems the Ajax function is always returning null, even though there is data in the specified URL.
<script>
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
var buildRSS = function (container_id){
$.ajax({
type: "GET",
url: "http://bloginstructions.blogspot.dk/rss.xml",
dataType: "xml",
success: function(result){
var values = getEntries(result)
console.log(result)
for (var i = 0; i < 10; i++) {
var entry = values[i],
info = entry.__text.split("\n"),
title = info[0],
link = info[1],
date = entry.pubdate.match(/(.*) \d/)[1],
snippet = entry.description.replace(/<\/?[^>]+(>|$)/g, "").substring(0,350)+'...';
var html = '<div><h4>' + title + '</h4><p>' + date + '</p><p>' + snippet + '</p></div>'
$('#' + container_id).append(html)
}
}
})
}
function getEntries(rawXML){
var x2js = new X2JS();
console.log(rawXML);
var xml = rawXML.responseText;
match = xml.match(/<item>(.*)<\/item>/);
xml = match[0] || '';
var json = x2js.xml_str2json(xml);
json = json.rss.channel.item;
return json
}
</script>
<div id="rssfeed">
</div>
<div id="rss">
</div>
<script>
$(document).ready(function() {
buildRSS('rssfeed')
});
</script>

How to get json array from json file?

im creating Image Hotspot using javascript, i need to get a data (x,y and Info) from json file, currently im getting data from Javascript Array. How can i get it from json file?
Code Pasted here;
var points;
var l_nOldX;
var l_nOldY;
function createHotspots(){
var points = new Array(
/*Tamilnadu*/
[38.7, 85.6, "0168"],
[36.1, 85.3, "1843"],
[38.5, 88.3, "39647"],
[34.8, 29.2, "12320"]
);
var divHotspot = document.getElementById("loadImages");
for(pi = 0; pi < points.length; pi++){
var hs = document.createElement("div");
hs.className = "hotspot";
hs.style.position = "absolute";
hs.style.left = "calc(" + points[pi][0] + "% - 8px)";
hs.style.top = "calc(" + points[pi][1] + "% - 0px)";
hs.style.width = "15px";
hs.style.height = "15px";
var html;
if (points[pi][0] < 31) {
html = "<table cellpadding='0' cellspacing='0' class='tbltooltipright' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxr'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
// alert('a');
hs.innerHTML = html;
$(hs).bind("mouseenter", function () {
$(".tbltooltipnormal").hide();
$(".tbltooltipleft").hide();
$(".tbltooltipright").hide();
$(this).find(".tbltooltipright").show();
});
}
else {
html = "<table cellpadding='0' cellspacing='0' class='tbltooltipnormal' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxn'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
hs.innerHTML = html;
$(hs).bind("mouseenter", function () {
$(".tbltooltipnormal").hide();
$(".tbltooltipleft").hide();
$(".tbltooltipright").hide();
$(this).find(".tbltooltipnormal").show();
});
}
$('.divclose').on('click touchstart', function () {
//debugger;
$('.tbltooltipnormal').hide();
$('.tbltooltipleft').hide();
$('.tbltooltipright').hide();
return false;
});
divHotspot.appendChild(hs);
}
}
In above code i've get data from "Points" array instead of i need to get this array data from one json file ?
Please help me to get this fixed.
thanks in Advance.
You can use ajax to get the data from the json file and just wrap the existing code in a function which takes an argument and just assign that argument to the desired var:
var points;
var l_nOldX;
var l_nOldY;
function createHotspots(points){ // <---pass the array
var points = points; // assign it here
var divHotspot = document.getElementById("loadImages");
...
}
$.ajax({
url:'points.json', //<----call the json file
type:'GET',
dataType:'json',
success:createHotspots // reference to the data
});
var yourJsonDataFromFile=undefined;
var getJsonData=function () {
console.log("fetching data from JSON file");
var url = "path_to_your_json _file";
var ajaxHttp = new XMLHttpRequest();
ajaxHttp.overrideMimeType("application/json");
ajaxHttp.open("GET",url,true);
ajaxHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
ajaxHttp.send(null);
ajaxHttp.onreadystatechange = function () {
if(ajaxHttp.readyState == 4 && ajaxHttp.status == "200")
{
yourJsonDataFromFile = JSON.parse(ajaxHttp.response);
}
};
}
modify this code add file path in path_to_your_json _fileand call this function getJsonData() after that your data will be in yourJsonDataFromFile in json format , hope this will resolve your issue
Please try this. Should solve your problem
$.getJSON('<path_to_your_json_file>/file.json', function(data) {
var points = data;
});

Uncaught TypeError: Cannot read property 'HotelInfo' of undefined

//an ajax call to the api
jQuery(document).ready(function() {
jQuery.ajax({
url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&theme=%22food%22",
dataType: 'JSON', type: 'GET',
success: function (data)
var viewModel;
if(data) {
viewModel = new dealsPageModel(data);
var idList = "";
for (var i = 0; i< data.packageDeal.length; i++)
{
if (i == data.packageDeal.length -1)
{ idList += data.packageDeal[i].hotelId;
}
else
{idList += data.packageDeal[i].hotelId + ',';
}
}
var searchUrl = "http://terminal2.expedia.com/x/hotels?hotelids=" + idList + "&apikey=6weV4ksGIJ5eQhd58o2XTDwVo35lZf2S";
//another call to another api to return hotel specific info
jQuery.get(searchUrl, function ( )
{
for(var i=0; i<viewModel.dealList.length; i++)
{
var hotelId = viewModel.dealList[i].hotelId;
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = HotelInfoList.HotelInfo[i].Name;
}
// Get the hotelid from the current deal
// Loop through the hotelinfolist.hotelInfo and find out the url for the hotel idList
//Loop through the hotelinfolist.hotelInfo and find out the name for the hotel
viewModel.dealList.push(new deal(data.packageDeal[i], url, name));
}
ko.applyBindings(viewModel);
});
}
}
})
});
You loop through data.HotelInfoList.HotelInfo but operate on HotelInfoList.HotelInfo[i].ThumbnailUrl. The data. at the beginning is missing.
Also, place data in the callback function in jQuery.get:
jQuery.get(searchUrl, function(data){
// …
your data is in data.HotelInfoList not in HotelInfoList
your loop should be like this
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = data.HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = data.HotelInfoList.HotelInfo[i].Name;
}

Transfer data from php as json, then store it in global object

I have the following code:
PHP code:
$data = array();
$data[0]['name'] = "Kj";
$data[0]['age'] = 30;
$data[0]['country'] = "Italy";
$data[1]['name'] = "Dn";
$data[1]['age'] = 18;
$data[1]['country'] = "USA";
$data[2]['name'] = "Jo";
$data[2]['age'] = 22;
$data[2]['country'] = "Switzerland";
$data[3]['name'] = "Ro";
$data[3]['age'] = 34;
$data[3]['country'] = "UAE";
$data[4]['name'] = "Lc";
$data[4]['age'] = 13;
$data[4]['country'] = "UK";
echo json_encode($data);
Javascript code:
var jsonData = {};
$(document).ready(function () {
$.get('page.php', function (data) {
jsonData = jQuery.parseJSON(data);
});
});
for (var i = 0; i < jsonData.length; i++) {
$('ul').append("<li>" + jsonData[i].name + "</li>");
}
The problem is when put the for loop inside the $.get callback works fine like as the following.
$.get('page.php', function (data) {
jsonData = jQuery.parseJSON(data);
for (var i = 0; i < jsonData.length; i++) {
$('ul').append("<li>" + jsonData[i].name + "</li>");
}
});
But when put the for loop outside the $.get callback does not print out anything, but the data has been received successfully, but without print it.
Now, how can store the data that has been received in global variable to print it in anywhere ?
You should change your approach when you work with asynchronous operations (AJAX, timeouts). Something like this:
function GetData(callback) {
$.get('page.php', function (data) {
callback(jQuery.parseJSON(data));
});
}
GetData(function (data) {
for (var i = 0; i < data.length; i++) {
$('ul').append("<li>" + data[i].name + "</li>");
}
});
Your code already stores data in a global variable correctly.
Type jsonData into F12-javascript console and you will see it.
The question is rather about the control flow, what is the other event that will trigger usage of jsonData?

Categories