Reputation: 1582
This might be easy but I'm having trouble doing this right. How can I open a new page in the same window using jquery-ajax response?
As you can see I'm trying to display a custom text if the php response is equal to the word "invalid". If not open a new html page in the same window.
$("#lBtn").click(function(){
$.post("php/session.php",
{ username:$("#username").val(),
password:$("#password").val()
},
function(response) {
alert(response)
if(response == "invalid"){
$("#loginResponse").text("Error!!");
} else {
window.location = $(this).find('new/pahe.html').html();
}
});
});
Alert(response) shows the word "invalid" but the if statement does not work. Means neither it display Error!!
in $("#loginResponse")
nor it opens the new page. That's what I want to fix.
Upvotes: 0
Views: 1766
Reputation: 93561
You are probably getting additional white-space returned in the output from the post (maybe a carriage return or space?).
Trim the response:
function(response) {
response = $.trim(response);
if(response == "invalid"){
or just do this to check for a sub-string match:
function(response) {
if(response.indexOf("invalid")>=0){
Upvotes: 1
Reputation: 31924
EDIT: You did not word your question right. What you are aiming to do is to redirect to another page.
If #lBtn
's html is the url itself, the solution to that is to use:
window.location.href = $(this).html();
This is for opening the link in a new tab
First create a new link, hidden somewhere:
Javascript code
$('body').append('<a id="new_wnd_temp" href="another_page.html" target="_blank" style="display:none"></a>');
Then trigger a click event on it:
Javascript code
$('#new_wnd_temp').trigger('click').remove();
In your example, it would look like this:
Javascript code
$("#lBtn").click(function() {
$.post("php/session.php", {
username:$("#username").val(),
password:$("#password").val()
},
function(response) {
alert(response);
if(response == "invalid") {
$("#loginResponse").text("Error!!");
} else {
$('body').append('<a id="new_wnd_temp" href="another_page.html" target="_blank" style="display:none"></a>');
setTimeout(function () {
$('#new_wnd_temp').trigger('click').remove();
}, 0);
}
});
});
Upvotes: 1