Uncaught SyntaxError: Unexpected token < On Chrome - json

I know this question has been asked many times but I can't find similarity with my issue. I'm getting this error only in Chrome, in every other browser everything is ok. I return data with JSON in several places but since my code works in other browsers I assume nothing is wrong with it.
Chrome doesn't show me where is error (in my code) it shows me these errors:
This is how I use JSON:
$.post("getData.php", {'id' : id}, function(data){
var obj = jQuery.parseJSON(data);
.
.
.
... some mysqli query
$data = $query->fetch_assoc();
echo json_encode($data);
So I don't see a problem here, can someone help me with this.

You can check your Network (console) and See the answer from the Server ... The "<" will be the first letter of your response. Something like "<"undefined index XY in line Z>"

My solution to this is pretty unbelievable.
<script type="text/javascript" src="/js/dataLayer.js?v=1"></script>
The filename in the src attribute needed to be lowercase:
<script type="text/javascript" src="/js/datalayer.js?v=1"></script>
and that somewhat inexplicably fixed the problem.
In both cases the reference was returning 404 for testing.

Error with Uncaught SyntaxError: Unexpected token < using #Mario answer but that was only part of my problem. Another problem is, javascript doesn't get any data from PHP file. That was solved using this code, inside PHP file: header("Content-Type: text/javascript; charset=utf-8");
This answer is found on this link, where I opened another question to solve this issue: Can't receive json data from PHP in Chrome and Opera

I got the same error ("Uncaught SyntaxError: Unexpected token <" ) at these two lines when testing a sample application .
<script type = "text/javascript" src="raphael-min.js"></script>
<script type = "text/javascript" src="kuma-gauge.jquery.js"></script>
After a control, I realized that, local file locations are not correct and my local server app returns default page as the result. Client app can find the files but the founded files are default page, not the *.js files. So I receive Uncaught SyntaxError: Unexpected token <
I changed to orginal location on the intenet andit solved.
<script type = "text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script>
<script type = "text/javascript" src="//www.jqueryscript.net/demo/Creating-Animated-Gauges-Using-jQuery-Raphael-js-kumaGauge/js/kuma-gauge.jquery.js"></script>

To override the error that you might experience in Chrome (and probably in Safari), try to set the Ajax parameter as dataType: "json". Then you shouldn't call parseJSON() on the obj because the response you'll get comes deserialized.

I have commented my this code : // $('#description').val('<?php echo $_POST['description']; ?>'); and I got that error.

header("Location: route_to_main_page");
I've encountered this problem while having a custom 404 error handling file. Instead of throwing some html content it was suppose to redirect to the main page url. It worked well.
Then I used this as a skeleton for a next project, therefore not changing the "route_to_main_page" actually on the new project (different URL) became a "route_to_external_url" so any 404 errors within your code (missing css stylesheets, js libraries) would return the "Uncaught SyntaxError: Unexpected token <".

I faced similar issue when I moved some of the js files into folders then deployed into production, after some struggle I found out that the js files were not actually got deployed to production. So
make sure that the file for which the error is shown does exist in
the server
the path given is correct
So, In the absence of js file, the server then server responds with as below
<!doctype html>
<html>
<someTag />
<AnotherTag />
</html>
Thats why we get Uncaught SyntaxError: Unexpected token <

It could be that the resource you're trying to request is under restricted access via your web app configuration, i.e. user must be logged for the application to serve the file.
Try adding this to your Web.Config file (this is for .NET applications):
<location path="js/resourcefile.js">
<system.web>
<authorization>
<allow users="?" />
</authorization>
</system.web>
</location>
You can place it anywhere before the closing configuration tag.

If you are trying to perform Ajax file upload or something similar, you have to get rid of displaying further HTML after printing your ajax response text. Probably that gives this error message. If you are using PHP framework you have to follow framework syntax to end the application. If you are coding pure PHP, you can use 'exit' after your ajax response text.
Hope this will help save some ones' time on finding solution for this. :) happy coding!!!

change it to
$.post({
url = 'getData.php',
data : { 'id' id } ,
dataType : 'text'
});
This way ajax will not try to parse the data into json or similar

Seems everyone has difference experiences from this and therfore solutions as well :) This is my "story".
My thing came from a validate.php file fetched with ajax. The output was meant to be :
$response['status'] = $status;
$response['message'] = $message;
$response['param'] = $param;
echo json_encode($response);
And the error that cause the "Unexpected token <" error was simply that in some cases $message hadn't been declared (but only $status and $param). So, added this in the beginning of the code.
$message = ''; // Default value, in case it doesn't get set later on.
So I guess, those "little things" may in this scenario big of quite importance. So be sure to really check your code and making it bulletproof.

Had the same error. My problem was caused from shifting around my project directory, and failing to adjust the path to my static files on the server to reflect the new path (i.e. was ./src/public but should have been ./public).

The only place it worked for me is when I place the scripts in public folder where my index.html resides and then placing these <script type="text/javascript" src="test/test.js"></script> inside <body> tag.

In my case, host had enabled iisnode at my web.config file so I've commented.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers>
<!-- <add name="iisnode" path="*.js" verb="*" modules="iisnode" /> -->
</handlers>
</system.webServer>
</configuration>

Related

Exception: '<' is an invalid start of a value

I have a Blazor Webassembly project with a controller method as follows:
[HttpGet]
public async Task<List<string>> GetStatesForProfile()
{
IConfigurationSection statesSection = configuration.GetSection("SiteSettings:States");
var sections = statesSection.GetChildren();
var states = statesSection.GetChildren().Select(s => s.Key).ToList<string>();
return states;
}
The razor page calls this method:
private async Task<bool> GetStatesModel()
{
try
{
States = await http.GetJsonAsync<List<string>>("api/account/getstatesforprofile");
...
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}, Inner: {ex.InnerException.Message}");
}
I get this Exception:
Exception: '<' is an invalid start of a value.
I read these values from appsettings.json file, And there is no '<' in values.
{
"SiteSettings": {
"States": {
"New York": ["NYC"],
"California": ["Los Angeles", "San Francisco"]
}
}
Also I put a breakpoint in the controller method and it doesn't hit.
What is this error? Is it from parsing json? and how to resolve this?
I had a very similar problem.
In the end it turned out that my browser had cached the HTML error page (I guess I had some problems with the code when I first tried it). And no matter how I tried fixing the code I still only got the error from cache. Clearing my cache also cleared the problem.
It happens when you're trying to access an API that doesn't exist. You have to check your API project connectionstring under AppSettings and make sure it's correct and running. If it's a Blazor project, you can set it as your default project, execute and see if you get a json response.
Most probably the response you are receiving is html instead of actual JSON format for the endpoint you are requesting. Please check that.
An as HTML usually starts with <html> tag, the JSON validator fails on the very first character.
You should also clear any cache, that might be interfering with the returned data. (this has helped people resolve this same issue)
I know this is an old question, but it's one of the top results when Googling the error.
I've just spent more time than I care to admit to tracking down this error. I had a straightforward Blazor hosted app, basically unchanged from the template. It worked just fine when run locally, but when published to my web host API calls failed. I finally figured out that the problem was that I was running the publish from the Client project. When I changed to the Server project it worked properly.
Hopefully my long frustration and slight stupidity will save someone else making a similar mistake.
Seems like your api is not not accessible and its returning error HTML page by default.
You can try below solution:-
I think you are using httpclient to get data to blazor application.
If you have separate projects in solution for blazor and web api,
currently your startup application may set to run blazor project only.
Change startup projects to multiple (blazor and web api app) and give httpClient url in startup of blazor application, as webApi application url, that may solve your issue.
This error indicates a mismatch of the project targeting framework version and installed runtime on the machine. So make sure that the target framework for your project matches an installed runtime - this could be verified by multiple means; one of them is to check out the Individual Components tab of the Visual Studio Installer and lookup the target version.
E.g., there is the TargetFramework attribute in the proj file:
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
Then launch the Visual Studio Installer, click Modify, and visit the Individual Components tab:
Install the missing runtime (.NET 5 Runtime in this case) and you're good to go.
I got the same error. Red herring. use your browser or postman to check your api endpoint is returning the json data and not some HTML. In my case my "api/companytypes" had a typo.
private CompanyType[] companytypesarray;
private List<CompanyType> CompanyTypeList;
private List<CompanyType> CompanyTypeList2;
public async Task<bool> LoadCompanyTypes()
{
//this works
CompanyTypeList = await Http.GetFromJsonAsync<List<CompanyType>>("api/companytype");
//this also works reading the json into an array first
companytypesarray = await Http.GetFromJsonAsync<CompanyType[]>("api/companytype");
CompanyTypeList2 = companytypesarray.ToList();
return true;
}
I know this is an old question, but I had the same problem. It took some searching, but I realized that the return data was in XML instead of JSON.
I'm assuming your "http" variable is of type HttpClient, so here's what I found worked for me.
By setting the "Accept" header to allow only JSON, you avoid a miscommunication between your app and the remote server.
http.DefaultRequestHeaders.Add("Accept", "application/json");
States = await http.GetJsonAsync<List<string>>("api/account/getstatesforprofile");
I had the same issue when passing in an empty string to a controller method. Creating a second controller method that doesn't accept any input variables, and just passing an empty string to the first method helped to fix my problem.
[HttpGet]
[ActionName("GetStuff")]
public async Task<IEnumerable<MyModel>> GetStuff()
{
return await GetStuff("");
}
[HttpGet("{search}")]
[ActionName("GetStuff")]
public async Task<IEnumerable<MyModel>> GetStuff(string search)
{
...
}
Versions of package
Try to update your packages to old or new version. In my case, system.net.http.json is updated from 6.0 to 5.0
Likely you are using an Asp.NetCore hosted WASM application. By default the client's App.razor has something similar to:
<CascadingAuthenticationState>
<Router AppAssembly="#typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView DefaultLayout="#typeof(MainLayout)"
RouteData="#routeData">
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
<Authorizing>
<Loading Caption="Authorizing..."></Loading>
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="#typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Herein lies the problem. Since the Client and Server share the same base address, when the application cannot find "api/account/getstatesforprofile" it gives you the client's "Sorry, there's nothing at the address" page. Which is of course HTML.
I have not found the solution to this issue, but I am working on it and will reply once I find an issue.
I was having the same problem,
"JsonReaderException: '<' is an invalid start of a value."
In my case the url for the REST service was wrong.
I was using the URL from the client project. Then I looked at the Swagger screen,
https://localhost:44322/swagger/index.html
and noticed the right URL should start with "44322"...
Corrected, worked.
In my case, I had a comma (,) written mistakenly at the beginning of the appsettings.json file ...
Just check your file and verify
///////
my error details
//////
System.FormatException HResult=0x80131537 Message=Could not parse the JSON file.
Source=Microsoft.Extensions.Configuration.Json StackTrace: at line 16 This exception was originally thrown at this call stack: [External Code] Inner Exception 1: JsonReaderException: ',' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
////
For me, most of the time it is the #lauri-peltonen answer above. However, now and again, depending on who wrote the controller I have found that this will work in Swagger but not when you call it via the client (at least in this Blazor project we are on.)
[HttpGet]
[Route("prog-map-formulations")]
public async Task<List<GetProgramMapFormulationsResult>> GetProgramMapFormulations(int formulationId)
{
...
}
It sends the request as:
api/formulation-performance-program-map/analytical-assoc-values?formulationId=1
And I get results in Swagger but failes with the '<' OP error.
When I change ONLY the route to:
[HttpGet]
[Route("prog-map-formulations/{formulationId:int}")]
public async Task<List<GetProgramMapFormulationsResult>> GetProgramMapFormulations(int formulationId)
{
...
}
It sends the request as:
api/formulation-performance-program-map/analytical-assoc-values/1
And this works in both Swagger as well as from the Client side in Blazor.
Of course, once updated, I did have to clear the cache!
If you delete "obj" folder in your directory then clean the solution and rebbuild it the exception will be resolved
In all these, there is two things that was my issue and realized, first off was that Route[("api/controller")] instead of Route[("api/[controller]")], that is missing square brackets. In the second exercise I was doing, with the first experience in mind, was from the name of the database. The database had a dot in the name (Stock.Inventory). When I change the database name to StockInventory it worked. The second one I am not so sure but it worked for me.

Google Chrome: DOMException: Registration failed - manifest empty or missing

I am trying to implement Push Notifications on my website (using Pushpad). Therefore I created a "manifest.json" with following content:
{
"gcm_sender_id": "my_gcm_sender_id",
"gcm_user_visible_only": true
}
of course I created a valid GCM-Account and have a sender id
I put the manifest.json into my root directory and I also added this line to my index.php:
<link rel="manifest" href="/manifest.json">
Using Firefox everything works fine and I can send and receive push notifications (so I think the manifest-include works fine), but Chrome won't work...
The console shows following error:
Uncaught (in promise) DOMException: Registration failed - manifest empty or missing
I searched Google for a long time and tried everything I found, but nothing works.
What I tried:
created the manifest.json with "Editor" and saved it as type All Types (so no hidden .txt-file) and also with UTF-8-Encoding.
restarted Chrome
cleared Chrome's cache, history, etc.
I really hope somebody can help me.
For me it was a redirect. The manifest.json must return a 200 status code (must be directly available from the server), without any redirects.
You can check the response via
wget --max-redirect=0 https://example.com/manifest.json
or
curl https://example.com/manifest.json
I faced same issue,added manifest file right after head tag . which worked for me.Cheers!
This may be an issue with your Service Worker scope. I ran into a similar problem when I rearranged my files/directories. Make sure your sw.js is on the same level as your manifest.json, otherwise the service worker won't be able to find your manifest. Try putting them both in the root of your directory. Optionally, you can specify the scope of your service worker by adding it to serviceWorker.register():
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/sw-test/'})
.then(function(reg) {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
}
Read more here:
https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers
Was wondering if your "manifest.json" is public accessible ?
If not maybe you can try to set it public accessible to see if that helps or not.
And it seems that the current chrome, when getting the "manifest.json" won't supply the cookies.
Because I didn't find an answer anywhere out there in the WWW, but managed to get it working after some time I want to provide my solution/answer for other users, who probably have the same problem:
In the file where I inlcuded the Pushpad files I wrote some PHP-Code before the <head>-Tag to include some files, e.g. for database connection. After I moved the PHP-Code below the <head>-Tag everything worked fine.
There seem to be three ways to fix this bug:
a) No redirects for "manifest.json" file.
b) Put a link to this file at the top of the tag.
c) Be sure, that there is no other manifest file before this one, cause it seems that web push script will try to import the first one and return an error due to the wrong data.
I have tried all three and finally forced Chrome to behave.
Adding the following block fixed this for me:
self.addEventListener('push', (event) => {
const title = 'Get Started With Workbox';
const options = {
body: event.data.text()
};
event.waitUntil(self.registration.showNotification(title, options));
});

