I'm using some simple AJAX page transition on a Craft CMS site, very similar to these instructions: https://designbycosmic.com/journal/craft-cms-ajax-page-transitions-with-history-pushstate
The basic structure of my code is this:
$.ajax({
type: 'POST',
url: href,
data: {},
success: function(result){
// hide old content, load new content, fade in new content
},
error: function(){
console.log("ajax error");
}
});
"href" is the link to new page to load.
I'm always getting a 400 (Bad Request) error.
I'm using this exact same method for a similar site on the exact same hosting environment and it works fine, so I'm banging my head as to why this would be acting differently.
All of the other answers on this subject seem to be for when "data" is not formatted correctly, but none address the issue when you're simply loading a URL, with no other data.
In this case, what would cause a 400 error?
UPDATE
OK here's the live site for anyone who is kind enough to help further investigate: http://mearch.nz/
Still very incomplete and under development. You should be able to navigate between Home, Projects, and and then any project detail page linked from the Projects index. You'll see that the loading indicator just gets stuck there and the new page never arrives because the AJAX fails.
If you reload any of those pages they work fine. Nothing wrong with the URL. For some reason it's just not accepted as proper data for the AJAX POST.
Now for comparison, here's another website on the same web host, using the same AJAX functions, and same CMS, and it works fine: http://benek.nz/
http:// mearch.nz/projects/ does not reference http:// mearch.nz/js/init.js. But init.js needs to be loaded since it contains your javascript-code!
In contrast http://benek.nz does reference init.js and therefore it works.
Looks like you use minmee on http:// mearch.nz and therefore it is a bit difficult to debug your issue.
It seems that your request has an CSRF-issue. This normally happens if javascript sends a request to a web-server, which is different to where the javascript comes from.
This is what I did to reproduce your issue:
navigated to http://mearch.nz/projects/
clicked on link "projects"
In Google Chrome: the console window writes "... 400 (Bad Request)"
In Google Chrome in the network tab under response I see the server also sent HTML containin text "Bad Request" and "The CSRF token could not be verified."
Related
so I made a Chrome extension whose whole purpose is fetching certain data from the backend and process it to do stuff on a certain domain that the user visits.
I'm trying to have it published but it's getting rejected, and this is what they told me:
Your item was found to have requested/fetched one or more external scripts. An example of one such instance in your item was backend URL in background.js. Please remove all external fetches including Json type.
(This is actually the last of 3 emails they sent me, they just added a few more words in this part I quoted with every email... Since they send only one per day, it's very frustrating...)
I use jQuery.ajax in my background script, and after searching with google I found out that by default it tries to process json requests as jsonp requests (I'm not 100% sure though...), so I've set the jsonp property to false in every ajax call in my code. My extension still got rejected today, and they didn't send another email, so I'm just gonna guess they really did mean that I need to remove that call that fetches json from my backend.
Here's an example of an ajax call in my code:
$.ajax({
url: backendUrl + '/theendpoint',
data: {
paramName: 'paramValue'
},
dataType: 'json',
cache: false,
jsonp: false
})
I'm pretty sure that I'm supposed to be allowed to do it. I've also searched to make sure, and other people do it too. So, what could actually be wrong?
I know it's hard by seeing hardly any code, but there's too much of it and the problem is just here in the ajax calls. And I can't post here the content of my manifest file.
I did add my backend to the permissions in the manifest. Do I have to add it to the content_security_policy too, even though I'm just fetching json from it, and not scripts?
Thanks for any help.
Edit: side question: is it mandatory to provide a physical adress and a link to a privacy policy in my developer account? If yes, could that be the reason why the extension keeps getting rejected? (Last time it got rejected, they didn't even send me an email)
(I'm not sure if I should post this as an answer, but)
Today I tried insisting again saying that json isn't a script and that I was supposed to be able to fetch it from my backend. I don't know if it was a coincidence but right after sending the email, I received another one saying this:
Thank you for reaching out to us.
Upon a subsequent review, we’ve reinstated your item and it will be available in the Chrome Web Store within 30 minutes.
Thank you for your cooperation,
Chrome Web Store team
I also must add that I did use this support form to ask for help. Maybe that's what actually did something.
Moral of the story: if your extension is getting mistakenly rejected, keep insisting and explain what you did and why it's valid...
Now, I've only gotta understand why it got immediately taken down from the store...
Edit: My extension was also taken down by mistake, they reinstated it after I used the support form to ask for the reason. So yeah, use that support form, it actually gets things done.
I am trying to load the HTML content of a webpage outside of my domain, which I can do just fine using functionality provided by this jQuery plugin: http://www.ajax-cross-origin.com/. However, when I print out the HTML there are pieces missing, which I assume is because the ajax request gets the HTML before the page is fully loaded. When I say "pieces missing," I mean that some tags that should have innerHTML in fact have none. Here's my code:
$.ajax({
crossOrigin: true,
url: "http://siriusxm.com/bpm",
success: function(data) {
console.log(data);
},
timeout: 5000
});
The crossOrigin attribute is from the plugin I mentioned. I get the same behavior with and without the timeout (and strangely, it doesn't seem as though the timeout is doing anything at all--when I check the console, it logs data pretty much immediately).
Is there a way to wait until the page is fully loaded before getting the content? For what it's worth, this is all part of a chrome extension I'm developing, so if there's anything else code-wise you might need just ask.
Thanks!
So according to your comments, the information you're looking for is just the Now Playing artist and Song, which you won't be able to get by loading just the source of the main page.
To find the data you're looking for just open up your Chrome DevTools, go to the network tab, and Refresh to see all requests on the page.
It looks like this is the request you want, you just need to update the timestamp every minute:
http://www.siriusxm.com/metadata/pdt/en-us/json/channels/thebeat/timestamp/08-12-03:48:00
Just parse that json and grab what you need. Of course they can always change the location or format of the file, but for right now that's what it is.
If the console log is showing all of the data you're looking for then the ajax call should be fine.
Any code in the success callback will be ran after the ajax call, so just use JQuery in the success callback function to insert data into the html. All I see there now is the console.log(data) unless you've removed some code.
The timeout just gives the ajax call a set amount of time to complete before it "times out", in other words it tells it to stop waiting after the set amount of time.
I have created a web site where in one page I select search criteria for mysql.
Depending on the drop-down elements selected, I create a string that I call myquery in a javascript, then I use
window.location.href = "queryMySQL.php?query=" + myquery;
and call a different page.
This works sometimes, but sometimes it gives me the 403 error and the page shows:
You don't have permission to access queryMySQL.php on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
I cannot figure out why it works sometimes and sometimes it does not, the syntax of the query is not a problem, I can get this error even if I remove the code on the page.
Additionally, this worked fine on another web hosting site, but when I copied this implementation on a different site I started having problems.
Suggestions?
EDIT ******************************************************
As I said this has nothing to do with the query. The target page can be a blank html page, and the error is still there. It looks like some security issue on this web hosting site because it worked fine on the other one and on my own server.
Try:
window.location.href = "queryMySQL.php?query=" + encodeURIComponent(myquery);
The query probably contains special characters that need to be encoded in a URL.
Recently I started facing issue with one of my scripts that loads a json response from the server. I am using jquery.ajax() to make an ajax call. The code snippet is so -
var request = $.ajax({
url: "script.jsp",
type: "POST",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response, error) {
console.log(response, error);
}
});
As I mentioned this script worked as recent as yesterday. I have not made any changes to either the server-side code or the front-end code. The json response is a bit large ~1 MB in size. But I validated the json output using -
python -mjson.tool < output.json
It prints out properly. Curious thing is FF & Chrome handle it differently.
In FF, I open firebug and see the ajax request being made. I see that the request is served in around 300ms but the loading wheel next to the link in the console is still animating for aorund 20 seconds. And after that the json response is properly processed and the result can be seen on the page. In IE also similar behavior, proper processing of the json after 20 seconds.
In Chrome, nothing happens for around 20 seconds after which I see an error in the console saying either "error": undefined or Failed to load resource. Alternatively it also prints the below stacktrace -
POST script.jsp
f.support.ajax.f.ajaxTransport.sendjquery.min.js:4
f.extend.ajaxjquery.min.js:4
DataTableWidget.extend._fetchBuildingBlockItemsPermissionBBItemsWidget.js:91
(anonymous function)PermissionBBItemsWidget.js:83
e.extend.eachjquery.min.js:2
DataTableWidget.extend._loadDataPermissionBBItemsWidget.js:82
DataTableWidget.extend.showPermissionBBItemsWidget.js:15
(anonymous function)permission-building-blocks.html:451
xLAB.min.js:5
ULAB.min.js:5
jLAB.min.js:5
ILAB.min.js:5
eLAB.min.js:5
a.onload.a.onreadystatechange
I dont understand this weird behavior in different browsers.
So in essence I made sure that -
Server side code returns the response fast. I put in some debug statements and saw the server log. None of the response form server take more than 500ms.
Made sure than json is properly validated. The fact that after 20 secs it is processed in both IE & FF without any issues is a proof of that. In addition to use of python's json.tool.
Set the dataType to json
So any pointers on the issue will be a great help. Thanks.
UPDATE
One more curious thing I noticed. While the request is being processed and I hit the refresh button even within 3 seconds of the original request, the process immediately completes. As in I see changes in the view of course fraction of a second later the page is wiped out due to refresh event.
UPDATE 2
I have noticed that after I slice up my big response by alphabets. The issue of looong response happens in only certain responses. I ran this split long response files through http://jsonformatter.curiousconcept.com/#jsonformatter and although it immediately returns saying that the josn is valid, it takes 20+ seconds to actually pretty print the response. I think the problem is happening due to certain characters like \u0026 so with this added info, how to resolve the problem? Here is the snipet of the problematic json.
I figured out the problem. The issue was with how the server-side code provided the client-side code JavaScript with the json string.
I was using a legacy method in our code base which actually rendered the already json string in a jsp page before passing it to the client. This was somehow screwing up the response. Also response type was text/html because of this.
As soon as I switched the response to be of actual application/json MIME type stream, everything was fine.
does your JSON have line feeds? Do you have Firebug or something line that open? The browser may be loading the JSON just fine, it might be your debugging tools crapping out. I Recall having issues before with inspecting certain JSON strings with certain tools just because it didn't have line feeds (or line feeds as understood in Windows). I'm wondering if the fact your logging the whole thing to the console doesn't have something to do with it.
I've written some HTML/Javascript that sits on a third-party server for security reasons. This page performs a javascript post to another page on the same site. However, instead of responding with useful data, it instead wants to perform a redirect (if you would post via a normal HTML form to this page, it would redirect your browser). How can I process this process? I basically want to be able to extract the url's query parameters that it is trying to redirect with (and then put this link into a hidden form field).
Here is my basic ajax post...
$.ajax({
url: '/someurl/idontcontrol',
data: serialized_form_data,
async: false,
type: 'POST',
success: function(data, textStatus, x) {
alert(x);
alert(x.getAllResponseHeaders());
return false;
$('#redirect_link').val(WHAT_DO_I_PUT_HERE);
}
});
Note that the URL I am posting to is not one that I control, so I have no power over what it returns.
UPDATE: When I use the above alerts, I receive "[object XMLHttpRequest]" and "null". I'm monitoring the headers with a Firefox plugin and they seem be coming back as expected, but I can't seem to access them via javascript (I've also tried x.getResponseHeader('Location'), but that and all other calls to getResponseHeader return empty).
ALSO: I don't know if it matters, but the status code is 302 (as opposed to 301 or 303).
Thanks!
According to the jQuery Documentation the success method can take a third argument which is the XMLHttpRequest object.
According to Mozilla's XMLHttpRequest page, this object should have a "status" property. If you check the value of this property, and it is a redirect code, such as 301 (permanent redirect) or 303 (temporary redirect) it is known the processing page is trying to perform a redirect. The "statusText" property should be able to be used to determine the location it is trying to redirect you to.
If you know it is trying to redirect, you can then re-post the data through Ajax to the new URL.
The strange thing is though, when researching this, stumbled across this page that indicates the XMLHttpRequest object should follow redirects (see the comments). So it seems like this would be a non-issue.
Unless the processing page is using an HTML meta redirect (like below) to do the redirection. In that case, I'm not sure what could be done - maybe try to parse the returned HTML for meta tags and see if any of them are attempting a redirect.
<meta http-equiv="refresh" content="0;url=http://www.example.com/some-redirected-page">
You can't get the full HTTP headers from an AJAX call in JQUery, so you can't process the redirect in this way.
However with a raw javascript request you do have access to the XMLHttpRequest getAllResponseHeaders() method which will allow you to process the redirect (this function for single headers).
Sorry, not directly an answer to your question, but I'm sure it's possible with jQuery too as it's quite simple with Prototype.
// Warning: this is Prototype, not jQuery ;-)
//...
onComplete: function(response) {
var refresh = response.getResponseHeader("Refresh");
var whatever = response.getResponseHeader("Whatever");
}
//...