location.href load on the current page/previous url - javascript

i have the following jquery for onclick code :
function find(){
$.ajax({
type: "post",
url: link + 'register/data',
data: {},
success: function () {
window.location.href= "mycontroller/myfunction"
}
});
}
i want to make the url stays on mycontroller/myfunction everytime they click the button, i tried substring lastindexof but it keeps adding more url everytime i click the button, how do i make the button stays on that whenever i click it?
thanks in advance

Let's pretend you're on http://example.com. You redirect the page to "test", so now you're on http://example.com/test. Now you redirect to "test" again. Uh oh, now you're on http://example.com/test/test. Didn't want that to happen, did you? You redirect it just one more time to "other/test". Oh no, now you're on http://example.com/test/test/other/test!
The way to solve this resides in a single bytes. Change test to /test, so it'll always compare to the base URL instead of the current one.
In your JavaScript:
window.location.href = "/mycontroller/myfunction";
However you click it you'll always be on http://example.com/mycontroller/myfunction.

You can change the success function to use window.location.origin like this:
function find(){
$.ajax({
type: "post",
url: link + 'register/data',
data: {},
success: function () {
window.location.href = window.location.origin + "/mycontroller/myfunction"
}
});
}

Related

How to lock / set / block variable inside .on jquery

So, I have a jQuery AJAX call that gets data from the server (some text, some links).
Inside AJAX success callback function I got a .on that is bind to <a> that load for me next page and get me the text of the clicked link (let's say stackoverflow.com).
The problem starts here because in the newly loaded page I got anchors...
After every click on anchor links I got new .text() value.
$.ajax({
url: url,
type: type,
dataType: dataType,
success: function(data){
$('.container').append(data);
$('.container').on('click', 'a', function(e){
e.preventDefault();
var clickLinkName = $(this).text();
console.log(clickLinkName);
$('.container').load($(this).attr('href'));
});
}
});
I would like to know how to lock clickLinkName variable. OR any other way to save only first hit.
I think this would do the trick:
$.ajax({
url: url,
type: type,
dataType: dataType,
success: function(data) {
$(".container").append(data);
var clickLinkName; // Declared here.
$(".container").on("click", "a", function(e) {
e.preventDefault();
// If not initialized, initialize.
if(!clickLinkName) {
clickLinkName = $(this).text();
}
console.log(clickLinkName);
$(".container").load($(this).attr("href"));
});
}
});
That would save only the first value in the variable clickLinkName. This answers your question, but I'm sure there are better ways of doing this.

Jquery Function running multiple times

I am using two scripts on my page and there is a general click function which records the number of clicks one user is making. So when I click on any element in the document, the click function should run after which other functions on the same element runs. But in my case, the click function runs multiple times before passing the control to the other function.
/************ 1st Jquery Script ***************/
function($) {
$(function(e) {
$('.signupCustom').click(function(){
var email = $('#form-email').val()
var password = $('#pass').val()
var firstName= $('#form-first-name').val()
var lastName= $('#form-last-name').val()
var number= $('#form-mobile').val()
var type=$('#sel1').val()
$.ajax({
url: '/login',
type: 'GET',
data: {
'email': email,
'password':password,
'firstName':firstName,
'lastName':lastName,
'number':number,
'type':type
},
success: function(data){
if ($('#sel1').val() == "Travel-Agent"){
window.location.href = "/agentVerification.html"
}
else{
window.location.href = "/dashboardTraveller"
}
}
})
})
$('.login').click(function(){
var email = $('#form-username').val()
var password= $('#form-password').val()
$.ajax({
url: '/loginCustom',
type: 'GET',
data: {
'email': email,
'password':password
},
success: function(data){
window.location.href = data['url']
}
})
})
$('.destinationsButton').click(function(){
var url="/destinations";
window.location=url;
})
}); })(jQuery);
I have attached the link to the html page which contains the second script.
Link to Page
If you go to this link, there is an image:
When I click on Login button, the click function runs multiple times before control goes to other function. I want the click function to run single time and then control should go to other function.
I tried e.stopPropagation but in case of a popup on same page, the popup does not open. Here on clicking on login, popup comes.
Is there any reason you are using the below?
jQuery('*').on("click",function(e){});
I think this might work better
jQuery('body').on("click",function(e){});
good luck
I don't know where you're stuck but you may use one to run the click function just once:
$(selector).one('click',function(){
//code runs only one click
});

