Angular - Redirect to a Route from JavaScript - javascript

How do I properly redirect a user to a route in Angular in from JavaScript?
Most of the redirection that I'm doing is simply from clicking a link, and this works great.
Main
However, if I do something like this:
<button class="btn btn-default" ng-click="performLogin()">Login</button>
$scope.performExternalLogin = function () {
DoSomeAuthenticationStuff();
window.location.href = "/#main";
}
This works the first time, but when the user does it a second time, I get an exception from Angular.
I suspect that there's a better way to redirect to a route, but my Googling skills have not come through for me.
I'd appreciate any help.
Here's the exception:
Unhandled exception at line 112, column 381 in http://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js
0x800a139e - JavaScript runtime error: [$rootScope:infdig] http://errors.angularjs.org/1.2.18/$rootScope/infdig?p0=10&p1=%5B%5B%22fn

In Angular you should use the $location service to interract with the window's location:
$scope.performExternalLogin = function () {
DoSomeAuthenticationStuff();
$location.path('/main'); // Will redirect to `#/main`
}

Related

Shopify JavaScript React how to include a local file in the code?

I'm currently making an app for Shopify and I'm stuck with one problem that I can't seem to solve or find any helpful answer from Google.
I need a FrontEnd button to run a script written in JavaScript. This script is located on the server locally in a different folder.
The page is written entirely in JavaScript React and there is no HTML in there.
I tried to import this js file, but it does not allow importing due to some error. Trying to fix this error, an error occurs with the code itself and it stops working adequately. This is why I gave up trying to import the file.
Then I tried to use fetch, but I just can't achieve the result that the page would at least see my file on the server.
FrontEnd button
onClick = {() => {
fetchText ()
}}
At the bottom of the pages / index.js file is this function, which the button calls. The readme.txt file is located in this path: pages / readme.txt
async function fetchText () {
var a = fetch ("/ readme.txt")
.then (promiseResult => {
console.log (promiseResult)
return promiseResult.text ()
})
.then (responseResult => {console.log (responseResult)})
}
Everything that displays in the browser console:
Response {type: "basic", url: "https://ooo.example.com/readme.txt", redirected: false, status: 404, ok: false,…}
All the data about the page is also written at the bottom, but the bottom line is that no matter how I try to write the code itself, it always gives the same 404 error, that is, Not Found

Ajax Error : Uncaught SyntaxError: Unexpected token '<' [duplicate]

