0

I need help guys.

I am trying to fetch data from the server which is returning JSON data but I am getting the following error message (in Chrome 52).

It seems like the JSON data that is returned is invalid or its not in the expected format.

ncaught SyntaxError: Unexpected token <

My server is returning data in the following JSON format

"[{\"ActionCardId\":1,\"ActionCardNumber\":\"279877\",\"AccountNo\":\"2202322179\",\"ClientName\":null,\"CellNumber\":\"0787596971\",\"TenantName\":null,\"TenantCellNumber\":null,\"AddressStandNo\":null,\"AddressStreet\":\"43 DELMAS AVENUE\",\"AddressSuburb\":\"BOKSBURG\",\"AddressCity\":null,\"AddressPortion\":null,\"AddressEarthNo\":null,\"AddressPremise\":null,\"AddressGISKEY\":null,\"AmountDueTotal\":4080.0,\"AmountDue30Day\":null,\"AmountDueCurrent\":null,\"AmountDue60Day\":null,\"ServiceLevy\":null,\"MeterNumberWater\":null,\"MeterNumberElectricity\":\"M22541\",\"MeterNumberElectricity2\":null,\"MeterNumberElectricity3\":null,\"MeterNumberPrePaid\":null,\"IsPrinted\":true,\"IsResidential\":null,\"ActionSuccessful\":false,\"ActionCardDate\":\"2016-08-20T00:00:00\",\"Remarks\":null,\"UnSuccessfulReason\":null,\"CaptureContractorId\":null,\"AddressCombo\":\", 43 DELMAS AVENUE, BOKSBURG, , \",\"BillCycleName\":\"120\",\"ServiceIndicator\":null,\"WaterReading\":null,\"WaterReadingDate\":null,\"ElectricityReading\":null,\"ElectricityReadingDate\":null,\"Unit\":null,\"ActionCardTypeId\":2,\"ContractorId\":1,\"ActionCardStatusId\":1,\"UnSuccessfulActionReasonId\":null,\"TechnicianId\":1,\"AccountInfoId\":null,\"ServiceDeliveryCentreId\":4,\"BillCycleId\":2,\"ActionCardType\":{\"ActionCardTypeId\":2,\"Active\":null,\"CreatedByOnlineUserId\":null,\"DateCreated\":null,\"DateModified\":null,\"Deleted\":null,\"Description\":\"Electricity Disconnection\",\"ModifiedByOnlineUserId\":null,\"Name\":\"ED\",\"CreatedByUser\":null,\"ModifiedByUser\":null},\"Contractor\":null,\"ActionCardStatus\":null,\"UnSuccessfulActionReason\":null,\"Technician\":null,\"AccountInfo\":null,\"ServiceDeliveryCentre\":null,\"BillCycle\":null,\"ActionName\":\"ED\",\"DateCreated\":\"2016-07-06T00:00:00\",\"DateModified\":\"2016-08-13T10:24:17.5833635\",\"CreatedByOnlineUserId\":null,\"ModifiedByOnlineUserId\":\"fa93e65d-e4a7-4a0c-91c6-4561e2612f9c\",\"CreatedByUser\":null,\"ModifiedByUser\":null}]"

I am using Javascript in my client side

$("#importDailyJobs").click(function () {

        var technicianId = 1;

        var serverUrl = "http://localhost:35825/Mobile/ImportDailyReadings"

        $.get(serverUrl, { TechnicianId: technicianId }, function (data, status) {

            alert("Success");
            console.log(data);


        }, "jsonp");

    });

I using jsonp because I am using cross domain to get the data.

Linda
  • 201
  • 1
  • 7
  • 19
  • 1
    `Uncaught SyntaxError: Unexpected token <` means there's a `<` in the response data. Check the network tab of your browser for the actual response. – Jason P Aug 22 '16 at 12:56
  • 2
    Most commonly - you probably actually got sent an error response in html/xml format. – tymeJV Aug 22 '16 at 12:58

2 Answers2

0

It seems like you are encountering an error on that URL and the response is enclosed inside an html tag <>.

As suggested by "Jason P" you should check the actual response in the "raw" format. If you are on Google Chrome, you can press F12, then navigate to "Network" Tab, and then select "XHR" after which you should trigger the respective event by clicking on #importDailyJobs. You should see the Ajax Request, on clicking of which you shall be able to view the details for that request, like Headers, Preview, Response etc.

You can view the raw data inside the Response tab.

