AJAX - setting parent object's member variables from callback function - javascript

I'm developing a Javascript libraray which I want to use as follows.
var obj = new Lib().actionOne();
This call should populate "transcript" and "session" member variables in obj.
Then I want to call:
obj.actionTwo();
which will use populated "transcript" and "session" objects in the previous call.
Find below my library.
var xmlhttp = null;
function Lib() {
this.transcript = null;
this.session = null;
return this;
}
Lib.prototype = {
_initRequest : function() {
// create xmlhttp request here
},
_consumeService : function(callback) {
this._initRequest();
xmlhttp.open("GET", "THE URL", true);
var self = this;
xmlhttp.onreadystatechange = function(self) {
if(xmlhttp.readyState==4 && xmlhttp.status==200 ){
callback.call(self);
}
};
xmlhttp.send();
},
actionOne: function() {
var connUrl = "SOME URL";
this._consumeService(this._actionOneCallback);
return this;
},
_actionOneCallback : function() {
var jsonObj = JSON.parse(xmlhttp.responseText);
this.session = jsonObj.session
this.transcript = jsonObj.transcript;
this.isActionOneDone = true;
xmlhttp = null;
},
actionTwo : function() {
// use this.session and this.transcript
}
};
The issue is that actionOneCallback() function doest not populate 'obj' members though I pass 'self' reference to it. Therefore when I call 'obj.actionTwo();', obj's member variables are undefined. What is the workaround for this?

Related

How to access a JSON array directly from url

I am new to javascript and I have a Json Array in a url like below;
[{"year":2015,"month":4,"day":1,"num":0,"time":"2015-04-01","hour":0,"zone":3,"state1":2137,"state2":249,"state3":1810,"state4":30,"state5":0},....]
I want to access the state1 value and assign that value to the variable which I have.How can I do that?(Is parsing necessary or are there any methods there that we can directly access the JSON object in the URL).I am sorry if I asked anything wrong.
You can use jQuery getJSON() function :
$.getJSON(' localhost:8080/dataurl', function(data) {
//data is the JSON string
var jsonObj = JSON.parse(data);
});
Now, Below are the methods to parse the jsonObj to get the state1.
Using array map() method :
var jsonObj = [
{
"year":2015,
"month":4,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2137,
"state2":249,
"state3":1810,
"state4":30,
"state5":0
},
{
"year":2016,
"month":12,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2474,
"state2":250,
"state3":1811,
"state4":31,
"state5":0
}
];
var state1arr = jsonObj.map(function(item) {
return item.state1;
});
console.log(state1arr);
using for...in loop :
var jsonObj = [
{
"year":2015,
"month":4,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2137,
"state2":249,
"state3":1810,
"state4":30,
"state5":0
},
{
"year":2016,
"month":12,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2474,
"state2":250,
"state3":1811,
"state4":31,
"state5":0
}
];
var state1arr = [];
for (var i in jsonObj) {
state1arr.push(jsonObj[i].state1);
}
console.log(state1arr);
The data you have is array of objects and you need to loop to access each object and access the key using dot notation
Like this,
var app=[{"year":2015,"month":4,"day":1,"num":0,"time":"2015-04-01","hour":0,"zone":3,"state1":2137,"state2":249,"state3":1810,"state4":30,"state5":0}];
for(var i of app)
{
console.log(i.state1);
}
Just use the following JS Code:
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
You can now use the function to get the JSON contents from the url:
getJSON("<URL>").then(function(data) { // Replace <URL> With your URL
var jsondata = data.result; //store result in variable
// Your code here....///
/// Now you can access the json's data using jsondata variable: //
// jsondata[0].year will have the value of year key, jsondata[0].month will have month key and so on.... //
}, function(status) { //error detection....
alert('Something went wrong.');
});

used instant variable inside the object define function

i need to used instant variable inside the object define function like that .
i need to use Result variable outside the function
function Request(params,type,url){
var loginReq = Titanium.Network.createHTTPClient();
loginReq.open(type,url);
loginReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
loginReq.setRequestHeader("enctype", "multipart/form-data");
loginReq.setRequestHeader("Content-Type", "image/png;charset=utf-8");
loginReq.send(params);
loginReq.onload = function()
{
var json = this.responseText;
var Result = JSON.parse(json);
};
return Result;
};
exports.Request = Request;
i need to return Result Or use it outside the scope.
You need to use either a callback, or a promise library
Using a callback
function Request(params,type,url,callback){
//...
loginReq.onload = function() {
var json = this.responseText;
var Result = JSON.parse(json);
callback(Result);
};
};
//Somewhere else
Request(/**/,/**/,/**/,function(result){
//use result
});
Using a promise library like Q
var Q = require("q");
function Request(params,type,url,callback){
var deferred = Q.defer();
//...
loginReq.onload = function() {
var json = this.responseText;
var Result = JSON.parse(json);
deferred.resolve(Result);
};
return deferred.promise;
};
//Somewhere else
Request(/**/,/**/,/**/).then(function(result){
//use result
});

