Responding to jQuery Ajax request with Python - javascript

I am currently trying to implement the pre-built inline editor located here: https://github.com/wbotelhos/inplace
Unfortunately, the support documentation leaves a lot to desire and I have very little experience with Javascript, jQuery, or Ajax.
I have been able to successfully implement the HTML edits:
<td><div class="inplace" data-field-name="name" data-field-value="{{people['name']}}" data-url="/update/{{id}}">{{ people['name'] }}</a></td>
The Js:
<script type="text/javascript">
$('.inplace').inplace();
</script>
and have successfully grabbed, and printed the info sent from the Javascript.
#app.route('/update/<id>', methods=["POST", "PATCH"])
#login_required
def update(id):
new_data = request.get_data(as_text=True)
print(new_data)
return "200"
The issue I am facing, is that the Js returns an Undefined value which is what the HTML updates to.
Ignore the return "200" - I have tired several different methods. Success = True, json values, etc and nothing seems to work.
I am sure I am missing something simple.

It looks like you need to print json with the field name that matches your field_name attribute which is name.
So you will need to print something like this. I don't use python, so you will need to follow actual python syntax. Where the word name is correct, but you will need to add the value that you want shown
print('{"name":"NEW FIELD VALUE"}')

Related

How to sanitize PHP posted in comments by users

I am creating a commenting system where users can post comments that can also consist of basic HTML including code. Like this:
<pre><code class="language-php"><?php
echo 'Test';
?></code></pre>
The problem is that I can't sanitize this one server side because the PHP code in the comment will actually run on my server. I tried using JavaScript like this before submitting the form:
$("#comment").val() = $("#comment").val().replace("<?", "<?").replace("?>", "?>");
However, this results in Syntax error.
Is there any way for me to safely post user comments that consist of PHP?
to set a new value of input element using jquery, you need to use this syntax
$("#yourElement").val(newValue);
so change your javascript code to:
$("#comment").val($("#comment").val().replace("<?", "<?").replace("?>", "?>"));
read: http://api.jquery.com/val/

Javascript Value of Variable not updating in Servlet

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/

Using jQuery on a string containing HTML

I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)

jQuery, Ajax and getting a complete html structure back

I'm new to jQuery and to some extent JavaScript programming. I've successfully started to use jQuery for my Ajax calls however I'm stumped and I'm sure this is a newbie question but here goes.
I'm trying to return in an Ajax call a complete html structure, to the point a table structure. However what keeps happening is that jQuery either strips the html tags away and only inserts the deepest level of "text" or the special characters like <,>, etc get replaced with the escaped ones
I need to know how to turn off this processing of the received characters. Using firebug I see the responses going out of my WebServer correctly but the page received by the user and thus processed by jQuery are incorrect. A quick example will so what I mean.
I'm sending something like this
<results><table id="test"><tr>test</tr></table></results>
what shows up on my page if I do a page source view is this.
<results><table....
so you can see the special characters are getting converted and I don't know how to stop it.
The idea is for the <results></results> to be the xml tag and the text of that tag to be what gets placed into an existing <div> on my page.
Here is the JavaScript that I'm using to pull down the response and inserts:
$.post(url, params, function(data)
{
$('#queryresultsblock').text(data)
}, "html");
I've tried various options other than "html" like, "xml", "text" etc. They all do various things, the "html" gets me the closest so far.
The simplest way is just to return your raw HTML and use the html method of jQuery.
Your result:
<table id="test"><tr>test</tr></table>
Your Javascript call:
$.post(url, params, function(data){ $('#queryresultsblock').html(data) })
Another solution with less control — you can only do a GET request — but simpler is to use load:
$("#queryresultsblock").load(url);
If you must return your result in a results XML tag, you can try adding a jQuery selector to your load call:
$("#queryresultsblock").load(url + " #test");
You can't put unescaped HTML inside of XML. There are two options I see as good ways to go.
One way is to send escaped HTML in the XML, then have some JavaScript on the client side unescape that HTML. So you would send
<results><results><table....
And the javascript would convert the < to < and such.
The other option, and what I would do, is to use JSON instead of XML.
{'results': "<table id="test"><tr>test</tr></table>" }
The JavaScript should be able to extract that HTML structure as a string and insert it directly into your page without any sort of escaping or unescaping.
The other thing you could do is create an external .html file with just your HTML code snippet in it. So create include.html with
<results><table id="test"><tr>test</tr></table></results>
As the contents, then use a jquery .load function to get it onto the page. See it in action here.

Pass data to database using javascript Onclick

I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.

Categories