I am using Freebase JS api to fetch topic details. This is a simple function for that:
function simpleTopicDetail(topicIds){
path = 'freebase/v1/topic' + topicIds;
var opts = {
'method': 'GET',
'path': path,
'params': {'filter':'/common/topic/article'}
};
var request = gapi.client.request(opts);
request.execute(onFinalSuccess);
var onFinalSuccess = function(data){
console.log(data);
//do something with data
//parsing JSON resp to get a node value.
}
}
On debugging I see, it goes to onFinalSuccess and then nothing! Skips to the end. What's wrong here?
NOTE I'm using it in conjuction with YT API. It's a sepearte function though. Can it a problem?
You are refering to the call back function before it's assigned.
Try:
function simpleTopicDetail(topicIds){
path = 'freebase/v1/topic' + topicIds;
var opts = {
'method': 'GET',
'path': path,
'params': {'filter':'/common/topic/article'}
};
var request = gapi.client.request(opts);
request.execute(function(data){
console.log(data);
//do something with data
//parsing JSON resp to get a node value.
});
}
Related
Browser: IE 11
PlatForm: SharePoint 2016
I am trying to cache data into an array when page loads, so that the array can be used throughout the rest of my code for efficiency purposes. I have 4 arrays and the data to populate the arrays will be coming form 4 different SharePoint lists. I am using jQuery to make the calls to the lists and to retrieve the data. I believe that the way I have done it is wrong because though the calls are successfully made the arrays are not populated by the time I use them. Here's an excerpt of the code:
var cacheNavData = [];
var cacheSubNavData = [];
var cacheMegaMenuData = [];
var cacheCategoryMenuData = [];
$(document).ready(function(){
getNavData();
getSubNavData();
getMegaMenuData();
getCategoryMenuData();
})
function getNavData(){
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('"+lName+"')/items";
var headers = {
"accept":"application/json;odata=verbose"
}
$.ajax({
url:endPointUrl,
async:false,
type:"GET",
headers: headers,
success: function success(data) {
cacheNavData = data.d.results;
}
});
}
function getSubNavData(){
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('"+lName+"')/items?$select=parentNav/URL, parentNav/URLNAME,subLink&$expand=parentNav";
var headers = {
"accept":"application/json;odata=verbose"
}
$.ajax({
url:endPointUrl,
async:false,
type:"GET",
headers: headers,
success: function success(data) {
cacheSubNavData = data.d.results;
}
});
}
function getMegaMenuData(){
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('"+lName+"')/items";
var headers = {
"accept":"application/json;odata=verbose"
}
$.ajax({
url:endPointUrl,
async:false,
type:"GET",
headers: headers,
success: function success(data) {
cacheMegaMenuData = data.d.results;
}
});
}
function getCategoryMenuData(){
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('"+lName+"')/items";
var endPointUrl = "_api/web/lists/getbyTitle('"+lName+"')/items";
var headers = {
"accept":"application/json;odata=verbose"
}
$.ajax({
url:endPointUrl,
async:false,
type:"GET",
headers: headers,
success: function success(data) {
cacheCategoryMenuData = data.d.results;
}
});
}
console.log(cacheNavData);
console.log(cacheSubNavData);
console.log(cacheMegaMenuData);
console.log(cacheCategoryMenuData);
Now, I know that the problem is Asynchronous and I'm still trying to wrap my head around it. I've looked at several problems and explanations on this site. I've also looked at different articles and watched videos but I still don't fully get it. In this situation, I know that when I'm looking to check the data in the console.log(), the Ajax call has not returned the data yet. Through all of my readings, I have come to understand that. The part that I'm not getting is the fix or the how do I prevent that from happening. I tried the following to fix this problem but it didn't work. Maybe I did something wrong. Any help would be much appreciated. Thanks!
var cacheNavData = [];
var cacheSubNavData = [];
var cacheMegaMenuData = [];
var cacheCategoryMenuData = [];
$(document).ready(function() {
var cache1 = getData("Navigation", "cacheNavDataVar");
var cache2 = getData("Sub Navigation", "cacheSubNavDataVar");
var cache3 = getData("category menu", "cacheCategoryMenuDataVar");
var cache4 = getData("Mega Menu Category", "cacheMegaMenuDataVar");
$.when(cache1, cache2, cache3, cache4).done(function(results){
if(results){
createNavigation(cacheNavData)
}
})
});
I hope above highlighted line is self explanatory. If you call multiple ajax async : true requests then browser opens new tcp port for every request and as soon it get response from any request, it starts calling ajax success function.
I have a data coming to NodeJS and then it needs to be served to Ajax query. but because the NodeJS is transfering it as chunked data, none of the general Javascript/JQuery ajax methods are able to capture the packet.
How can i get the values
nodeJS:
http.createServer(options, (req, res) => {
msg = c++_to_javascript();
res.writeHead(200);
res.end(msg);
}).listen(89);
Javascript/JQuery:
received the data as transfer encoded: chunked as a result no methods are able to decode the received packets in JS.
How could i solve it from NodeJS or in JS?
TRY 1: FAILED
$.stream(javascript_to_c++,{
open:function(){
console.log("opened");
},
message:function(event){
console.log(event.data);
buf1 = buf1 + event.data;
},
error:function(){
console.log("error");
},
close:function(){
console.log("closed");
}
});
TRY2 : FAILED
var test = $.ajax({
type: "GET",
url: javascript_to_c++,
async: false,
success:function(m) {
buf1 = buf1 + m;
}
}).responseText;
console.log(test);
TRY 3: FAILED
// Define a method to parse the partial response chunk by chunk
var last_index = 0;
function parse(xhr) {
var curr_index = xhr.responseText.length;
if (last_index == curr_index) return; // No new data
var s = xhr.responseText.substring(last_index, curr_index);
last_index = curr_index;
console.log(s);
}
function test() {
var xhr = new XMLHttpRequest();
var url = javascript_to_c++;
xhr.open("GET", url, true);
xhr.send();
// Check for new content every 5 seconds
var interval = setInterval(parse, 5000);
// Abort after 25 seconds
setTimeout(function(){
clearInterval(interval);
parse(xhr);
xhr.abort();
}, 25000);
}
test();
You just have to properly wait for the response to come back. I'm not too familiar with the other ajax methods you're using but let's look at this for example:
var test = $.ajax({
type: "GET",
url: javascript_to_c++,
async: false,
success:function(m) {
buf1 = buf1 + m;
}
}).responseText;
console.log(test);
Are you expecting test to be the response? $.ajax returns a Promise representing the asynchronous request. It's not until the success callback is called or the promise is resolved when you'll get the response text. Try this instead:
var test = $.ajax({
type: "GET",
url: javascript_to_c++, // I'm assuming this is a valid URL?
success:function(content) {
console.log(content); // This is your actual full response.
}
});
As far as having the node process specify the content type, try the content-type header:
res.set('content-type', 'text/plain');
res.end(msg);
Update:
As already pointed out, it's highly doubtful that the Transfer-Encoding thing is actually a problem. It you do want to disable it, do:
res.set('transfer-encoding', '');
...but really, it shouldn't be necessary.
Another Update:
Not using Express? You'll just need to slightly modify this:
res.writeHead(200, {
'content-type': 'text/plain',
'transfer-encoding': '' // not recommended...
});
res.end(msg);
this is my code
<script type="text/JavaScript">
var myarray = new array();
function getsvg1() {
$.ajax({
alert("hello");
type: "post",
url: "WebForm1.aspx/getsvg1",
alert("abc");
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
alert(cars);
alert("hi");
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</SCRIPT>
webservices
[System.Web.Services.WebMethod]
public static ArrayList getsvg1()
{
XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/NewFolder1/10000.svg"));
//XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/Orders/100001_PRO/2/svg0.svg"));
//XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
//var g = doc.Descendants(ns1 + "image").FirstOrDefault();
// XDocument doc = XDocument.Load(Server.MapPath("~/excelfiles/svg0.svg"));
XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
var retrieveimage = doc.Descendants(ns1 + "image").FirstOrDefault();
var retrivetext = doc.Descendants(ns1 + "g").FirstOrDefault();
ArrayList arlelem = new ArrayList();
foreach (XElement element in doc.Descendants(ns1 + "g"))
{
//string[] parts = element.Split(',');
Console.WriteLine(element);
arlelem.Add(element);
}
// var retrivetext1 = doc.Descendants(ns1 + "text").SelectMany(i => i.ElementExtensions.Select(e => e.GetObject<XElement>().Attribute("url").Value)).ToArray();
//var retrivetext = doc.Descendants(ns1 + "text").All();
string v = arlelem[1].ToString();
string values = retrieveimage.ToString();
string values1 = retrivetext.ToString();
char[] delimiterChars1 = { ' ', ',', '"', '\\', '\t', '=' };
//string text = "one\ttwo three:four,five six seven";
//System.Console.WriteLine("Original text: '{0}'", text);
string[] words = values.Split(delimiterChars1);
string[] words2 = values1.Split(delimiterChars1);
string[] newword = v.Split(delimiterChars1);
//Session["newimgwidth"] = words[15];
return arlelem;
}
alert is not coming for cars values and breakpoint not going for success and failure. in this example i m calling server side function from
json that function result
To start with your ajax request is filled with syntax errors.
The $.ajax({ }) block cannot have a alert("hello"); inside it
Remove alert("abc"); too
use console.log() instead of alerts in your success method, this is not one of the error but a suggestion/advice.
What is your method returning in case of error ? In your ajax error method it seems to be expecting a string value.
Why are you using type: "post" when you are not posting any data to your method. Use a 'get' instead.
To debug your server side code, try opening the WebForm1.aspx/getsvg1 url in your browser window and see if you get the expected response. If all is well next try sending an ajax request using a client like postman rest client to check the response again.
Hope this helps.
you can use jQuery for this:
$.getJSON( "http://server.com/webservice", function( data ) {
console.log(JSON.stringify(data));
}
See more details at: http://api.jquery.com/jquery.getJSON/
{key,value } it allow json data.means already availble options or new define json value only. you can enter,if you try to alert("hello") it doest allow.so it stopped.so,try without alert message use inside brackets {}.
I am writing a test and would like for prototypejs to read from a text file and store variables. Is this possible and what am I doing wrong?
Selenium.prototype.doLoadData = function(dataFile) {
new Ajax.Request('dataFile', {
method:'get',
onSuccess: function(data) {
var lines = data.split("\n");
lines.each(lines, function(i) {
var line = lines[i].split(' = ');
window[line[0]] = line[1];
globalStoredVars[line[0]] = line[1];
});
}
}
);
};
PrototypeJS passes the AJAXTransport object to the success callback, not just the data. Try this
onSuccess: function(resp){
var data = resp.responseText;
//or if your response contains JSON
//and the Content-Type: application/json header was sent in the response
var data = resp.responseJSON;
}
I'm trying to send JSON data to my web server via jQuery and I'm running into an error.
Uncaught TypeError: Cannot use 'in' operator to search for 'context' in {"id":45,"isRead":true}
code I am testing:
var obj = {};
obj.id = 45;
obj.isRead = true;
var data = JSON.stringify(obj);
var url = "/notification/read"
$.ajax(url, data, 'application/json', function() {
// code remove notification from the DOM
});
});
Is there a better or more correct way to do this? Not sure if I'm getting the params right on the $.ajax call either.
UPDATE
code I got to work
var obj = {
id: 45,
isRead: true
};
var json = JSON.stringify(obj);
var url = "/notification/read"
$.ajax({ url: url,
type:'POST',
contentType: 'application/json',
data: json,
success: function(data, textStatus) {
// do stuff
}
});
My server was expecting JSON data POSTed as application/json. So was I wrong in thinking I needed all these variables? without these it was sent as a GET and was application/x-www-form-urlencoded. Without the stringify it also didn't work.
You are passing too many arguments to the ajax function: http://api.jquery.com/jQuery.ajax/
Also, the JSON.stringify call is not necessary, jQuery will take care of that for you.
var obj = {
'id':45,
'isRead':true
};
$.ajax({
url: "/notification/read",
data: obj,
success: function(data, textStatus){
/* code here */
}
});
$.ajax(url, obj);
You need to send an object as second param
{success: success, data: data}
Documentation is here:
http://api.jquery.com/jQuery.ajax/
You have to pass parameters as one object, not multiple ones