Accessing Data from JavaScript Object's Array Member Variable

I'm writing a jQuery plugin for work which pulls in RSS feed data using Google's Feed API. Using this API, I'm saving all of the relevant RSS feed data into an object, then manipulating it through methods. I have a function which is supposed to render the RSS feed onto the webpage. Unfortunately, when I try to display the individual RSS feed entries, I get an error. Here's my relevant code:
var RSSFeed = function(feedTitle, feedUrl, options) {
/*
* An object to encapsulate a Google Feed API request.
*/
// Variables
this.description = "";
this.entries = [];
this.feedUrl = feedUrl;
this.link = "";
this.title = feedTitle;
this.options = $.extend({
ssl : true,
limit : 4,
key : null,
feedTemplate : '<article class="rss-feed"><h2>{title}</h1><ul>{entries}</ul></article>',
entryTemplate : '<li><h3>{title}</h3><p>by: {author} # {publishedDate}</p><p>{contentSnippet}</p></li>',
outputMode : "json"
}, options || {});
this.sendFeedRequest = function() {
/*
* Makes the AJAX call to the provided requestUrl
*/
var self = this;
$.getJSON(this.encodeRequest(), function(data) {
// Save the data in a temporary object
var responseDataFeed = data.responseData.feed;
// Now load the data into the RSSFeed object
self.description = responseDataFeed.description;
self.link = responseDataFeed.link;
self.entries = responseDataFeed.entries;
});
};
this.display = function(jQuerySelector) {
/*
* Displays the RSSFeed onto the webpage
* Each RSSEntry will be displayed wrapped in the RSSFeed's template HTML
* The template markup can be specified in the options
*/
var self = this;
console.log(self);
console.log(self.entries);
};
};
$.rssObj = function(newTitle, newUrl, options) {
return new RSSFeed(newTitle, newUrl, options);
};
// Code to call the jquery plugin, would normally be found in an index.html file
rss = $.rssObj("Gizmodo", "http://feeds.gawker.com/Gizmodo/full");
rss.sendFeedRequest();
rss.display($('div#feed'));
Obviously, my display() function isn't complete yet, but it serves as a good example. The first console.log() will write all of the relevant data to the console, including the entries array. However, when I try to log the entries array by itself, it's returning an empty array. Any idea why that is?
I guess the problem is that display() is called without waiting for the AJAX request to complete. So the request is still running while you already try to access entries - hence the empty array.
In order to solve this you could move the call to display() into the callback of $.getJSON(). You just have to add the required selector as a parameter:
this.sendFeedRequest = function(selector) {
var self = this;
$.getJSON(this.encodeRequest(), function(data) {
var responseDataFeed = data.responseData.feed;
...
self.entries = responseDataFeed.entries;
self.display(selector);
});
};
EDIT:
If you don't want to move display() into the callback, you could try something like this (untested!):
var RSSFeed = function(feedTitle, feedUrl, options) {
...
this.loading = false;
this.selector = null;
this.sendFeedRequest = function() {
var self = this;
self.loading = true;
$.getJSON(this.encodeRequest(), function(data) {
...
self.loading = false;
if (self.selector != null) {
self.display(self.selector);
}
});
};
this.display = function(jQuerySelector) {
var self = this;
if (self.loading) {
self.selector = jQuerySelector;
}
else {
...
}
};
};

receiving json via ajax asp.net issue