I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token : error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:
{"votes":47,"totalvotes":90}
I don't see any problems with it, why would this error occur?
vote.each(function(e){
e.set('send', {
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = JSON.decode(resp);
if (!j) return false;
var restaurant = e.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
});
e.addEvent('submit', function(e){
e.stop();
this.send();
});
});
Seeing red errors
Uncaught SyntaxError: Unexpected token <
in your Chrome developer's console tab is an indication of HTML in the response body.
What you're actually seeing is your browser's reaction to the unexpected top line <!DOCTYPE html> from the server.
Just an FYI for people who might have the same problem -- I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.
This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=? to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"} and getting the error.
This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})
Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:
$ret['foo'] = "bar";
finish();
function finish() {
header("content-type:application/json");
if ($_GET['callback']) {
print $_GET['callback']."(";
}
print json_encode($GLOBALS['ret']);
if ($_GET['callback']) {
print ")";
}
exit;
}
Hopefully that will help someone in the future.
I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:
vote.each(function(element){
element.addEvent('submit', function(e){
e.stop();
new Request.JSON({
url : e.target.action,
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = resp;
if (!j) return false;
var restaurant = element.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
}).send(this);
});
});
If anyone knows why the standard Request object was giving me problems I would love to know.
I thought I'd add my issue and resolution to the list.
I was getting: Uncaught SyntaxError: Unexpected token < and the error was pointing to this line in my ajax success statement:
var total = $.parseJSON(response);
I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.
I found that out by just doing a console.log(response) in order to see what was actually being sent. If it's an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.
When you request your JSON file, server returns JavaScript Content-Type header (text/javascript) instead of JSON (application/json).
According to MooTools docs:
Responses with javascript content-type will be evaluated automatically.
In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:
{"votes":47,"totalvotes":90}
as JavaScript, parser treats { and } as a block scope instead of object notation. It is the same as evaluating following "code":
"votes":47,"totalvotes":90
As you can see, : is totally unexpected there.
The solution is to set correct Content-Type header for the JSON file. If you save it with .json extension, your server should do it by itself.
It sounds like your response is being evaluated somehow. This gives the same error in Chrome:
var resp = '{"votes":47,"totalvotes":90}';
eval(resp);
This is due to the braces '{...}' being interpreted by javascript as a code block and not an object literal as one might expect.
I would look at the JSON.decode() function and see if there is an eval in there.
Similar issue here:
Eval() = Unexpected token : error
This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.
Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.
If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below
<br />
<b>Deprecated</b>: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:\Projects\rwp\demo\en\super\ge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}
Not the <br /> etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start
error_reporting(E_ERROR | E_PARSE);
To view, right click on page, "view source" and then examine complete html to spot this error.
"Uncaught SyntaxError: Unexpected token" error appearance when your data return wrong json format, in some case, you don't know you got wrong json format.
please check it with alert(); function
onSuccess : function(resp){
alert(resp);
}
your message received should be: {"firstName":"John", "lastName":"Doe"}
and then you can use code below
onSuccess : function(resp){
var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp);
}
with out error "Uncaught SyntaxError: Unexpected token"
but if you get wrong json format
ex:
...{"firstName":"John", "lastName":"Doe"}
or
Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}
so that you got wrong json format, please fix it before you JSON.decode or JSON.parse
This happened to because I have a rule setup in my express server to route any 404 back to /# plus whatever the original request was. Allowing the angular router/js to handle the request. If there's no js route to handle that path, a request to /#/whatever is made to the server, which is just a request for /, the entire webpage.
So for example if I wanted to make a request for /correct/somejsfile.js but I miss typed it to /wrong/somejsfile.js the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get
Uncaught SyntaxError: Unexpected token <
So to help find the offending path/request look for 302 requests.
Hope that helps someone.
I had the same problem and it turned out that the Json returned from the server
wasn't valid Json-P. If you don't use the call as a crossdomain call use regular Json.
My mistake was forgetting single/double quotation around url in javascript:
so wrong code was:
window.location = https://google.com;
and correct code:
window.location = "https://google.com";
In my case putting / at the beginning of the src of scripts or href of stylesheets solved the issue.
I got this error because I was missing the type attribute in script tag.
Initially I was using but when I added the type attribute inside the script tag then my issue is resolved
I got a "SyntaxError: Unexpected token I" when I used jQuery.getJSON() to try to de-serialize a floating point value of Infinity, encoded as INF, which is illegal in JSON.
In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller
#RequestMapping(name="/private/updatestatus")
i changed the above mapping to
#RequestMapping("/private/updatestatus")
or
#RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)
For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You'll immediately see the red circle with a cross in it on the failing line. It's a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.
I did Wrong in this
`var fs = require('fs');
var fs.writeFileSync(file, configJSON);`
Already I intialized the fs variable.But again i put var in the second line.This one also gives that kind of error...
For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl (path) I provided couldn't be found. I just had to provide a reachable path and the problem went away.
In my case it was a mistaken url (not existing), so maybe your 'send' in second line should be other...
This error might also mean a missing colon or : in your code.
Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock
xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'\n at eval (<anonymous>)\n at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)\n at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)\n at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)\n at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)\n at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)\n at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)\n at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"
Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.
Try this to ignore this issue:
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
});
Uncaught SyntaxError: Unexpected token }
Chrome gaved me the error for this sample code:
<div class="file-square" onclick="window.location = " ?dir=zzz">
<div class="square-icon"></div>
<div class="square-text">zzz</div>
</div>
and solved it fixing the onclick to be like
... onclick="window.location = '?dir=zzz'" ...
But the error has nothing to do with the problem..

Angular return URL is wrong

In my Angular 5 Application I am doing something like this at
this.returnUrl = this.route.snapshot.queryParams['returnUrl']
I am using this when a user accesses a route but it's not logged in. He is redirected to the login page and after login he should be going back to this return url.
The problem is that http://localhost:4200/schedule?selectedDate=2018-01-29 when accessing this route, the return url becomes:
http://localhost:4200/login?returnUrl=%2Fschedule%3FselectedDate%3D2018-01-29 and after the successful login, the application tries to go to the http://localhost:4200/%2Fschedule%3FselectedDate%3D2018-01-29 URL but that throws a 404 error since it does not recognize the path.
Any idea how can I stop Angular changing my url to this format ? I was assuming that it would pick up the correct URL.
I managed to somehow fix this by instead of using
this.router.navigate(this.returnUrl)
I used
this.router.navigateByUrl(this.returnUrl);
i think You can simply add the url like this <button class="btn btn-md btn-danger pull-right" routerLink="../../">cancel</button>
or else call click event
Use this.
this.returnUrl = decodeURIComponent(this.route.snapshot.queryParams['returnUrl']);