Load template/html in require.js with text plugin

Since two days I try to load a template in require.js using the text plugin, but I can't manage that.
define(['jquery', 'text!myView.html'], function ($, myView) {...
Produces the error: XMLHttpRequest cannot load
So I put myView.html to a local Webserver and enabled CORS
define(['jquery', 'text!http://localhost/myView.html'], function ($, myView){...
Produces the error: Uncaught SyntaxError: Unexpected token <
Google told me, I should use the requirejs optimizer, which produces a .js out of my html file. This should solve the problem.
To be honest, I really don't undertand what to write in the build.js.
It's so confusing to me. Here is an example build.js: https://github.com/jrburke/r.js/blob/master/build/example.build.js
The only thing I know is that "optimizeAllPluginResources" option has to be true. But what about all the other options?
build.js:
({
paths: {
myView: "myView.html"
},
optimizeAllPluginResources: true,
name: "myView",
out: "myView.js"})
..doens't work
Let me summarize: I only want to optimize a single html file, to use it my Application, nothing else.
Thanks for help.

Safari and Chrome do not want to JSON.parse

I'm trying out localStorage and JSON using a variety of browsers with this piece of code:
function getStorage() {
stored = JSON.parse(localStorage['test']);
if (typeof stored == 'object') {return stored;}
}
Chrome gives me the following error message: "Uncaught SyntaxError: Unexpected token u" for the first line inside the function body. For that same line, Safari says "SyntaxError: Unable to parse JSON string". Firefox does not give any error messages for that line.
Other JSON.parse examples (from books, etc) work fine in both Safari and Chrome. For instance, this one from "Pro JavaScript" by Nicholas Zakas:
var jsonText = "{\"name\":\"Nicholas C. Zakas\", \"age\":29, \"author\":true }";
var object = JSON.parse(jsonText);
alert(object.name); //"Nicholas C. Zakas"
No problem at all with getting that to work. Local storage also works fine in both.
I've also checked the encoding on all my files using file -I my file and all files, both my own and the ones from the above book, are encoded as filename.html: text/html; charset=us-ascii - so encoding doesn't seem to be the problem here.
This is perplexing. Thanks a lot for any help.
/ James
It's because the content of localStorage['test'] is undefined, hence the unexpected u.
Thanks for the advice on debugging the contents of localStorage directly. The bug was in the line if (localStorage.length == 0). I had some other data in localStorage from previous apps, so json didn't get set to anything inside that conditional.

Using Ext JS with my HTML Files

I have an application uses Spring Security 3(has a Jackson Marshaller) runs on a Tomcat 7. I designed my application with Jquery and it runs well. I designed a login page with Ext JS and after successful login it redirects to index.html. However it gives an error and can't redirect because when server sends HTML file it comes into that function at Ext JS:
Ext.util.JSON = new (function(){
...
doDecode = function(json){
return eval("(" + json + ")");
},
...
I wants to render it as a JSON response and gives an error as usual. How to solve it?
PS: It gives that on Firebug:
syntax error
[Break On This Error] (<!DOCTYPE html>
The server is not returning valid JSON. Its look as if it is returning a HTML page (perhaps a friendly error page). If you follow the stack trace up its probably Ext.decode response.responseText (inspect this you'll see whats returned although not the best way)
First step would be to investigate the request in the Net panel in Firebug or Chrome, look at the request and response headers and content this will point you in the right direction. Please please please do not resolve this problem without first learning to use a client side browser debugger (Firebug or Chrome Dev Tools or even Safari) such as walking the stack on break on error, break on XHR, inspect the XHR headers and response etc.. not just watching the console window.
You might be able to fix this continuing blind but you'll pay heavily again next time.