Also on a side note, just wrap the string in single quotes when you have double quotes inside it, and if you have both then wrap the string in the one which is least used, to prevent lots of escaping as can be seen in your sample response.

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • Thank you guys for your help. Here is the **Response**...Unfortunately I cannot post here...its too long. I will try to see whats wrong with it – Linda Aug 22 '16 at 14:27
  • @Linda Edit your question and add it there. – Jason P Aug 22 '16 at 14:32
  • @JasonP thank you, I have edited my question with the Json results from the browser. The Json data seems to be fine, but its not running my function (code inside the function). Do you perhaps know why? – Linda Aug 22 '16 at 20:34
0

Your returned data is not a JSON. It's a string. You explicitly expect JSON via the jsonp argument, and you return a string, hence the error.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • JSON *is* a string. If it's not a string, it's not JSON. – Jason P Aug 22 '16 at 13:20
  • JSON = JavaScript Object Notation. JSON is an object. It can be stringified using `JSON.stringify()` and parsed using `JSON.parse()`, but an object is not a string. – Jeremy Thille Aug 22 '16 at 13:25
  • No. The result of `JSON.stringify()` is a string in JSON format. The result of `JSON.parse()` is a javascript object. See http://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation or http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/ – Jason P Aug 22 '16 at 13:29
  • Okay so go to jsonlint.com, validate `{"key":"val"}`, and then come again and say "JSON is a string, if it's not a string, it's not JSON". Apparently you don't know what Json is. – Jeremy Thille Aug 22 '16 at 13:37
  • Sure, neither do the people in the links I posted either, apparently. – Jason P Aug 22 '16 at 13:48
  • I've been a web developer for many years, I'm now MEAN stack developer, I've built countless websites with jQuery, Angular and React, and never, ever have I sent a string as a JSON. And neither has any of my colleagues present here. Never used stringify or parse, always iterated pure JSON from the server. Well, thank you for redefining all I thought I knew. – Jeremy Thille Aug 22 '16 at 13:52
  • Not to spoil that cute little thing that you guyz got there going, Just wanted to say that JSON is not an object or a string its a *notation*, a *format* that lays the ground rules, which in turn are supposed to help in exchange of data between apps. The exchange is supposed to happen in plain text/string format. Whether to send a correct JSON or an Incorrect one is totally the sender's call, Likewise how to interpret it is totally the receiver's call. Btw, please carry on :) – Mohd Abdul Mujib Aug 22 '16 at 13:55
  • @MohdAbdulMujib, Yes, it is a notation for representing serialized data *as a string* – Jason P Aug 22 '16 at 15:03
  • We're not talking about how servers exchange data. In that case, json is a chain of binary numbers or electric impulses. Is "12345" a valid json? Yes. Is `{"key":"val"}` a valid json? Yes. `typeof {"key":"val"} === 'object'`. Hence the statement "if it's not a string it's not json" is wrong, end of story. – Jeremy Thille Aug 22 '16 at 15:08
  • 2
    @JeremyThille If you are doing `{"key":"val"} === 'object'` then you are executing javascript code, and in that case, `{"key":"val"}` is a javascript object, not json. json is like xml, it's a way of serializing data. But you don't say you have an xml object, you have an xml-formatted string or text. Just because a json-formatted string looks like the syntax you use to define a javascript object in javascript does not mean that the two are the same thing. – Jason P Aug 22 '16 at 15:11
  • I think the [ECMA-404 Standard](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) can shed some light on this argument. According to the standard, _"JSON is a text format that facilitates structured data interchange between all programming languages."_ Additionally, _"Programming languages vary widely on whether they support objects, and if so, what characteristics and constraints the objects offer....Most programming languages will have some feature for representing such collections, which can go by names like record, struct, dict, map, hash, or object."_ – War10ck Aug 22 '16 at 20:26
  • So in conclusion, JSON is passed between systems as a serialized string. Whether that system keeps the data as a string or parses it to an object, map, struct, associative array, etc. is entirely dependent on the programming language's interpretation and implementation of the JSON spec. As the standard notes: _"It [JSON based on ECMA Language Specification 3rd edition] does not attempt to impose ECMAScript’s internal data representations on other programming languages. Instead, it shares a small subset of ECMAScript’s textual representations with all other programming languages."_ – War10ck Aug 22 '16 at 20:29
  • @War10ck thank you for the lesson and information sharing. – Linda Aug 23 '16 at 08:20
  • Does anyone know why my code inside the function does not get executed? `function (data, status) { console.log(data); alert("Success");}` – Linda Aug 23 '16 at 11:28