convert jquery ajax method to javascript - javascript

purpose:When we clicking on a link it opens a new window going to gotopage2.aspx.Please help in understanding the code. what does the data parameter in function() contain? the ajax request settings say that request is synchronous and if success run the function. How is the url parameter being used in this context? How can i write the below function in pure javascript without using jquery/ajax settings?
$.ajax({
url: "page1.aspx?Q=userSess1",
async: false,
success: function(data) {
if(data.substring(0, 1)=="1") {
if(mywindow){
mywindow.focus();
}
else{
mywindow=open('gotopage2.aspx','newwindow home page');
}
}
else {
alert("fail");
}
}
});

If all you want is to open a particular URL in a new window, you don't need any fancy JS. All you need is a hyperlink, with the target attribute set to _blank, like so:
CLick me!
AJAX is used to fetch information from the server and dynamically updating our page without refreshing the entire page and without opening a new window. For example, retrieving some JSON from a WEB API endpoint URL.
The url parameter in your ajax call is used to tell the browser where is should retrieve the data from. This is similar to typing "google.com" in your browser and pressing Enter. "Google.com" becomes the address from where the data is downloaded and displayed in your browser.
There are various alternatives to using $.ajax(). Most browsers nowadays have a function called fetch(), which essentially does the same as $.ajax(). Also, most browsers should support the XMLHttpRequest object which does the same. There are also third party JS libraries that can do AJAX as well, like axios and superagent. But as mentioned, if all you want is to open a new Window with a particular page, an tag should suffice. Hope this helps.

Related

Can I respond with javascript instead of HTML by link?

I have lot of HTML pages containing links to same URL address like this:
Link
The question is: Can I return a javascript response instead of plain HTML that can be executed by clicking on a link?
For example, I tried this in page.php:
header("Location: javascript:alert(1)", true, 302);
but it doesn't work. If I send the HTML page containing the required javascript, then the browser opens a new page or replaces the current page with this blank page containing the JS.
Is there any other method to do this without changing link's href? It seems like it can't because of security restrictions.
No, you cannot invoke JavaScript from the server-side. You can, however, have JavaScript loaded that makes calls to the server and retrieves data.
With that in mind you can have a call to retrieve JSON or XML from the server in which a payload resides that can be extracted by a JavaScript function that is already defined on the client-side.
// note: in this example I use jQuery because their AJAX API is terrific
$.ajax({
url: "http://example.com/page.php?params=1"
})
.done(function( data ) {
// data is our payload
doSomethingWithPayload(data);
});
That way doSomethingWithPayload already is defined on the client, and is called whenever the payload is received.

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.

Open new tab without popup blocker after ajax call on user click

I have a page that enable user to perform image manipulation via HTML5 canvas, on the page, there's a facebook share button for sharing a generated image of the canvas on facebook.
When the link is clicked, an ajax request is sent to the server (ASP.NET MVC) to perform the image generation, save the image on the server, then generate a url(that links to the image) that is returned as the ajax response. The returned url is what I want to pass as the parameter for facebook to share. The issue is that popup blocker is blocking facebook share dialog when I call "window.open".
Is there any other way to open a new tab without popup blocker. I believe that since the user initiated the action, there should be a way for me to bypass popup blocker. Thanks.
Update Oct 2014:
It was noted correctly in the comments, that Firefox has deprecated the synchronous setting in June 2014, but it is still working in this browser.
Furthermore, Chrome received updates which will only allow this to work as wanted if the ajax call returns in less than a second. Which is rather hard to gurantee. I've created another question devoted to the Chrome timeout:
Synchronous Ajax - does Chrome have a timeout on trusted events?
The linked post contains a JSFiddle demonstrating this concept and the problem.
Original Answer
Short answer: Make the ajax request synchronous.
Full answer:
A browser will only open a tab/popup without the popup blocker warning, if the command to open the tab/popup comes from a trusted event. That means: The user has to actively click somewhere to open a popup.
In your case, the user performs a click so you have the trusted event. You do loose that trusted context however, by performing the Ajax request. Your success handler does not have that event any more.
The only way to circumvent this is to perform a synchronous Ajax request which will block your browser while it runs, but will preserve the event context.
In jQuery this should do the trick:
$.ajax({
url: 'http://yourserver/',
data: 'your image',
success: function(){window.open(someUrl);},
async: false
});
Here's how I got round the issue of my async ajax request losing the trusted context:
I opened the popup directly on the users click, directed the url to about:blank and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made
var myWindow = window.open("about:blank",'name','height=500,width=550');
Then, when my request is successful, I open my callback url in the window
function showWindow(win, url) {
win.open(url,'name','height=500,width=550');
}
The answer from wsgeorge is the one that got me on the right track. Here is a function that hopefully illustrates the technique more clearly.
function openNewAjaxTab(url) {
var tabOpen = window.open("about:blank", 'newtab'),
xhr = new XMLHttpRequest();
xhr.open("GET", '/get_url?url=' + encodeURIComponent(url), true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
tabOpen.location = xhr.responseText;
}
}
xhr.send(null);
}

Handling PDF result data from ajax success

I wondered if anyone could suggest an alternative approach to the following work around.
I have a web application that makes an http request for a PDF. The PDF can take more than the default timeout for a request to be created server side, so to better control this, I have used ajax, where as previously just window.open had been used.
However, because of how the PDF is prepared, the request to create it, also returns it. I couldnt work out a way to handle the binary PDF data returned so I simply rellied on the browsers cache to store the data. Then simply requested against the same url again, but using window.open.
The code for this is as follows..
function loadPdf(url, timeout){
$.ajax({
url: url,
success: function(data){
window.open(url);
},
error: function(error, status){
window.alert("Problem retrieving PDF.\nThe error status is: " + status);
},
timeout: timeout,
dataType: "application/pdf"
});
}
Really what I would like to do is handle the success data in a way that asks the user to open/save the PDF. I dont really like to use window.open in this way, especially as a repeat call like this.
Really what I would like to do is handle the success data in a way
that asks the user to open/save the PDF
That's impossible. You should not use AJAX to download files. You can't do anything useful with the byte array that you retrieved in the success callback. You can't directly save it on the client computer (for obvious reasons) and you can't prompt the user with the Save dialog neither.
You don't need to use window.open either. You could simply provide a link to the file:
download pdf
and then on the server specify the: Content-Disposition: attachment; filename="test.pdf" custom HTTP header to show the save dialog allowing the user to specify a location on his computer to store the file.
Would the jquery.fileDownload plugin do what you need?

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