I know there are already several questions about the best way to do a Flask URL_for through Javascript, but I can't get it to work for me. I am new to Front End development so go easy on me here. I have tried multiple ways, and each way returns an error or a different problem.
I have a Bootstrap dropdown menu that when clicked on, should return a report to the user. I thought I had it solved earlier because I can get it to return the report if I do it this way:
$('.dropdown-item').on('click', function (event) {
branch = $(this).attr('branch');
selected_date = selected_date;
window.location.href = route_summ/branch/selected_date
The problem is then that it adds the route_summ in front of every other file, including javascript, css, etc files, so none of those can be found any longer. If instead I do:
window.location.href = "{{url_for('route_summ', branch=branch, selected_date = selected_date)}}"
As I have seen in other posts people suggest, it doesn't look at any of the variables and instead just tries going to route_summ//.
Some posts talk about using an $.ajax call, so I have done it this way:
$.ajax({
type: 'GET',
url: "/route_summ/" + $(this).attr('branch') + '/' + selected_date,
data: {
branch: $(this).attr('branch')
},
method: 'GET',
success: function(response) {
console.log('Success');
window.location.href = "{{url_for('route_summ', branch = branch, selected_date = selected_date)}}"
}
});
But that doesn't work either. It establishes a call and returns "Success", but it doesn't redirect to the site. If I were to just go to the site, it works, but I can't get it to link to it without screwing up the other dependent links on it. Can anyone please help me? I'm at my wit's end here.
Okay I figured it out. My first solution would've worked, but I needed to put a "url_for" in my tags. I'm going to leave this up in case any other novices run into this problem.
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.
I've seen several questions here with the similar subject but I can't find anything which is relevant to my situation. I am trying to build jQuery code that is able to build a list of items to save it in an inventory database and I am using .post() those to a additems.php that will add them to that database (after sensitization), as well as the current path name so the .php can send the user back to the same page.
The behavior I am getting is nothing whatsoever with no console error (except the 'this works' alert when I leave that in.) The behavior I am looking for is, the page should redirect to additems.php as an html form action would, execute the code there and redirect back to this page.
Here is my piece of code:
$(document).ready(function(){
$("#button").click(function(){
alert("this works");
var itemsarray = ['itemname'];
var itemattributesarray = ['itemattribute'];
var quantitiesarray = ['1'];
$.post('additems.php', {
items:{items: itemsarray},
itemattributes:{itemattributes: itemattributesarray},
quantities:{quantities: quantitiesarray},
returnpath: window.pathname
});
});
});
Thank you for your time and any suggestions. I've never used this site so please let me know how I can improve my question as well, if you have the time.
An alternative way is,
$.ajax({
'url':'additems.php',
'method' : 'POST',
'data':{
'items':itemsarray,
'itemattributes':itemattributesarray,
'quantities' : quantitiesarray
},
success: function(data){
//here you will get ajax response
console.log(data);
}
});
Anyone can tell me what I'm doing wrong?
I am creating a simple system to get people in and out of user groups and for that purpose I am using Dojo and Perl. (If I could have it my way it would be PHP but I am not the boss.)
At the moment I only use three files, one for Perl, one for JavaScript and one for CSS styles.
The start of the CGI script routes to different functions as follows:
if ($search = $cgi->param('psearch')) {
dbConnect();
jsonSearchPersons($search);
dbDisconnect();
} elsif ($user_id = $cgi->param('person')){
dbConnect();
create_form($user_id);
dbDisconnect();
} elsif ($user_id = $cgi->param('saveuser')) {
save_user();
} else {
mainPage();
};
...
sub save_user {
print $cgi->header(-type=>'text/plain',-charset=>'utf-8');
print("success");
}
The problem I have now is when I want to save the new groups for the user though an Ajax call (a call to this URL: users.cgi?saveuser=xx). This should (in my point of view) be a POST call, so I made this and tried to append the resulting HTML/text in a <div> but it didn't work:
dojo.xhr.post({
url: "/cgi-bin/users.cgi?saveuser="+user_id,
content: {
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
When I do it with dojo.xhr.get(); it works fine, but when I do it with the POST it's like it jumps over that part of the if statement and just appends the mainPage() function. Is there something basic I don't understand between Dojo and Perl? Do I have to set up the pages so it will accept a POST call? Or what am I doing wrong?
NOTE: This is the first "system" I have made though Dojo and Perl. (I'm normally a PHP/jQuery kind of guy who makes everything UI by hand, so I'm kinda new to it.)
Try adding the saveuser-parameter to the content-object of dojo.xhrPost instead of passing it in the url.
You're trying to pass the saveuser-parameter as GET and the other as POST, maybe that confuses your serverside part.
Try it like that:
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
new_groups: group_ids.toString(),
saveuser: user_id
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Found a solution.
The problem was my javascript. When posting to a perl script you use $cgi=new CGI; and all that. This takes both GET and POST variables and validates them. In my javascript/dojo code, i then used an url with GET vars and then made a POST as well. This meant perl could not find out (or was mixing) the two variable types. So when i changed my ajax code (as below) it worked, since $cgi->param('saveuser') both fetches GET and POST of "saveuser" (no change to the perl was needed):
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
saveuser: user_id,
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Kinda wack bug, but im glad since it works great now :D
Line 675 of CGI.pm :
# Some people want to have their cake and eat it too!
# Uncomment this line to have the contents of the query string
# APPENDED to the POST data.
# $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
Made me laugh !
The snippet of JavaScript that I am having trouble with looks like this:
var content_value = encodeURI(document.getElementById("chattext").value)
downloadUrl("/getchats", "POST", "content=" + content_value, onChatsReturned);
This code works, but it only posts the content. How would I have to change this in order to post another item, such as a description? I have all the other code ready and working, I just don't know how the parameters work for downloadUrl.
It's quite hard to say anything for certain since I can't know what downloadUrl() function actually does, but here is a solution that at might solve your problem (if it just passes the 3rd argument to the backend).
downloadUrl("/getchats", "POST", "content=" + content_value + "&description=" + desciption_value, onChatsReturned);
As the comments mention more information on the downloadUrl-function is needed to say for sure.
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="!";