I am trying to receive a json data using ajax asp.net.
i have got a web service with a web method -
[WebMethod]
public List<Song> GetSongListByMood(string Mood)
{
SongBL songbl = new SongBL();
return songbl.GetSongListByMoodBL(Mood);
}
and i have got the javascript code -
$(document).ready(function () {
var cssSelector = {
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_1"
};
var playlist = [];
var options = {
swfPath: "./js",
supplied: "mp3"
};
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options);
$("#slider a").click(function () {
var mood = $(this).text();
var xhr = new XMLHttpRequest();
var url = "AvironaService.asmx/GetSongListByMood";
xhr.open("POST", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var obj = JSON.parse(xhr.responseXML.text);
myPlaylist.playlist = obj;
}
};
var contentType = "application/x-www-form-urlencoded"
xhr.setRequestHeader("Content-Type", contentType);
var qs = 'Mood=' + mood;
xhr.send(qs);
});});
now basically what im trying to do is get the data from the server using ajax in json format and put the data in the playlist variable
You need to make a few changes.
Change your method to return a string instead of List<Song>.
add a using statement using System.Web.Script.Serialization.
Create an instance of JavaScriptSerializer and use that to serialize your object and return the results.
So...
using System.Web.Script.Serialization;
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string GetSongListByMood(string Mood)
{
SongBL songbl = new SongBL();
var jss = new JavaScriptSerializer();
return jss.Serialize(songbl.GetSongListByMoodBL(Mood));
}
Change your AJAX code to leverage the JQuery methods available:
$("#slider a").click(function () {
$.ajax({
"url" : "AvironaService.asmx/GetSongListByMood",
"type" : "post",
"data" : {"Mood" : $(this).text()},
"dataType" : "json"
"success" : function(data){
myPlaylist.playlist = data;
}
});
});

Using My Own Callback with an HttpRequest Object

I'm writing an Http Request without the use of a library (another script was having conflits...)
But Im having trouble with the scope of my object. Below is the calling script, then the Ajax_Request object follows.
function loadCard(e) {
var element = e.target;
if($('overlay')) {
return false; //something is already over the layout
}
var card = '/card/'+element.id;
var option = {method:'post', parameters:'test', async:true}
loadOverlay();
var ajax = new Ajax_Request(card, option);
}
//Ajax_Request
function Ajax_Request(url, options) {
if(typeof url !== 'undefined') {
this.url = url;
}
if(typeof options.method !== 'undefined') {
this.method = options.method;
} else {
this.method = 'get';
}
if(typeof options.parameters !== 'undefined') {
this.parameters = options.parameters;
}
if(typeof options.async !== 'undefined') {
this.async = true;
} else {
this.async = false;
}
if(window.XMLHttpRequest) {
this.request = new XMLHttpRequest();
} //check for MS browser
this.makeRequest = function() {
try {
this.request.onreadystatechange = this.checkReadyState;
this.request.open(this.method, this.url, this.async);
if(this.method == 'post') {
this.request.send(this.parameters);
} else {
this.request.send(null);
}
} catch(err) {
alert(err);
}
}
this.setResponse = function(r) {
alert(r)
this.response = r;
}
this.getResponse = function() {
return this.responseText;
}
this.checkReadyState = function(r) {
switch(this.readyState) {
case 4:
//Represents a "loaded" state in which the response has been completely received.
if(this.status == 200) {
this.setResponse(this.responseText)
}
...
}
}
}
I'm trying to set the response to a property so my calling object can work with it.
But when I try to call this.setResponse(), I get an error that it's undefined.
How can I tie the onreadystatechange callback to my program properly?
The script otherwise returns the data properly, and I could simply output it right there, but I need a bit more flexibility.
Thanks
Rich
This is happening to you because inside the checkReadyState function this actually represents the XMLHttPRequest instance not you Ajax_Request object, thus this.setResponse is undefined. In order to reference your object´s method you have to use a little trick: var that = this.
function Ajax_Request(url, options) {
var that = this;
...
this.checkReadyState = function (r) {
switch(this.readyState) {
case 4:
if(this.status == 200) {
// "this" refers to the XMLHttpRequest,
// but "that" refers your custom Ajax object
that.setResponse(this.responseText)
}
...
}
}
}
I'm not sure whether this is the problem, but you shouldn't be referring to Ajax_Request within the constructor. Use this instead. (this refers to the actual object instance—Ajax_Request refers to the object constructor.)
this.makeRequest = function() {
try {
this.request.onreadystatechange = this.checkReadyState;
this.request.open(this.method, this.url, this.async);
if(this.method == 'post') {
this.request.send(this.parameters);
} else {
this.request.send(null);
}
} catch(err) {
alert(err);
}
};
In this.checkReadyState, try changing this.setResponse(this.responseText) to this.setResponse(this.request.responseText);.

Categories

Resources