This question already has answers here:
replace div content using ajax and jquery
(4 answers)
How to manage a redirect request after a jQuery Ajax call
(34 answers)
Closed 5 years ago.
I am trying to call a function in Flask by clicking a button. When the button is clicked, the following script runs.
JS
$("#load_btn").click(function() {
$.get("/callback");
}
Flask
#app.route('/callback')
def callback():
print('called')
... # code here that needs to run before rendering callback
return render_template('callback.html')
The problem here is, called is printed, and GET /callback HTTP/1.1 200 is logged as well, but callback.html is not rendered - the page stays the same. I'm guessing this is probably not the best approach to solving this problem, but if so what is the recommended approach?
$.get just sends an HTTP request to your server, but doesn't actually do anything anything with the data (in your case, the rendered template) it gets back from the server.
Try something like this:
$("#load_btn").click(function() {
$("html").load("/callback");
}
Or if the template you render doesn't contain any <head> tags, only body content, you can do
$("#load_btn").click(function() {
$("body").load("/callback");
}
Or, you can exchange "body" for a specific element to only replace a specific part of the page.
If you want the user to be redirected, do this:
$("#load_btn").click(function() {
window.location = "/callback";
}
Related
This question already has answers here:
Fetch: POST JSON data
(17 answers)
How to use a link to call JavaScript?
(10 answers)
Closed 3 years ago.
I have a certain JSON object already setted in my HTML code, which via Jinja2 I receive and proceed to perform actions with.
let selectedJson = {{json | safe}}
This is the way I send it in the first place:
#app.route('/pad/analizador222/', methods=['POST', 'GET'])
def analizador222():
littleJSON = {"something" : "something-else"}
mode = 1
return render_template("output.html", json = littleJSON , mode = mode )
Now, after I did some stuff with the object, I need to re-send it back to another "#app.route()" via an HTML LINK, for example:
<a>This is the link I need to click on to send the previously mentioned JSON</a>
Here's the other app.route()
#app.route('/analisis-conversaciones', methods=['POST', 'GET'])
def analisisconversaciones():
return render_template("analysis.html")
I need to do some other stuff that does not matter at the moment with that JSON in "analysis.html"
The question is:
How can I send that JSON object via a common HTML link?
I think POST protocol can help, but in that case I don't know how to use it.
I have simplified my Code to breakdown the Problem and to have a simple Example with a Timestamp for whats actually going wrong.
So please not be suprised why i do a AJAX call, this is for the real functionality of the Servlet.
Its a Servlet and the follwing code is part of a JSP page, im Working on JAVA 1.7 and a Tomcat 7. I run it in Firefox and Chrome.
My goal is to retrieve a value from a Java method and write it on the servlet page into the DIV "ContentCharts".
The Problem is that Javascript does not update the vaule of "zeit" and always writes the same Timestamp into the DIV-Container and on the Console
$(document).ready(function()
{
function ausgabe()
{
<%
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
String JZeit = df.format(now.getTime());
System.out.println("FKT ausgabe zeit:"+ JZeit);
%>
var zeit='<%=JZeit %>';
console.info('Zeit:', zeit);
document.getElementById('ContentCharts').innerHTML = zeit;
}
$("#subtab2").click(function()
{
$.ajax
(
{
url:'overview',
data:{dbname:this.className},
type:'get',
cache:false,
success:function(){ausgabe();},
error:function(){alert('error');}
}
);
}
}
To test this I write the value of the JAVA varible "Jzeit" into the Serverlogs and get this (Click to see the Picture) results when I click the buttons three times. As you can see in the Picture here I get the right Timestamps.
Now I have also post the Value of the JS varialbe "zeit" into the Firebug Console. And now i get the Wrong time Stamps (Click to see the Picture)
The Content in the DIV is refreshing but here is the same Problem like in the Console, its always the same Timestamp.
These are my thoughts and Questions:
Why has the JS variable the wrong value when its right in JAVA?
Is there any option to say JS that it has to update the variable?
Could it be that JS saves the answers of the JAVA code and does not run it anymore, but runs the upper JAVA Code Snippet because there is no direct connection betwen JS and JAVA, like a value allocation?
How can i fix my Problem?
If you need more Informations to help me please ask for it.
You're a bit confused about the ajax pattern.
Note that anything you write in <%= jsp tags %> will be rendered on the server, then sent to the client where it will never change. Therefore your ausgabe function will always return the same result when it is called. Subsequent calls to the function will not make repeated server requests, which is the behavior you're observing.
To fix this, the success function in your ajax call should take an argument which will be instantiated with the response from the server. The java code you've written in the jsp tags in the ausgabe function should be moved to the server and any variables you need should be returned from the overview endpoint. Then, the ausgabe function should be refactored to take an argument containing the server-calculated values, and update your page as desired.
Here is some reading on ajax requests:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://api.jquery.com/jquery.ajax/
This question already has answers here:
Pure JavaScript Send POST Data Without a Form
(13 answers)
Closed 6 years ago.
How can I get Json information from a website API in javascript?
I need to get quotes text from this website http://forismatic.com/en/api/ to put in my quotes generator page.
I think I kinda of get how to great GET requests, but from my understanding this API requires POST requests.
If you have any idea, could you also direct me to the explanation of the code you've written, because I'd also like to understand the underlying logic.
Thanks!
Try this.. Its already working, JSONP
function insertReply(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'http://url.to.json?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);
I'd like to reload a web page after supplying new parameters to it via POST in the same way as would be possible with an HTML form but from within JavaScript (inside an HTML page, but outside the context of a form).
Is this possible as HTTP POST instead of GET request (kind of XMLHttpRequest plus replace the currently shown document)? How could I replace the document, if XMLHttpRequest must be employed (instead of window.location.href)? The second question has been partially answered here.
The way I have always done this (with jquery) is this.
var $form=$(document.createElement('form')).css({display:'none'}).attr("method","POST").attr("action","URLHERE");
var $input=$(document.createElement('input')).attr('name','FIRST NAME HERE').val("FIRST VALUE HERE");
var $input2=$(document.createElemet('input')).attr('name','SECOND NAME HERE').val("SECOND VALUE HERE");
$form.append($input).append($input2);
$("body").append($form);
$form.submit();
This question already has answers here:
Fire Greasemonkey script on AJAX request
(2 answers)
Closed 3 years ago.
I'm using greasemonkey with Firefox to alter what content is displayed when I visit a particular domain. One of the pages contains a dropdown with two elements, let's call them element0 and element1. Whenever it detects a switch from one to the other, it performs an ajax query that alters the page content depending on which one you've selected. So it looks something like this:
$(".dropdown").change(function(){
if($(this).val()=='element0'){
$.ajax({
// fetch some html
});
}
else{
$.ajax({
// fetch some other html entirely
});
I'm happy with what is displayed when element0 is selected - it's element1's associated content I want to alter. So I need a way to trigger my own userscript function only in the second case. I also somehow need it to execute only after the ajax query is complete of course. How do I do this?
I have some basic experience with programming, but know absolutely nothing about jquery, ajax, json etc etc. A friend helped me locate the above ajax for that page so that I could even post a meaningful question. Please bear my level of experience in mind, because I'd really really like to move forward with whatever knowledge/wisdom you guys can offer, but will only be able to do so if I understand it.
Many thanks!
EDIT: The above is javascript that the host is running. I accessed it by saving the page and looking around manually. I am writing userscripts on the client side to alter what my browser displays. So I want to write my own function that responds to their js in the way I described.
AJAX
In ajax you have a tow useful method,
success & compleate
success: with execute if ajax request are work truth
complete: are work when finished ajax function, so you can use this method
example:
complete: function(){
// call another ajax, hide somthing, do any somthing
},
another example:
var all_data = {'user':txtuser,'pass':txtpass};
$.ajax ({
url:"ajax.php",
type:"post",
data:all_data,
beforeSend:function(){
// do somting before send a data
},
statusCode:{
404:function(){
$("#ma").html("Page not found");
},
401:function(){
$("#ma").html(".....");
}
},
success:function (data) {
$("#ma").html(data);// if sucsess
},
complete:function(){ // when complete
$("#user").hide(2000);
$("#pass").hide(2000);
$(".q").hide(2000);
}
});