HTML API popstate prevent ajax Request

I have a problem with popstate, Basically my code works really well. I perform an AJAX request and pushState. The problem comes up when I hit the back button on the browser. The whole page will request AJAX again. As you know Github is using this method also but when we hit back button it will not request AJAX again. how does Github do that? This is my code :
function loadProducts(dataPage) {
$.ajax({
type: "GET",
url: test.php,
data: {page : dataPage},
dataType: "html",
cache: true,
success: function(checks) {
$(".ajaxpage").html(checks).fadeIn("slow");
}
});
};
window.onpopstate = function(event) {
if (event.state != null) {
var pop = event.state;
loadProducts(pop.dataPage)
document.title = pop.dataPage;
}
};
$('#product').on("click", ".paging a", function(e) {
e.preventDefault();
history.pushState({
dataPage: $(this).attr('href')
}, null, $(this).attr('href'));
loadProducts($(this).attr('href'));
});
i try to remove "loadProducts(pop.dataPage)" but the page did not show previous page that should be. only the URL had change.
What's wrong with my code?

Ajax response change location

I have a function in jquery that submit a form that is working fine, but i need different types of reaction according to the response, sometimes i need to show a message, sometimes reload the window, and other relocate the window
I have a problem with this last part, i dont know how can i detect that is a url, and change the location.
this is my script jquery
function process_form(type_form, id_content_error){
var url = "url.php?form="+tipo_form;
var response= document.getElementById(id_content_error);
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $('#'+type_form).serialize(),
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data;
}
}
});
return false; // Evitar ejecutar el submit del formulario.
};
My php returns 3 types of sentences,
"1": when i need to reload the window.
"messaje": when i need to show something.
"some_url.php":when i need to relocate the window.
sorry for my english, and thanks
I resolve it adding this in the sucsess function
}else if (data.search(/.php/)!=-1){
window.location = data;
}

Can I continue with a previous prevent link?

I have this link:
$('.popup-window').click(function (e) {
e.preventDefault();
$.ajax({
...
})
});
which is a .NET LinkButton (a link that call a javascript, not a real href). I want to prevent Default if ajax return some (let say, false). Else, if true, continue with that link handler.
How can I do it?
P.S. I need that e.preventDefault(); at the beginning, else .NET handler will act immediatly.
You can use the __doPostBack() js function to trigger the postback in your AJAX callback.
The only thing is that you need to pass in the id of the control causing the postback, e.g.
__doPostBack('btnPopup', null);
you can see more on this function in this question: How to use __doPostBack()
I think I understand what you're looking for.
Here's my idea on it: use a data attribute on the DOM element to decide weither default event should be prevented or not. Initially, the event is prevented but the ajax has the power to "unlock?" it, then fire it again. It's a little bit of custom work but it may do the trick:
var $popupWindow=$('popup-window');
// initially "tell" the LinkButton to prevent default
$popupWindow.data('prevent-default', 1);
// the click event (initially prevents default)
$popupWindow.click(function(e){
var $this=$(this);
if ($this.data('prevent-default')==0) { // if "unlocked"
// "lock" it again (default isn't prevented)
$this.data('prevent-default', 1);
} else { // if "locked"
// default is prevented
e.preventDefault();
// test if it should be unlocked
$.ajax({
// ...
}).done(function(data){
if (data.length>0 && data.response==false) {
// set the attribute so it shouldn't prevent default
$this.data('prevent-default', 0);
// trigger this click (should let the event fire completely)
$this.trigger('click');
}
});
}
});
UPDATE:
An alternative could be to add a Page Method.
(See: Using jQuery to directly call ASP.NET AJAX page methods)
This would reduce the mechanics to somethink like this:
$('popup-window').click(function(e){
e.preventDefault();
$.ajax({
// ...
}).done(function(data){
if (data.length>0 && data.response==false) {
$.ajax({
type: "POST",
url: "YourPage.aspx/YourMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
}
});
});
$('.popup-window').click(function (e) {
data = '?sample=1' //serialized data here
callback = function(json){
if(json.returnVar!=true){ //check if returnVar is not true
e.preventDefault(); //prevent redirect if not true
}
};
$.ajax({
type: 'POST',
url: "../ajaxcall.php", //the url to call for ajax here
data: data,
success: callback,
dataType: 'json'
});
});
Try this, let me know if you can't understand the code

Categories

Resources