jQuery AJAX not loading URL with hash - javascript

I have the following AJAX:
$.ajax({
cache: false,
type: 'GET',
url: 'preview.php?url=http://domain.com/Demo/MarsPlaybook/#/view-0',
...
However when I check the console for what was requested, the hash part is binned off...
The console just says: 'preview.php?url=http://domain.com/Demo/MarsPlaybook/'
Any ideas why this is happening? Or how I can stop it?

The hash fragment isn't sent to the server, and you cannot make it be. The hash is purely for the browser to maintain your location within the page.
You'll have to encode it as part of the query string.
The fragment identifier functions differently than the rest of the URI: namely, its processing is exclusively client-side with no participation from the web server
-- http://en.wikipedia.org/wiki/Fragment_identifier

You may want to set the url to: 'preview.php?url=http://domain.com/Demo/MarsPlaybook/?view=0' then on the server/php side direct to 'preview.php?url=http://domain.com/Demo/MarsPlaybook/#/view-0'
However, without knowing a lot about what you're doing, It's hard to say the best answer for you.

Related

How to access web service from Javascript or PHP?

I want to access a web service from here in my web application. When the user chooses a species name, the service will inform if the name is valid, the author and year of the name, etc.
First I thought of using Javascript, since the information comes from the user. Then I saw cross-domain restrictions, so I wonder what is the best workaround here. According to this suggestion, I should be using a server-side workaround. But in that case, wouldn't it be easier to just use php curl functions?
Yes.
If you want to do this reliably, do it from a computer you control.
If you are using PHP already, than cURL is the usual HTTP client library.
That said, using PHP/cURL on your server is the server side workaround to cross-origin JS issues, not an alternative to using a workaround.
Try this ajax code.
$.ajax({
url: 'http://localhost/webservice.php?callback=',
type: "GET/POST",
data:{data:JSON.stringify([{action:'getUserData', userId: 1234}])},
dataType: "jsonp",
crossdomain: true
});
For more details refer this link HTML-PHP Webservice using the AJAX with crossDomain as TRUE.

How to make cross domain ajax call to get plain HTML content

I have a situation where I need to get data from an HTML file existing in another server. It will contain simply plain text content and nothing else. I don't have access to change anything there nor I can get any structured html. What I have is only text content stored in an HTML which is hosted in http://host1.demoserver.com.
Now, from my application which is hosted in http://host2.demoserver.com, I need to get the content through an ajax call. Problem is without implementing CORS. So, upto to my knowledge level I have an option JSONP. But, when I make ajax call with JSONP, I can see the response in Firebug, but it starts throwing javascript exception. There reason that comes into my mind(may be I am not correct) is that, since the content comes as callback parameter it contains undefined variables.
HTML file: copyright-info.html
This is a simple copyright info which needs to be rendered.
And, if we make a call with ajax call:
$.ajax({
url: "http://host1.server.com/static/copyright-info.html?callback=?",
method: "GET",
dataType: "jsonp",
jsonpCallback: "callback",
callback: function(result) {
//code to excute after success
}
});
Then, response would be like:
callback(This is a simple copyright info which needs to be rendered.)
And, as parameter is not in double quotes its not recognizing it and throwing exception.
2nd, this whole thing was working without JSONP, when it was in localhost. And, I guess, http://host1.demoserver.com will be same localhost as it is for http://host2.demoserver.com. But, when it is deployed in server its failing.
Can anyone suggest what's wrong here? Or, any other way for implementing this.
Thanks in advance.

How to send a request from JavaScript without base URL?

I'd like to send a request to a simple URL from my JavaScript, so that the base URL will NOT be added to the request URL. For example, the request should be sent to the following URL (without the base URL):
SAPEVENT:SOME_TEXT?2
I used the jQuery's $.ajax function in order to implement it, but without success.
Here is a JSFiddle for it:
http://jsfiddle.net/txb6tdjj/2/
The JS code:
function sendEvent(id) {
$.ajax("SAPEVENT:SOME_TEXT?" + id);
}
sendEvent(2);
I see the following error in the JS console:
XMLHttpRequest cannot load sapevent:SOME_TEXT?2. Cross origin requests
are only supported for HTTP. (jquery-2.1.0.js:8556)
I even set the parameter crossDomain: true, but it didn't help:
http://jsfiddle.net/auhx2v2v/3/
The JS code:
function sendEvent(id) {
$.ajax({
url: "SAPEVENT:SOME_TEXT?" + id,
crossDomain: true
});
}
sendEvent(2);
It ends up with the same error.
It works correct in the HTML like this:
http://jsfiddle.net/1f6npcn2/2/
The HTML code which works correctly:
<FORM action="SAPEVENT:PRESS_ME">
Click on me to send an event!
<INPUT TYPE="submit" VALUE="Press me to send an event!"/>
</FORM>
But I need to implement it in JavaScript, so that a request parameter can be set dynamically in the URL in JavaScript.
Do you know how to implement it in JS so that the request will be sent to the URL SAPEVENT:SOME_TEXT?2 without the base URL?
Additional information about used browsers: The error is shown only in Chrome. IE and Firefox do not show an error, but they also don't send the request.
Additional information for the SAP guys: I know there is a SAP Note 191908 which states that it's impossible, but a colleague has confirmed that he has successfully tested such functionality in an HTML page which used the same code as I copied above (see the HTML code above and http://jsfiddle.net/1f6npcn2/2/). So the SAP Note is wrong. I know how I can implement this functionality in HTML, but I don't know how I can implement it in JS. That's the problem.
I have no experience of working with SAP but I think you are missing a crucial part here.
In the samples you gave SAPEVENT:CLICK_ON_ME isn't a http url at all but rather it would invoke whatever handles the SAPEVENT-protocol on the local computer with the parameter CLICK_ON_ME. I'm guessing that you have some sort of client installed on your computer that does this for you (how do I create my own URL protocol? (e.g. so://...) contains some more information on how this is accomplished).
The reason your error-message talks about crossdomain-stuff is probably because it tried to interpret it as host:port.
So in other words, since this isn't a http url there isn't a webserver working on the other end so you can't do ajax-requests against it.
The SAPEVENT: stuff is not handled by any web server. The SAP GUI uses an embedded Internet Explorer and registers a custom protocol handler. There is no use in trying to use ajax techniques since you need to reach the container of the client, not the server. To reiterate: You do not want to "send a request" anywhere, you want to convince the browser that a certain local navigation event happened". SAP Note 191908 contains more information on that topic.
No idea about SAP Views, but to me this seems like a usual behaviour on webservers. I presume that SAPEVENT gets parsed by the server during the runtime to a more regular URI. Only the views get parsed, not the resources like CSS and JS, so the SAPEVENT placeholders in the JS file don't get parsed and the JS interpreter will not accept it as a valid URI. One of the common ways of solving this, is to create either a hidden form in the HTML or just a hidden input containing the server-generated values you are needing. For example
SAP View:
<input type="hidden" id="my_event_url" value="SAPEVENT:PRESS_ME">
JS:
function sendEvent(id) {
$.ajax({
url: $('#my_event_url').val() + '?' + id,
crossDomain: true
});
}
sendEvent(2);
I finally implemented it in JavaScript. Thanks go to this web page.
I modified the solution which was shown in this web page in order to add a link instead of a form in JavaScript.
This is the working solution in JS:
var targetUrl = "SAPEVENT:SOME_TEXT?2";
function sendSapEvent(targetUrl) {
var link = document.createElement("a");
link.setAttribute("style", "display:none;");
link.setAttribute("href", targetUrl);
// Move the click function to another variable
// so that it doesn't get overwritten.
link._click_function_ = link.click;
document.body.appendChild(link);
link._click_function_();
}
sendSapEvent(targetUrl);
You can find it also in this JSFiddle: http://jsfiddle.net/708r95p0/6/
It works! It sends a request to the URL sapevent:SOME_TEXT?2
I decided to use a link instead of a form element, bacause I couldn't pass the request parameter using a form.

Delete iframes with broken link jquery

I have this kind of problem, I have iframes with videos embedded into my pages of the website. Note, that iframes urls are from another domain. From time to time these urls can be broken, or stop working and instead of the video there is a message "This video has been removed from public access. ". Is there any way that I can delete those "failed" iframes from the pages by jquery or just javascript.
I was thinking I could be able to search for text inside iframes similar t
$("iframe").each(function() {
var val = $(this).is(':contains("video has been")');
console.log(val); // returns false
});
and then remove those, but it returns false, afa I understood from the http://en.wikipedia.org/wiki/Same-origin_policy.
Also, if it matters, I found out that the difference(without having the above text) between working and broken iframe, is that the last one does not contain object node.
Is there any method to handle this problem ?
Thanks
Due to Same Origin Policy, the browser will prevent all AJAX to different domains and direct access of iframes of different domain. However, there are ways to bypass this limit. One way is to let a server to fetch the data, then return back the data to the client. Here is one plugin for jQuery that does this. It uses YQL (Yahoo Query Language) as a proxy.
Just make a normal GET request with .ajax and the plugin will handle of the details for you:
$.ajax({
url: [url of the iframe],
type: "GET",
success: function(data){
$(data.responseText); //do something with it
}
});
http://jsfiddle.net/DerekL/HGHJ5/
Of course, if you don't trust Yahoo of handling the data, you can always host one yourself.

Get jQuery post redirect response

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");
}
//...

Categories