I have a hard coded URL like so:
https://bupacouk.bwa.local.internal.bupa.co.uk/cash-plan-quote/quoteAction.do?getBenefitLevelDetails=getBenefitLevelDetails&productPolicyId=7841#a1
When Javascript is enabled i don't want the hash value on the end so how do i remove it?
When Javascript is disabled it needs to be present.
Thanks.
EDIT
Here is the AJAX jQuery that i am using. So i am pasisng the hard coded URL to the same page on the server and retrieving a table from it:
// Find href of current tab
var $tabValue = $(this).attr('href');
// AJAX new table in
$.ajax({
type: "GET",
cache: false,
url: $(this).attr('href'),
success: function(data){
// Find benefit wrap
$(data).find('.benefitWrap').each(function(){
// get the contents
var $benefitWrap = $(this).html();
// replace contents on page
$('.benefitWrap').replaceWith($('<div class="benefitWrap">' + $benefitWrap + '</div>'));
});
}
});
original
It depends on what the hash value does. If it just moves the document down to #a1, you just need to set scrollTop to 0 after document has been loaded probably.
edit
looking on other stackoverflow questions,
parent.location.hash = ''
should do it, but maybe reloads the page (you have to test it)
Other than that, I advice you to handle it during/before your AJAX calls - i.e.
if (hash != 'a1'){ doAjax(); } //pseudocode obviously.
edit 2 with code based on posted code
Or, if you just need to call AJAX with url without hash, you can delete it in string, that calls the jQuery, no?
var $tabValue = $(this).attr('href');
var $withoutHash = $tabValue.substr(0,$tabValue.indexOf('#'));
we basically get a's href before first #
A simple window.location.hash="" will do it.
This might be helpful to someone asking the same question, how to pull the data following a # in a href.
this.hash.slice(1);
This will give #123 as 123.
Edit: I should probably note, if you're going to be calculating numbers from this data, best to use parseInt(this.hash.slice(1)); or else you'll get funky results.
This works for me. I have added a ! to prevent the page from scrolling up.
window.location.hash="!";
Related
Problem- I have an API that displays a random quote once the page loads. My button(div) called "newQuote" doesn't generate a new quote, instead, it displays the exact same quote, making my button useless.
My code can be found on GitHub here
SO-
I have a javascript function, called getNewQuote() that runs when my page loads. This function grabs a quote and author from an API (https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1), and appends it to my div with the class quoteTitle and quoteDisplay.
function getNewQuote() {
$.ajax({
url: 'https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
jsonp: 'jsonp',
cache: 'false',
success: function(data) {
var post = data.shift();
$("#quoteTitle").empty();
$("#quoteDisplay").empty();
$("#quoteTitle").append(post.title);
$("#quoteDisplay").append(post.content);
}
});
}
getNewQuote();
Then, I set another div called newQuote which, when clicked, would display a new quote.
$('#newQuote').on('click', function(e) {
e.preventDefault();
getNewQuote();
Now, to me, it seems that the problem is caching. The reason that I think it is a cache problem is because if I go to the site on my phone using the app Firefox Focus, which (pretty sure) doesn't store any cache, the site will run as wanted, and will change my quote whenever I click on my #newQuote. You can try it for yourself at 'rqg.ronlaniado.me', where it is hosted.
Since my problem is cache, I did use some methods and plans to avoid this.
cache: 'false',
I set cache-ing to false in my .ajax request.
<script src="qg_js.js?v=42"></script>
I put "?v-42 which, according to Google, shouldn't keep cache stored.
If anyone can look through my code and assist me in solving my issue, that'd be great. Also, this is my first time posting here, so sorry if I am a bit messy with everything.
The error was here:
cache: 'false';
The correct usage is:
cache: false;
These quotes caused cache to be kept, meaning that the quotes didn't change.
My client is tormenting me to be able to go back to a 'previous page' using the browser back button. The thing is that this 'pages' are being called via Ajax to a modal window that displays the content. I'm doing an ajax call and I found that pushState will be my solution, but I really don't get it. I found stuff where there's not even a bit of ajax, it's all javascript.. So, what should I do to add pushState to an ajax call? Is that even possible? Or should I just a find a way to make it work with Ajax?
I found this thing called Pjax but I really don't get it. My ajax call looks something like this;
$(function() {
$('.w-container .w-nav-menu a').click(function() {
var $linkClicked = $(this).attr('href');
var $pageRoot = $linkClicked.replace('#', '');
if (!$(this).hasClass("active")) {
$(".w-container .w-nav-menu a").removeClass("active");
$(this).addClass("active");
$.ajax({
type: "POST",
url: "./PATH/load.php",
data: 'page='+$pageRoot,
dataType: "html",
beforeSend: function(){
$('#canvasloader-container.wrapper').show();
},
complete: function(){
$('#canvasloader-container.wrapper').hide();
},
success: function(msg){
if((msg))
{
$('.content').html(msg);
$('.content').hide().fadeIn();
}
}
});
}
event.preventDefault();
});
I'm sorry if someone else already created something like this, but I didn't find anything useful
You can do a pushState at any stage you'd like in the code you provided, depending on when do you want the history to be manipulated.
You can just do history.pushState([data], [title], [url]); (with appropriate values as parameters) just after a successful ajax form return and before replacing the html content like this:
success: function(msg){
if((msg))
{
history.pushState([data], [title], [url]); // replace with appropriate values as parameters
$('.content').html(msg);
$('.content').hide().fadeIn();
}
}
There might be an issue depending on the UX you've set up, if a user is accessing pages continuously by ajax calls and there are no URLs to reflect the previous page or 'state' in that case, then this solution probably won't work for you.
History manipulation functions like pushState only change the browser history, they don't control what happen when someone clicks the 'back' button.
If there are no pages being loaded with URLs in your setup then you might need to control what happens when a user clicks the 'back' button, by doing another ajax call and loading the previous content (you got to keep track of the changes in content). If that is your scenario, this might help you getting started: https://stackoverflow.com/a/25806609/4283725
The best solution is I think use a javascript component that handles this for you. I use for example Barba.js. Thats a component that used PJAX.
I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.
Edit: Sorry guys, I got the issue, Misspelled class name :(
Hey, I got a quick question for your guys here. I have some anchor tags each of them points to a url of a certain user. The link id is the username. All the links share a css class (.userset). When a user clicks the link I need to issue an Ajax request -using jQuery.ajax method- to a server resource passing in the id of the link. Here's how my code looks like:
JS
$(".columnist_set .img").click(function() {
alert("this.id =" + this.id);
var x = track(this.id);
});
This doesn't seem to work for me! this.id is always undefined.
Yeah, I'm suer I'm missing something, so what am I missing dear SO Gus?
You can try
$(this).attr("id");
You can try this:
$(".userset").click(function() {
var x = track($(this).attr("id"));
});
Edit (I was on the wrong track because of some probably incorrect assumptions)
Try the following:
$(".columnist_set .img").click(function() {
var id = $(this).attr("id");
alert("id =" + id);
var x = track(id);
});
Reading your request i can feel some confusion.
Your request says:
I have some anchor tags
each of them points to a url of a
certain user.
With this sentence you mean you have many <a> in your code, with the href attribute pointing to some user-driven path.
The link id is the username. All the links share a css
class (.userset).
More info, why not. Your tag now should look in my mind like <a class=".userset" id="myUserName" href="./some/url">content</a>
When a user clicks
the link I need to issue an Ajax
request -using jQuery.ajax method- to
a server resource passing in the id of
the link
Let's add the click event:
//all the anchor tags with "userset" class
$('a.userset').click(
function(){
//doing the ajax call
$.ajax({
type: "POST",
url: $(this).attr("href"), //picking the href url from the <a> tag
data: "id=" + $(this).attr("id"), //sanitize if it's a free-inputed-string
success:
function(result) {
alert("I AM THE MAN! Data returned: " + result);
}
}
);
}
);
With that being said, i can't really understand what your javascript code (with references to .img class?) is referring to.
Hope my answer helped a bit though.
The problem is that, I misspelled the class name so the returned wrapped set of my selector is undefined. Thanks for your help all though.
Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")