window.open("index.php"); does not open the new page in the same tab, it opens it in a new tab.
I tried window.open("index.php",'_self') as well which does not open the tab at all.
Here is my code :
$.ajax({
url: "login.php",
type: 'POST',
data : "username="+name+"&password="+pwd ,
datatype :"text",
async: false,
cache: true,
timeout: 30000,
error: function() {
return true;
},
success: function(msg) {
if(msg == "Validated")
{
alert(msg);
window.open("index.php");
}
if(msg=="Incorrect password")
{
alert(msg);
location.reload();
}
}
});
Instead of window.open you should use window.location = "http://...."
The window.open function opens a new window(or tab). The window.location changes the url the current tab.
window.location is the function/property you should look at.
window.open will open in new tab if action is synchronous and invoked by user. If you remove async: false from ajax options (and this method is invoked by user for example by clicking a button), then new window will open instead of new tab. For simple navigation set window.location.href
As far as I know, window.location doesn't do this. The right method to do this is:
document.location = 'url-you-want-to-open.ext';
Best thing is to either include the full path (if it's on a different domain) or the absolute path if it's on the same domain. Only use relative path if the destination document is in the same folder.
To add to this:
window = speaks to the browser and its tabs
document = speaks to the current document that's loaded in the browser / tab.
Related
I am trying to post some data on facebook after getting a response from the server side.
Example :
function share_to_facebook(url){
$.ajax({
type: "POST",
url: "/create_data",
data: data,
success: function(result) {
if(result.success=="success"){
// url contains the facebook url with some required parameters.
window.open(url, '_blank');
}
}
});
}
After executing this method, Getting following message-
"Browser(browser name) prevented this site from opening a pop-up window"
How to open facebook page without getting this errors?
Popup blockers in modern browsers in default settings only let popups go through if they were opened directly on user interaction (most often a click.)
But inside the callback function of an async AJAX call, that “direct” connection is lost. The browser sees no connection to the previous user interaction any more, therefor thinks it is an “automated” popup the user did not ask for - and so it gets blocked.
You could try and open the popup window before your AJAX request, with an empty page/about:blank as URL (assuming share_to_facebook gets called directly on user interaction), and then in your callback you just assign a new URL to the popup window.
function share_to_facebook(url){
var myPopup = window.open('about:blank', '_blank');
$.ajax({
// ...
success: function(result) {
if(result.success=="success"){
// url contains the facebook url with some required parameters.
myPopup.location.href = url;
}
}
});
}
Here's my code:
$rootScope.http({
url: myUrl,
method: "POST",
data: "",
}).success(function (data) {
alert(data.uri); //for test, and I see correct uri shows up here.
window.open(data.uri, ''); return false; //window doesn't open.
});
The window.open doesn't work inside the .success, but it does work outside the http post method. Something is wrong when comes to callback function. I met very same issue in $.ajax and fixed it. But same solution doesn't work here for angular.
We faced the similar problem before and the reason is simple; in the most of the modern browsers, browsers will not allow the window.open() call which are not the direct result of user activity.
Here, your window.open() is being triggered in an asynchronous call which is not being called by a user action, for example: clicking on a link or a button.
You can fix this problem by disabling the popup blocker but we have to notify the user that their popup blocker is enabled. For that, you can do something like this:
$rootScope.http({
url: myUrl,
method: "POST",
data: "",
}).success(function (data) {
$rootScope.popupWindow = window.open(data.uri, '');
$timeout(function() {
// Check if popup blocker is enabled by verifying the height of the new poup
if (!$rootScope.popupWindow || $rootScope.popupWindow.outerHeight === 0) {
alert("Please disable the popup blocker");
}
}, 1000);
});
(Note: I've tested this is a browser, not sure in the mobile but this should work)
I am trying very hard to implement history.js a jQuery plugin for IE 8 and 9. The demo seems to be fine in IE10+ and other modern browsers but I'm not able to understand the problem below for IE<=9. The demo is a asp.net mvc5 application where I want to provide a single page user experience where I'm just loading partial views and performing a post action via ajax. All the views load in a #shell div in my master view. May be I am missing something!!
My demo app starts with http://localhost:1089/ which is the first request that renders a login page. Any other pushState() causes a change in the url with appending #Home/About?ref=one.
Following is my script that is executed in layout.cshtml which is loaded only once:
(function (window, undefined) {
History.Adapter.bind(window, 'statechange', function () {
var state = History.getState();
if (state.data.options == undefined) {
alert("options is undefined");
var options = {
url: state.url,
type: "GET",
dataType: "html"
};
GetPartial(options);
} else {
GetPartial(state.data.options);
}
});
})(window);
$(document).on('click', 'a', function (e) {
e.preventDefault();
var options = {
url: $(this).prop('href'),
type: "GET",
dataType: "html"
};
History.pushState({ options: options }, $(this).text(), $(this).prop('href'));
});
function GetPartial(options) {
if (options) {
$.ajax({
url: options.url,
type: options.type || 'GET',
dataType: options.datatype || 'html',
async: true,
data: options.dataToPost,
beforeSend: function() {
$("#loaderMain").show();
},
complete: function() {
$("#loaderMain").hide();
},
cache: false,
}).success(function(response, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
// returned result is of type html, so act accordingly
if (options.selector == undefined) {
InjectContentToShell(response);
} else {
$(options.selector).empty().append(response);
}
} else if (ct.indexOf('json') > -1) {
// returned result is of type json, so act accordingly
}
}).fail(function(e) {
console.log(e);
});
}
}
function InjectContentToShell(content) {
$('#shell').fadeOut(100, function () {
$(this).empty().append(content);
}).fadeIn(100);
}
When I render this first page, I add one entry to History by pushState method like this:
$('#submit').on('click', function (e) {
e.preventDefault();
var formInstance = $(this).closest('form'),
dataToPost = formInstance.serialize();
var options = {
url: formInstance.prop('action'),
type: formInstance.prop('method'),
dataType: "html",
dataToPost: dataToPost
};
History.pushState({ options: options }, "Home - All Summary Views", "/Home/Index");
});
Pushing the state above, changes the url to http://localhost:1089/#Home/Index in html4 browser which is fine. I am able to go back and forward. This works well.
Now when I refresh the page in html4 browsers, the request sent to server is for first url i.e. http://localhost:1089/ which bring the first view to the client. So, the user can see the first page i.e. login screen. And then statechange event is fired and the state url still remembers the last url where page was refreshed and a new request is made for this url to server. The response is then injected in shell.
So, the problem is - on page refresh, user is getting two views instantly - the initial page where the user started his browsing session and soon the second page is loaded from the server and added to shell via animation as when the statechange event is fired, the History.getState() still remembers the last url.
I don't want to show this initial page on page refresh. If this is solved, then everything works fine with this history.js I think!
The above problem is also mentioned as a concept of bookmarking in the this article. Refer to the first figure and the text written above it.
My demo application works fine in html5 browsers as on every History.pushState() the browser's url is changed to the url I have specified. And when page is refreshed, the request is sent to the server as per that url and not with the first url in the browsing session started.
After trying many things, I have come up with the following solution to avoid showing the first view i.e. login page to the users with html4 browser:
I have created a view "Index" that is the first view being rendered. Which doesn't have any html content but has this script:
<script>
$(function () {
if (History.getCurrentIndex() == 0) {
var options = {
url: "/Account/Login",
type: "GET",
dataType: "html"
};
History.pushState({ options: options }, "Login Page", "/Account/Login");
}
});
</script>
The above code checks if the current index is 0 or not. If it is 0, then it means that user has just started his browsing history and it should give a login screen. If it is not 0, then it means that user was on some other step of user journey within the application which does nothing. And once this view is rendered the statechange event is fired which already has the information about the url of the page where user requested for refresh. As per the logic of statechange event handler above in my question, that resource is requested from the server and injected in the #shell container.
The above solution is working very well and gives the same experience to user as if they are on html5 browser. The above code works for me but will be glad to know if someone has any other solution.
Very new to code in general so apologies in advance if i dont explain myself properly,
But I have a form, that actions a piece of JavaScript on submit.
If the form validates successfully then it calls a php file for server side processing.
Once the server side processing is complete the php file returns some data (a url) which the user is then redirected to (client side)
This all works fine on desktop (chrome, IE, FF) and via modern mobile devices, however the redirect is not working on some devices (blackberry for one), and a i assume other older devices. Instead of the redirect URL going straight into the address bar, it is being placed after the url of the original page - as such causing the user to be redirected to a page that of course doesnt exist.
Below is the script that is called on submit. Again apologies if none of the above makes sense...I am very new to all this:
$(function () {
$('#wait').hide();
$('form#leads_form').on('submit', function (e) {
if (validateFrm()) {
$(":submit", this).attr("disabled", true);
$('#wait').show();
var jqxhr = $.ajax({
type: 'post',
timeout: 300000,
url: 'sell-save-leads.php',
cache: false,
data: $('form').serialize(),
success: function (data) {
//alert("Submit success: " + data);
window.top.location.href = data;
}
});
} else {
//alert("validation errors");
$('#wait').hide();
}
e.preventDefault();
});
});
If anyone is able to help or offer some advice that would be great.
As your form is located in an iFrame I suggest you to use this jQuery plugin to send messages from an iframe to its parent:
http://benalman.com/projects/jquery-postmessage-plugin/
With this you could send a message from inside your success function, containing the new url, and catch it in the parent window.
You can also use
window.top.location.assign(data);
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window.location
I am trying to open a link in a new tab on ajax success, but the link opens in a new window. How to forcefully open the link in a tab rather than in a new window in chrome with jquery or javascript.
Code:
$("#A1").click(function (event) {
$.ajax({
type: "POST",
url: "Home.aspx/btnTestProject",
data: "{'preview':'" + inventory + "' }",
contentType: "application/json; charset=utf-8",
datatype: "json",
cache: false,
success: function (response) {
window.open("TestnRun.aspx"); //opens in new window
}
});
window.open("TestnRun.aspx"); //opens in new tab
});
In general you cannot control it. As this is user preference to open link with target="_blank" in new window or tab.
When browsers starts supporting css-3 completely then you will be having an option in future:
http://www.w3.org/TR/2004/WD-css3-hyperlinks-20040224/#target-new
You can use this:
#anchorId { target-new: tab ! important }
I saw the same thing.
And I've noted that (I'm using jquery.1.9.1):
if you call $.ajax in async, or % the browser (Chrome) open in NEW WINDOW, else if you run a JSON call SYNC the window will be open tabbed!
This open in a NEW WINDOW, pop-up:
$.ajax({ url: "/cliFindExist/",
async: true,
function(data){...
window.open("some.aspx","_blank")});
This open window TABBED
$.ajax({ url: "/cliFindExist/",
async: false, // <<<<<<<<<<<<< NOTE
function(data){...
window.open("some.aspx","_blank")});
JQuery may be change the way/context when it call the function? depending if it run a sync or an async call.
Use target "_blank" like this
My link
or with Javascript like this
<button onclick="window.open('http://www.google.it','_blank')">Button</button>