I want to open a link to a new window without using window.open() from a link retrieving from an ajax call.
I have an hyperlink with href="#". I want to change the href then go to a link from an ajax call when the user click on the link once.
I am not trying to change the link after the event has been consumed.
Here is my code:
<i class="fa fa-eye fa-2x" id="save-btn"></i>
<script>
var lockLink = true;
$("#preview-btn-link").click(function (e) {
if (lockLink) {
lockLink = false;
e.preventDefault();
var a = $(this);
saveProject("true", function (r) {
gvwcProject.id = r;
$.post("ajax_path", {"id": r, "pn": paj.non})
.done(function (r) {
console.log(r);
a.attr("href", r);
a.click();
})
.fail(function () {
console.log("fail");
});
}, function () {
console.log("failed");
});
} else {
lockLink = true;
}
});
</script>
I can see the link from the href has been changed. But it does not call the link back even if I click on the link back.
Well, I just get it work by submiting a form.
<form id="form" method="post" action="the_link" target="_blank">
--some fields --
</form>
js:
$("#preview-btn-link").click(function (e) {
//some check
//Edit the form attributes then submit
$("#form").submit();
return false;
});
Related
Trying to get this Script to open with window.open, any ideas?
<script type="text/javascript">
function get_action(form) {
form.action = 'http://'+document.getElementById("address").value;)
}
</script>
I need to be able to somehow put it after "form.action ="
That function should be the correct way of changing it, however you should make the code run after the form is submitted
window.onload = function () {
const form = document.querySelector("#myForm") // finds element with id of form
form.addEventListener("submit", function (e) {
e.preventDefault() // Stops the form from redirecting
form.action = `http://${document.getElementById("address").value}`
form.submit()
})
}
If you want it to just open in a tab without submitting any form data you can use window.open()
window.onload = function () {
const form = document.querySelector("#myForm") // finds element with id of form
form.addEventListener("submit", function (e) {
e.preventDefault() // Stops the form from redirecting
let url = `http://${document.getElementById("address").value}`
window.open(url)
})
}
And if you want it to open in a new window change the window.open(url) towindow.open(url, "_blank", "location = yes")
I am writing external script to check availability for e-commerce store. When "Add to basket" button is pressed, I'm calling my API and checking if product is available to order. However, I don't know how to undo preventDefault(). When condition is true, event under button should continue and product should be added to basket as without the script.
button.addEventListener('click', (event) => {
event.preventDefault();
fetch(`https://example.com/api.php?part=${partId}`)
.then(function (response) {
return response.json();
})
.then(function (jsonRes) {
console.log(JSON.stringify(jsonRes));
if (jsonRes.part.partFound == true) {
console.log('Found! Processing...');
// REMOVE preventDefault() and process
} else {
console.log('Not found! Aborting...', partId);
}
});
});
If your button is type="submit" change it totype="button"`. This
a) Won't submit the form
b) Means that you don't have to use preventDefault to prevent the form from submitting
That simply means you're left to decide how you want the data to be submitted, and you can either do that with another AJAX call to an API endpoint, or by submitting the whole form to the server - whichever is your setup.
// Grab the form and button, and add an event
// listener to the button
const form = document.querySelector('form');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
// Fake API call
function fakeAPI() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`API called!`)
}, 2000);
});
}
function handleClick() {
console.log('Clicked');
fakeAPI(2000).then(data => {
// If partfound submit the form data
// Either another fetch call to post the data,
// or `form.submit()` to post the whole form instead
});
}
<form>
<button type="button">
Click
</button>
</form>
you can try something like code below:
async function apiCall(onSuccess, onError) {
fetch(`https://example.com/api.php?part=${partId}`)
.then(function (response) {
return response.json();
})
.then(function (jsonRes) {
console.log(JSON.stringify(jsonRes));
if (jsonRes.part.partFound == true) {
console.log('Found! Processing...');
onSuccess(jsonRes);
} else {
console.log('Not found! Aborting...', partId);
onError();
}
});
}
button.addEventListener('click', (event) => {
// show loading or something
apiCall(function (response) {
// success
}, function () {
// error
});
});
I am using following code to trigger the are you sure leaving website alert but for some reason its not recognising my if else condition in it and only works if I only put return true in window.onbeforeunload = function() { return true } . Is there a way I can trigger this alert only when user is navigating away from my website cause at the moment without if else condition its asking if user tries to navigate in the same website as well?
window.onbeforeunload = function() {
var location = window.document.activeElement.href;
if (typeof location != 'undefined')
{
console.log(location);
} else { reutn true; }
};
You can set a flag and toggle that flagged based on host of links that are clicked
var host = location.hostname,
allowNavigate = false;
window.onbeforeunload = function() {
if (!allowNavigate) {
return 'Message string';// not what actually gets displayed in most browsers these days
}
//don't return anything
return;
};
window.onload = function() {
document.querySelectorAll('a').forEach(function(a) {
a.addEventListener('click', function(e) {
allowNavigate = this.hostname === host;
});
});
};
The hostname on this page for example is "stackoverflow.com"
DEMO
You can add the "window.onbeforeunload" dynamically for the links you want to see the prompt message
and remove the "window.onbeforeunload" for the links you don't want prompt
<a onClick="a(true)" href="https://www.w3schools.com">Click here to get promt before navigate</a>
<br>
<a onClick="a(false)" href="https://jsfiddle.net/">Click here to navigate without promt </a>
<script>
function a(showPrompt){
window.onbeforeunload = showPrompt ? function(e) {return '';}: null;
}
</script>
https://jsfiddle.net/vqsnmamy/1/
I've got a button:
<button type="button" class="btn btn-primary mt15 send-emails" name="SendEmails" value="true">Send Emails</button>
And a method:
$('.send-emails').click(function (e) {
// build data and other stuff
$.post('/leads/sendemails', data, function (data, status, xhr) {
alert('Emails have successfully been queued for sending.');
window.onbeforeunload = null;
window.location.href = '/Leads/Lead/' + #Model.LeadID;
}, 'json');
});
Even with window.onbeforeunload = null; I still get the popup warning:
How can I prevent this?
The solution is following:
$(window).unbind();
This will remove the onbeforeunload event just before redirect the browser to a new page using location.href.
Use a global variable to check before redirecting to the page like this. Have a string variable to hold href which you need to redirect and redirect it before statement
(function($){
var dontSubmit = false,
$form = $('form#my-form');
// Prevent the trigger a false submission on link click
window.addEventListener("beforeunload", function (e) {
dontSubmit = true;
$form.trigger('submit');
});
$form.on('submit', function(event){
if (dontSubmit) {
event.preventDefault();
return;
}
// Continue on as normal
});
})(jQuery);
I am putting a modal alert on the screen when a user clicks a choice of a dropdown like this:
$(document).ready(function(){
$('#id_state').change(function(e){
var selection = $("#id_state").val();
if(selection == 1){
event.preventDefault();
var entryType = 'diabetes';
var data = new Object();
data.entryType = entryType;
programAlertModal(programAlertModalCallback, data);
return false;
}
});
$('#id_state').trigger('change');
});
Program alert modal is then called here:
programAlertModal:function(callback, data){
var entryType = data.entryType;
var url = '/shared/enrollment/'+entryType+'/';
$.get(url, function(result) {
callback(result, entryType);
return false;
});
},
programAlertModalCallback:function(result, entryType){
$( "body" ).append(result);
},
The result is some html that looks like this:
<div class="takeover">
<div class="takeover-bg"></div>
<div class="takeover-body">
{% if entry_type == 'diabetes' %}
<h1>My awesome title</h1>
Dismiss
</div>
</div>
How can I dismiss what is loaded without reloading the page (and clearing the dropdown selection)?
Add a class to the Dismiss link so we can reference it:
Dismiss
Then bind a handler that removes the modal in the callback:
programAlertModalCallback: function(result, entryType) {
var $result = $(result).appendTo("body");
$result.find("a.dismiss").on("click", function(e) {
e.preventDefault();
$result.remove();
});
},
Pass an e parameter to your function and add e.preventDefault(); to prevent the default behaviour of the a tag that reloads the page. You should also include href="#" in your a since leaving it blank causes some trouble in some cases.