My server (node.js) maintains an array :
var list = [];
I want to use this array in some js code (client side). I would like to retrieve it thanks to ajax. What is the best practice?
$.ajax({
url: "http://localhost:8000/updatePendingAlerts",
timeout: 2000,
success: function (data) {
console.log(data);
//data should be an array
},
error: function(jqXHR, textStatus, errorThrown) {
clearInterval(timeout);
alert('error ' + textStatus + " " + errorThrown);
}
});
Serialise it to JSON (with JSON.stringify) and output it with an application/json content-type header.
It will then be an array in data with the client side JavaScript you already have.
Related
I am working on my webdesign assignment based around ajax. I am having a problem with the JSON.parse() function. The problem goes as follows, I perform a get request on my JSON database using ajax:
artist_list = $.ajax({
dataType: "json",
async: false,
method: "GET",
url: "/database/artists.json",
error: function (xhr) {
console.log("AJAX error:", xhr.status);
},
success: function(xhr, responseText) {
console.log("Ajax operation succseded the code was:", xhr.status);
console.log("This is the output", responseText);
response = responseText;
console.log("Parsing artist list");
JSON.parse(response);
console.log("Artist list parsed");
},
done: function(data, textStatus, jqXHR){
console.log("data:", data);
console.log("Response text",jqXHR.responseText);
}
})
The console log of the responseText matches what the JSON file I wanted but,
when I run response text through a for loop the log returns the JSON file char by char:
artist_list = artist_list.responseText;
JSON.parse(artist_list);
console.log(artist_list);
for(var i = 0; i < 1; i++) {
console.log("generating artist,", i);
console.log("which is:", artist_list[i]);
index = parseInt(i);
index = new artist_lite(artist_list[i]);
artist_lite_dict.push(index);
}
The console returns:
generating artist, 0
which is: {
The list is limited to one because of the lenght of the JSON object which I am trying to pass through. The JSON can be found here https://github.com/Stephan-kashkarov/Collector/blob/master/main/database/artists.json along with the whole code for testing purposes.
Thanks for your help!
- Stephan
You need to save the result of JSON.parse(artist_list); into some variable. I guess in your code you would like to solve it like this:
artist_list = JSON.parse(artist_list);
This thread is very similar to that question but I am not convinced by the answer given ("The library can't be used if the application is not deployed on the same sharepoint site domain") because in this page here the author insists on the fact that it is possible via the object SP.RequestExecutor(appweburl).
So I followed all the steps mentionned in the page and I ended up with this code:
$(document).ready(function () {
var hostweburl = decodeURIComponent("https://lpl.sharepoint.com/sites/TestPortail");
var appweburl = decodeURIComponent("http://localhost");
var scriptbase = hostweburl + "/_layouts/15/";
// Load the .js file using jQuery's getScript function.
$.getScript( hostweburl + "/_layouts/15/SP.RequestExecutor.js", continueExecution );
function continueExecution() {
var executor;
// Initialize your RequestExecutor object.
executor = new SP.RequestExecutor(appweburl);
console.log(executor); // just to see if created
// You can issue requests here using the executeAsync method
// of the RequestExecutor object.
executor.executeAsync({
url: appweburl + "/_api/SP.AppContextSite(#target)/web/title?#target='" + hostweburl + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
console.log('Successfully obtained data.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('There is an error.');
console.log(jqXHR.status);
console.log(textStatus);
console.log(errorThrown);
}
});
}
});
When I executed it from localhost I get this:
I have been looking for the solution for 2 days. Maybe it is because the localhost is not a https, but even with this great answer I have not managed to do it (wamp won't start).
Any help would be appreciated.
var url="service/signProcess.aspx";
//sets the important hidden field of the form by which server decides what to send
$('#hdnReqType2').val('sign87162');
var data=$("#frmLogin").serializeArray();
var success=function(rdata, textStatus, jqXHR) {
console.log(rdata);
};
var fail=function(jqXHR, textStatus, errorThrown) {
console.log("Error" + errorThrown + " " + textStatus);
}
$.post(url,data,success,"text").fail(fail);
I am using this in the console of the page 'http://fsa.citop.in/lnct/' opened in chrome(when login form of the page is empty) and got a JSON String as response.
I found out at https://api.jquery.com/serializeArray/ that serializeArray() returns an array of objects having name and value.
so when I used
var data=[{name :"txtLogId",value: ""},{name:"txtLogPass",value: ""},{name:"hdnReqType2",value: "sign87162"}];
which I thought to be equivalent object to object returned by $("#frmLogin").serializeArray() . Server gave me a HTML page in response.
I tried console.log(data) with both the version of data variable and couldn't find any difference. Please explain me whats the difference between both the version of data and what could be the correct equivalent object to serailizeArray().
The data argument in success callback is the response object (JSON).
Your data variable before success function is conflicting with data argument in success callback.
I suggest you change the name of the data variable or change the name of data argument in success function.
var url="service/signProcess.aspx";
//sets the important hidden field of the form by which server decides what to send
$('#hdnReqType2').val('sign87162');
var data=$("#frmLogin").serializeArray();
var success=function(dat_a, textStatus, jqXHR) {
console.log(dat_a);
};
var fail=function(jqXHR, textStatus, errorThrown) {
console.log("Error" + errorThrown + " " + textStatus);
};
$.post(url,data,success,"text").fail(fail);
Here in the above code I have changed data argument in success callback function to dat_a.
So I'm made a php script to output tweets in json and now I am trying to parse with data with javascript. I've tested the data and it's valid json. When I do the request in Example 2 it works fine. When I try to parse using example 1 it fails saying Uncaught SyntaxError: Unexpected token N. What is my problem?
Example 1
var request = $.ajax({
url: "http://website.com/twitter.php",
type: "GET",
data: {
twitter: 'google'
},
dataType: "json"
});
request.done(function(data) {
var resp = JSON.parse(data);
console.log(resp);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
Example 2
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://website.com/twitter.php?twitter=google", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
console.log(resp);
}
};
xhr.send();
JSON Data
["New Google Trends features\u2014including Trending Top Charts\u2014make it easier to explore hot topics in #GoogleSearch g.co\/jmv6","Stating now, join our Hangout w\/ President Barroso on the #SOTEU goo.gl\/FZCXaJ #askbarroso","Explore the Galapagos Islands + see sea lions, blue-footed boobies & other animals w\/ Street View in #googlemaps g.co\/ufjq","Slow connections may keep Google Instant (results as you type) from working smoothly. Our troubleshooting tip: g.co\/bve7","From #BBCNews: search VP Ben Gomes on how search has become more intuitive & the next frontier (includes video) goo.gl\/Z0ESkJ","\"Audio Ammunition\" - an exclusive 5-part documentary about the Clash from #GooglePlay g.co\/zrxn & on youtube.com\/googleplay","justareflektor.com\u2013\u2013an interactive #ChromeExp HTML5 film with #arcadefire, featuring their new single, \u201cReflektor\u201d","#askbarroso about the State of the European Union in a live conversation Thurs, Sept 12 g.co\/n3tj","Don\u2019t get locked out: set up recovery options for your Google Account now g.co\/sm4k","It's time for more transparency: our amended petition to the the U.S. Foreign Surveillance Court g.co\/gkww"]
Since you have json as your data type, data in your done callback will already be parsed so trying to parse it again is causing the error.
request.done(function(data) {
//var resp = JSON.parse(data);
console.log(data);
});
jQuery's .ajax automatically parses the JSON response, so .parse shouldn't be called separately. Use the following:
$.ajax({
url: "http://example.com/twitter.php",
type: "GET",
data: {
twitter: 'google'
},
dataType: "JSON",
success : function(JSON,jqXHR){
console.log(JSON.value); /* value of value */
console.log(jqXHR.responseText); /* all returned */
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request failed: " + textStatus);
}
});
Hi I am doing a ajax post via a JSP. I am posting JSON data in string format (parsed using parseJSON, then I use the JSON stringify to return to a string.
This post works fine. But what I am not sure how to do, is basiclally I sending this to a a client gateway, which translates this jsonString into XML to do some internal processing. This internal work will generate an XML response, that needs to be sent back to my JSP. I plan on receiving and this XML in the ajax post 'success' function facility.
So far I have been able to make this work with the success function "data" item being HTML. But I am not sure how this can be done when I want to XML. How do I do this? How do I receive XML, and how do you host/find/display the XML for it to be returned in the sucess 'data' function?
My other option, is that if it is not XML that I want to recieve, I could possibliy receive JSON data. How can I host/find/display JSON data for it to be returned in the sucess 'data' function?
This is my post code:
$.ajax({
type: "POST",
url: suppliedURL,
data: "jsonData=" + jsonString, // I have already done a json stringify on this.
success: function(data, textStatus, jqXHR) {
alert('Success : ' + data); .. I want this to be XML
alert('textStatus : ' + textStatus);
alert('jqXHR : ' + jqXHR);
var jsonJqXHR = JSON.stringify(jqXHR);
alert('jsonJqXHR : ' + jsonJqXHR);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
},
//complete: alert('complete'),
dataType: "text" // xml, json, script, text, html
});
Change dataType to xml; after that data in the success method will be an XML document.