Changing routes doesn't refresh data, gives ng:areq error

In my AngularJS app, I have a route that looks like:
.when('/:project/:page', {
templateUrl: '/ui-editor/editor',
controller: 'EditorCtrl'
})
In a view, I have a link that looks like:
Next page
When I click that link in my app, the URL in the browser changes correctly (e.g. /myproject/1 to /myproject/2), but I get an error Error: [ng:areq] Argument 'scope' is required. The line that the error refers to is the console.log statement in:
socket.on('ws:init-data', function(data) {
console.log('on ws:init-data', data);
// Handle incoming data from server
//...
});
If I refresh my browser, the correct data loads as it should for /myproject/2.
use ng-href is better. It can avoid link be clicked before angular parse.
<a ng-href="/{{currentProjectId}}/{{currentPageId + 1}}">Next page</a>
I don't know the exact cause about this error, but I have a suggestion:
use $location to change your url.
you can see on the dev_guide:
When should I use $location?
Any time your application needs to react to a change in the current URL or if you want to change the current URL in the browser.
http://docs.angularjs.org/guide/dev_guide.services.$location

Troubles using scrapy with javascript __doPostBack method

Trying to automatically grab the search results from a public search, but running into some trouble. The URL is of the form
http://www.website.com/search.aspx?keyword=#&&page=1&sort=Sorting
As I click through the pages, after visiting this page, it changes slightly to
http://www.website.com/search.aspx?keyword=#&&sort=Sorting&page=2
Problem being, if I then try to directly visit the second link without first visiting the first link, I am redirected to the first link. My current attempt at this is defining a long list of start_urls in scrapy.
class websiteSpider(BaseSpider):
name = "website"
allowed_domains = ["website.com"]
baseUrl = "http://www.website.com/search.aspx?keyword=#&&sort=Sorting&page="
start_urls = [(baseUrl+str(i)) for i in range(1,1000)]
Currently this code simply ends up visiting the first page over and over again. I feel like this is probably straightforward, but I don't quite know how to get around this.
UPDATE:
Made some progress investigating this and found that the site updates each page by sending a POST request to the previous page using __doPostBack(arg1, arg2). My question now is how exactly do I mimic this POST request using scrapy. I know how to make a POST request, but not exactly how to pass it the arguments I want.
SECOND UPDATE:
I've been making a lot of progress! I think... I looked through examples and documentation and eventually slapped together this version of what I think should do the trick:
def start_requests(self):
baseUrl = "http://www.website.com/search.aspx?keyword=#&&sort=Sorting&page="
target = 'ctl00$empcnt$ucResults$pagination'
requests = []
for i in range(1, 5):
url = baseUrl + str(i)
argument = str(i+1)
data = {'__EVENTTARGET': target, '__EVENTARGUMENT': argument}
currentPage = FormRequest(url, data)
requests.append(currentPage)
return requests
The idea is that this treats the POST request just like a form and updates accordingly. However, when I actually try to run this I get the following traceback(s) (Condensed for brevity):
2013-03-22 04:03:03-0400 [guru] ERROR: Unhandled error on engine.crawl()
dfd.addCallbacks(request.callback or spider.parse, request.errback)
File "/usr/lib/python2.7/dist-packages/twisted/internet/defer.py", line 280, in addCallbacks
assert callable(callback)
exceptions.AssertionError:
2013-03-22 04:03:03-0400 [-] ERROR: Unhandled error in Deferred:
2013-03-22 04:03:03-0400 [-] Unhandled Error
Traceback (most recent call last):
Failure: scrapy.exceptions.IgnoreRequest: Skipped (request already seen)
Changing question to be more directed at what this post has turned into.
Thoughts?
P.S. When the second errors happen scrapy is unable to cleany shutdown and I have to send a SIGINT twice to get things to actually wrap up.
FormRequest doesn't have a positional argument in the constructor for formdata:
class FormRequest(Request):
def __init__(self, *args, **kwargs):
formdata = kwargs.pop('formdata', None)
so you actually have to say formdata=:
requests.append(FormRequest(url, formdata=data))

Categories