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);
}
});
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);
I am struggling with this issue for 2 days...
I have a JavaScript array (20,000K rows and 41 columns). It was originally received in javaScript through an ajax call as shown below,
var dataArray = [];
var dataRequest = {};
dataRequest.SearchCondition = 'some value';
$.ajax({
type: "POST",
url: "api/GetData/ProcessRequest",
dataType: 'json',
cache: false,
async: true,
crossDomain: false,
data: dataRequest ,
success: function (response) {
dataArray = response;
},
error: function (xhr, textStatus, errorThrown) {
dataArray = null;
}
});
In the application, the user will verify the data and send it back to Web API method.
I am trying to send the same data back (dataArray) to web api method but, it fails. Please see the code below,
Option 1: (failed - the request did not hit web api method)
var dataArrayJsonStr = JSON.stringify(dataArray);
$.ajax({
type: "POST",
url: "api/SendData/ProcessRequest",
dataType: 'json',
data: {'dataValue':dataArrayJsonStr },
success: function (response) {
alert('success');
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown)
}
});
In IE 8, I am getting 'out of memory' exception popup. (most of our application users still have IE 8)
In Chrome, it crashes.
Option 2 tried: (don't know how to read the value)
I tried to send the same value to web api through XmllHttpRequest
var dataArrayJsonStr = JSON.stringify(dataArr);
var xmlRequest;
if (window.XMLHttpRequest) {
xmlRequest = new XMLHttpRequest();
}
xmlRequest.open("POST", "api/SendData/ProcessRequest", false);
xmlRequest.setRequestHeader('Content-Type', 'application/text');
xmlRequest.send("dataValue=" + dataArrayJsonStr);
Using Chrome, I am able to post the data successfully to Web API, I am seeing the content-length as '128180309'. But, I don't see the values. How do i get the values in Web API?
Please suggest me how to send large data back to web api from javascript.
Thanks,
Vim
I think you create overhead, maybe I wrong, you can edit me.
Did you really need send back all datas back or you just need send modified data?
Because in real life hard to imagine that user will review 20.000 of rows.
Good example is ExtJS stores, you can see example here
Key thing of stores that they send back to the server only modified or deleted data, it save browser, network and server resources.
Try to add more memory for API or more time excecution, also you can try return data in more small parts. Defining the number of parts to send.
Did you try to send the data by chunks?
I mean, you need to split it in small pieces and perform multiple number of requests.
For example, it can be like:
--HELLO SERVER. STARTING TRANSMITION FOR DATA SET #177151--
PIECE 1/13
PIECE 2/13
...
PIECE 13/13
--BUE SERVER--
So, it will take some time, but you can send any amounts of data without memory problems. If you're struggling with it for 2 days, I think you got some time to code it :)
UPD1: Client code example.
Here's an example of client code. This is a simple chunking algorithm.
Have to say I didn't test it, because it would take a lot of time to represent your situation.
So, you should read it and get the point.
You have a simple function, that takes you whole data set and callbacks for each response (to update your progress bar, e.g.), for successful finish and for error.
Hope, it will help you to make some problems.
Also, I can help you to build architecture on the server-side, but I need to know what technologies do you use.
function sendData(data, onEach, onFinish, onError) {
var CHUNK_SIZE = 1000;
var isFailed = false;
var chunkNum = 0;
var chunk, chunkStart, chunkEnd;
while(data.length + CHUNK_SIZE > chunkNum * CHUNK_SIZE) {
if(isFailed) {
return;
}
chunkStart = chunkNum * CHUNK_SIZE;
chunkEnd = chunkStart + CHUNK_SIZE + 1;
chunk = {
num: chunkNum,
data: data.slice(chunkStart, chunkEnd)
};
ajaxCall(chunk);
chunkNum++;
}
function ajaxCall(data) {
$.ajax({
type: "POST",
url: "api/GetData/ProcessRequest",
dataType: 'json',
async: true,
data: dataRequest ,
success: function (response) {
onEach(data, response);
},
error: function (xhr, textStatus, errorThrown) {
isFailed = true;
onError(arguments);
}
});
}
}
I'm having an issue using JOSN data in MS CRM 2011. I am using the correct REST syntax to pull the CRM data but my JavaScript is the remaining issue.
What I want to do is append data from my JSON to a class of my choosing. I checked the console and no errors are apparent. Originially I believed once I had the JSON object I could pull the data from it using jQuery. Here is the code I currently have:
RetrieveScoutMetadata : (function(scout_displayable){
var query = "/scout_metadataSet?$select=scout_data_type,scout_display_name,scout_display_order,scout_displayable,ImportSequenceNumber,scout_name,scout_metadataId&$orderby=scout_display_order asc&$filter=scout_displayable eq "+scout_displayable+"";
ExecuteQuery(query);
})
RetrieveScoutOpportunity : (function(scout_account){
var query = "/scout_opportunitySet?$select=*&$filter=scout_account/Id eq guid'"+scout_account+"'";
ExecuteQuery(query);
})
RetrieveScoutAccount : (function(scout_account){
var query = "/scout_accountSet?$select=*&$filter=scout_account/Id eq guid'"+scout_account+"'";
ExecuteQuery(query);
})
//
// ExecuteQuery executes the specified OData Query asyncronously
//
// NOTE: Requires JSON and jQuery libraries. Review this Microsoft MSDN article before
// using this script http://msdn.microsoft.com/en-us/library/gg328025.aspx
//
function ExecuteQuery(ODataQuery) {
var serverUrl = Xrm.Page.context.getServerUrl();
// Adjust URL for differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
//
// e.g. data.d.results
alert("OData Execution Success Occurred");
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
$('.up-sell').append(account.scout_num_up_sells);
}
//
// Error Handler
//
function ErrorHandler(XMLHttpRequest, textStatus, errorObject)
{ alert("Error Occurred : " + textStatus + ": " + JSON.parse(XMLHttpRequest.responseText).error.message.value); }
To get response use "complete" function:
complete: function (jsondata, stat) {
if (stat == "success") {
data = JSON.parse(jsondata.responseText);
}
}
So when I attempt the following two responses from nodejs the behavior is different in the browser specifically chrome. I have a file with just the following content SOMESTRING
var string = fs.readSync(filename,'ascii');
res.end(string);
VS.
res.end('SOMESTRING');
and on the front end I use jQuery and I do the following.
$.ajax({type: params.type,
url: 'ajaxrequest',
cache: false,
data: {"name":"value"},
dataType:'text',
error: function(jqXHR, textStatus, errorThrown) {
},
success: function(data, textStatus, jqXHR) {
if(data == 'SOMESTRING')
console.log('data == SOMESTRING');
}
});
No matter what the encoding is (utf8,etc) or trying string.toString() I can not get data == 'SOMESTRING' eventhough if I just res.end('SOMESTRING') the equality works just fine. And yes I am certain that there is no extra white spaces or return carriage.
Try console.log('[' + data + ']');. I'll bet you'll find a newline in there.
I am developing a heavily scripted Web application and am now doing some Error handling. But to do that, I need a way to access the AJAX parameters that were given to jQuery for that specific AJAX Request. I haven't found anything on it at jquery.com so I am asking you folks if you have any idea how to accomplish that.
Here is an example of how I want to do that codewise:
function add_recording(filename) {
updateCounter('addRecording','up');
jQuery.ajax({
url: '/cgi-bin/apps/ajax/Storyboard',
type: 'POST',
dataType: 'json',
data: {
sid: sid,
story: story,
screen_id: screen_id,
mode: 'add_record',
file_name: filename
},
success: function(json) {
updateCounter('addRecording','down');
id = json[0].id;
create_record(id, 1, 1, json);
},
error: function() {
updateCounter('addRecording','error',hereBeData);
}
})
}
hereBeData would be the needed data (like the url, type, dataType and the actual data).
updateCounter is a function which updates the Status Area with new info. It's also the area where the User is notified of an Error and where a Dismiss and Retry Button would be generated, based on the Info that was gathered in hereBeData.
Regardless of calling complete() success() or error() - this will equal the object passed to $.ajax() although the values for URL and data will not always be exactly the same - it will convert paramerters and edit the object around a bit. You can add a custom key to the object to remember your stuff though:
$.ajax({
url: '/',
data: {test:'test'},
// we make a little 'extra copy' here in case we need it later in an event
remember: {url:'/', data:{test:'test'}},
error: function() {
alert(this.remember.data.test + ': error');
},
success: function() {
alert(this.remember.data.test + ': success');
},
complete: function() {
alert(this.remember.data.url + ': complete');
}
});
Of course - since you are setting this data originally from some source - you could rely on the variable scoping to keep it around for you:
$("someelement").click(function() {
var theURL = $(this).attr('href');
var theData = { text: $(this).text(); }
$.ajax({
url: theUrl,
data: theData,
error: function() {
alert('There was an error loading '+theURL);
}
});
// but look out for situations like this:
theURL = 'something else';
});
Check out what parameters you can get in the callback for error.
function (XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
this; // the options for this ajax request
}
You can use the ajax complete event which passes you the ajaxOptions that were used for the request. The complete fires for both a successful and failed request.
complete : function (event, XMLHttpRequest, ajaxOptions) {
//store ajaxOptions here
//1 way is to use the .data on the body for example
$('body').data('myLastAjaxRequest', ajaxOptions);
}
You can then retireve the options using
var ajaxOptions = $('body').data('myLastAjaxRequest');