Because I start to go crazy I really need your help xD
I'm tying to make a simple Ajax POST, and with it I want to send JSON data to python script to save it later on server.
I'm using python 3.6.4 (anaconda3 with wfastcgi.py) for backend and Javascript (jQuery) and Flask for frontend.
Here's what I got from Chrome Dev Tools -> Network:
POST 1 is from local python server Werkzeug, POST 2 is from IIS 7.5.
I'm showing both in hope that it will help locate the problem. I only need a way to fix IIS.
I already tried :
<customHeaders> with Access-Control-Allow-Origin etc
<requestFiltering> with <add verb="POST" allowed="true" />, or <verbs allowUnlisted="true">
changing OPTIONSVerbHandler verb from OPTIONS to POST (don't ask me, found it here)
But it didn't help.
With Failed Request Tracing Rules module I was able to find this:
But I don't know what where in IIS I can change anything with FastCgi to make it work with POST.
My Ajax POST:
$.ajax({
url: "/static/scripts/saveData.py",
type: "post",
data: JSON.stringify(tableObject),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(error){
console.log(error)
}
});
ps. Link to file works because when I change POST to GET I get code from saveData.py in console.log(response).
I think that you forgot to register this method in flask routs:
#app.route('/login', methods=['POST', 'GET'])
Soooo, after close to 2 days of looking in net, tying different ways to make it work, i finally found a way to send a Ajax POST.
Basically I had to change target url "/static/scripts/saveData.py" from local address to Flask url "/annotate" and this enable me to send data with POST and letter process it in views.py (my main flask view file).
$.ajax({
url: "/annotate",
type: "post",
data: JSON.stringify(tableObject),
//data: tableObject,
contentType: "application/json"
});
Now, why this work, and POST to normal .py script doesn't, I don't know.
But at least now I can work with that data.
Related
Im trying to implement paypal with Django using paypalrestsdk.
I followed the code example from the example here: https://prettyprinted.com/blog/1125955/creating-paypal-express-payments-in-flask
But there is this error:
here are my code snippets of template .html, views.py and urls.py
https://gist.github.com/axilaris/1e6e34ba5915abceb0dbd06d46baf08b
here is template code that shows the button:
<div id="paypal-button"></div>
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<script>
var CREATE_PAYMENT_URL = 'http://127.0.0.1:8000/payment_create';
var EXECUTE_PAYMENT_URL = 'http://127.0.0.1:8000/payment_execute';
paypal.Button.render({
env: 'sandbox', // Or 'sandbox'
commit: true, // Show a 'Pay Now' button
payment: function() {
console.log("payment function")
return paypal.request.post(CREATE_PAYMENT_URL).then(function(data) {
console.log("return create payment")
return data.paymentID;
});
},
onAuthorize: function(data) {
return paypal.request.post(EXECUTE_PAYMENT_URL, {
paymentID: data.paymentID,
payerID: data.payerID
}).then(function(res) {
console.log(res.success)
// The payment is complete!
// You can now show a confirmation message to the customer
});
}
}, '#paypal-button');
</script>
What is the problem, how to fix it and what is ppxo_unhandled_error ?
Alternatively, whats the best way to implement paypal properly on Django. (I'm just not seeing any good docs on this)
Django==1.11.7
Your origin is localhost:8000 and you're trying to access a resource at 127.0.0.1:8000. The page appears the same on both localhost:8000 and 127.0.0.1:8000 because localhost (usually) translates to 127.0.0.1 on your system but your browser interprets these two destinations as different addresses. Therefore, your browser is preventing you from accessing the resource at 127.0.0.1:8000 from origin localhost:8000 because the destination resource doesn't respond with a Access-Control-Allow-Origin: http://127.0.0.1:8000 header.
I recommend changing your origin (the URL you're at in your browser) to 127.0.0.1:8000 rather than adding the header. Or changing the JavaScript around to use localhost:8000 addresses.
Access-Control-Allow-Origin (Mozilla)
The Access-Control-Allow-Origin response header indicates whether the response can be shared with resources with the given origin.
This is most common problem regarding Http request when the request(localhost:8000) and Remote Address( http://127.0.0.1:8000/) for web url differ.
If you change your localhost port then also this problem will occured.
try with these two option:
1.Add this extension to your crome download extension from here
2.Get solution from this stack question
Could you please help me with Python-Flask server misunderstanding. I have some project with flask, it perfectly works on local server 127.0.0.1, but when I moved it to the Web Server (blue host), some of my script give me these errors:
Here I have jQuery, Ajax response to show a table without reloading page:
<button class="myButton" id = "Lbutton">Load</button>
<script>
$("#Lbutton").click(function(){
$.ajax({
url: "/table,
type: "get",
data: {jsdata: $( "#select option:selected" ).text()},
success: function(response) {
$("#place_for_suggestions").html(response);
},
error: function(xhr) {
// handle error
}
});
});
</script>
url: "/table, is the link for Flask function:
#FlaskApp2.route('/table')
def table():
modid = request.args.get('jsdata')
return render_template('table.html')
But finally the Server gave me error:
File does not exist: /home1/user/public_html/table
Why direct link for action, server understand like a link for a file?
So, every action to Python-Flask
<form action="/sendemail" method="post">
the Server understand like a link and give an error message !
What I'm doing wrong ?
Solved, I need to put the full path in action and route() decorator #app.route "/.../templates/table.html"
Most likely you need to add the POST method to your route definition.
#FlaskApp2.route('/table')
becomes:
#FlaskApp2.route('/table', methods=['GET', 'POST'])
Check out the documentation here:
http://flask.pocoo.org/docs/0.12/quickstart/#http-methods
Which has an example of an endpoint that accepts both GET and POST HTTP methods.
Also check out a related question: Flask example with POST
Wishing you a Happy New year.!
I am having trouble when i am trying to load a json file from my web server. Actually i do not know java script. I just need this code to work. I am developing a website using Django. One of the django views, serves the client side java script and at the back end on a separate thread, it process some modules and generates a json output.
Now i am accessing this json using the below code.
<script type="text/javascript">
function addmsg(msg) {
document.getElementById("messages").innerHTML = msg;
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "{% static ""%}tmp/{{url_hash}}/{{url_json}}",
cache: false,
timeout: 50000,
success: function (data) {
addmsg(data);
if (!data) {
setTimeout(
waitForMsg,
1500
);
};
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
addmsg("error");
setTimeout(waitForMsg, 15000);
}
});
};
$(document).ready(function () {
waitForMsg();
addmsg("loading");
});
</script>
When i run this, javascript gets served and then it queries for the json file every 1.5 sec.
What happens is, once the file is available on the server, this script loads the file and redirects the page to something like this ,
localhost:8000/+e+/
I dono from where this is getting redirected. I am not redirecting on any views or urls.py is clean.
Please help me with a code which will load this json from webserver when its available and then print the contents.
Thanks
===========update------------------
can anyone please suggest me angular js script for achieving the same ? thanks
==================== Update =====================================
Found the error, Actually the json dict has javascript, which has } { and quotes. Which breaks it.
I suggest looking beyond a lack of knowledge about JavaScript and stepping through all the parts of your problem. For example, use chrome and open the developer tools tab. Reload the page. Look at the url the JavaScript is testing to open. I suspect it is not the url you intend.
This code looks odd:
{% static ""%
Why is there the quote in the middle of the django directive? This isn't a JavaScript issue, just a quoting issue. It's also a warning sign because your JavaScript is using template directives - not an impossible or illegal thing, but a concern that some teams wouldn't allow.
In any case, track down the url that is actually bring invoked, see if it is the one you intend, and check the quoting issue in the httpcall.
I have read different blogs about django and angular, but all of them have client side (HTML+CSS+JS) codes inside django project.
All I want to do is create two projects: One with all client side stack ( HTML+JS+CSS) and another with Django and Django-rest-framework only. This means that I could write all my presentation code in different project and server code in different project but link them together using REST api.
But there comes a threat which I should always consider CSRF against which Django's CSRF Middleware provide nice security.
So, is it possible to put my client codes outside the Django project directory but still get protected against CSRF?
Read the documentation, everything is explained well. The cleanest way to do this is when you will submit your data using Ajax, you have to add a custom header X-CSRFToken. The token can be parsed from the cookies, which should be enabled by the way. Here is a link to the documentation.
The documentation is always the best place to find your questions, you just have to read mate. But anyway, here is an example:
// Using the jquery cookie plugin, you can get the csrf token like this
var csrftoken = $.cookie('csrftoken');
Then in your javascript/Anuglar code, to post or make ajax request, you have to add the X-CSRFToken header before making the POST/PUT request:
// This HTTP method doesn't need protection since you will be reading and not pushing data
// into the server
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// This is for setting up the upcoming ajax request, here you add the header with the
// csrftoken you got it from the cookies
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
NB: This is using jQuery, you can still do the same thing using Angular.
After this you can make your Ajax call and Django will happily accept your request, again RTD please, everything is well explained, you have all of this code examples included.
I am new to Extjs. I wanted to know how can I send a json object to the backend from an extjs page. I am using python to connect to the databse. What I wanted to do was, if an user enters data on the form, that data to be transfered to the database. I am not getting any good tutorials online. Can someone please help??
Thanks in advance.
There are two ways to send Json Object from a form to the Server side for processing and saving in database.
1st way:
Ext.Ajax.request({
url : 'your-server-url-to-post-to',
method : 'POST', //or GET, PUT, DELETE.. case sensitive
jsonData : your-json-object
params : {
//your-request-parameters
},
success : function(response){ //callback function },
failure : function(response) { //callback failure function}
});
For direct form submission:
Ext.form.action.submit({
form : your-form-instance,
method : 'POST',
url : 'url-to-post-to',
params : {
//your request params
}
});
or another way of doing it is :
your-form.submit({
//same config options as above, except form : your-form-instance
});
Read the docs for more config options to suit your needs.. Documentation is pretty good. For learning a good coding style for ext js check out the examples that are part of the download package.