I'm a complete beginner here and facing a problem in passing javascript variable into flask. Please note that my question is completely different from previous question that has been asked.
This is my code:
JavaScript
var dd = {'mvar': 1};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/",
data: JSON.stringify(dd),
success: function (data) {
alert("DONE!")
},
dataType: "json"
});
Flask(edited)
#app.route('/', methods=['GET', 'POST'])
def new():
form = InputForm(request.form)
v = request.get_json().get('mvar')
print(v)
return render_template('new.html',form=form,v=v)
However, when the output that I get when print out the result is "None" while I expected it to be "1"
Really hope that experts can help me, thank you!
The Request.get_json() method is what you are looking for in your Flask code.
data = request.get_json()
edit here is the exact pattern i use which works:
javascript:
$.ajax({
type: "POST",
url: "{{ url_for("get_post_json") }}",
contentType: "application/json",
data: JSON.stringify({hello: "world"}),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(err) {
console.log(err);
}
});
python:
#app.route('/_get_post_json/', methods=['POST'])
def get_post_json():
data = request.get_json()
return jsonify(status="success", data=data)
Instead of using
v = request.form.get('mvar', type=int)
Use this
v = request.get_json().get('mvar')
Once you print v then you should get it.
Related
i have issue to send data in flask from js. I try use ajax.
AJAX code
$.ajax({
type: "GET",
contentType: "application/json;charset=utf-8",
url: "/getmethod/data",
traditional: "true",
data: JSON.stringify({data}),
dataType: "json"
});
Python code
def get_javascript_data(data):
content = request.get_data('data')
jsonify(content)
If u got some tips or tricks please tell me.
new_item = $('#input').val() //value I want to send
$.ajax({
url: '/set_value',
type: 'POST',
data: new_item,
success: function(response){
$('#main').text(response)
}
})
in flask:
new_item = request.get_data()
For my single page web app, I need to:
Send a json from .js to flask (DONE)
Run the input through a python function - getString() and get a str output (DONE)
Send the str output back to the .js file (PROBLEM)
Here is the flask app:
#app.route('/',methods =['GET','POST'])
def index():
req = json.dumps(request.get_json())
if request.method == 'POST':
result = getString(req) #Function outputs a string
return jsonify(result)
else:
print('Not Received')
return render_template('index.html')
if __name__ == '__main__':
app.run()
The problem is that the jsonify(result) is not being sent probably due to the request.method == 'POST' switching to else when jsonify is called. Is there any way to fix my code to send the str output to the .js?
Here is the .js:
//To send info to flask
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json"
});
})
//To receive from Flask
$.ajax({
url: "/",
type: 'GET',
success: function(data) {
console.log(data);
}
});
I think you've misunderstood what GET and POST are, GET is a request that only fetches something from the back end without a message body but a POST can send a body and recieve something.
try this instead:
document.querySelector('#generate').addEventListener('click',function() {
var json_inputs = JSON.stringify(inputs);
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/",
traditional: "true",
data: json_inputs,
dataType: "json",
success: function(data) {
console.log(data);
}
});
})
I have this small but annoying problem. I really not usual with a web thing. I try to request to my php file using ajax jquery. When I want to retrieve the data I send from ajax, it return undefined index. I dunno what's the problem, it make me spend a lot of time to solve it. Thanks
Below is my ajax code
var at=this.name.substring(this.name.length,7);
var value_header = $("#key"+at).val();
var jsObj = { new_value:value_header, id:at, data:'header'};
console.log(JSON.stringify(jsObj));
$.ajax({
type: 'POST',
headers: 'application/urlformencoded',
url: 'admin_crud.php',
data: jsObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log("Sukses");
}
When I call the below code in my php file, the result is 'Undefined index: data'
echo $_POST['data'];
//Edit
So, when I try var_dump($_POST);, the result is array(0) {}. Where is my mistake? I thought I had send the right one
//Edit
As I mention above, I want it to run perfect without error. Thanks
Remove headers, change your datatype to text and catch errors in the ajax call
$.ajax({
type: "POST",
dataType: "text",
data: jsObj,
url: "admin_crud.php",
success: function (result) {
console.log("success", result);
},
error: function (e) {
console.log("Unsuccessful:", e);
}
});
I have another solution beside #Marco Sanchez too, I don't know it always work or not, but in my case, it work :
$.ajax({
type: 'POST',
url: 'admin_crud.php',
headers: "Content-type: application/x-www-form-urlencoded"
data: "new_value="+value_header+"&id="+at+"&data=header",
success: function(data){
console.log("Sukses");
console.log(data);
}
});
I am using ajax to POST a JSON string to Python Flask but get the following error:
Error
This is my JavaScript:
$.ajax({
type: 'POST',
url: window.location.href,
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
And this is my Python:
#app.route('/test', methods=['GET', 'POST'])
def test():
question = request.get_json()
question1 = json.loads(question)
print (question)
return render_template('test.html')
Using print(question) yields the following output (same output when tested in JavaScript using browsers console):
{'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'}
From what I understand, the output should be a string and therefore padded with quotation marks.
Has anyone come across anything similar/know how to fix the issue?
Flask's request.get_json() returns a dict object from the JSON data supplied in the request, so you don't need to call json.loads on it again.
app.py
#app.route('/', methods=['GET'])
def index():
return render_template('index.html')
#app.route('/test', methods=['POST'])
def test():
question = request.get_json()
print(question['question'])
return ''
templates/index.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var questionObj0 = {'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'};
console.log(JSON.stringify(questionObj0));
$.ajax({
type: 'POST',
url: '{{ url_for('test') }}',
data: JSON.stringify(questionObj0),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(msg) {
console.log(msg);
});
</script>
I have an Ajax request that's returning a 404. Here is the JavaScript:
function rowClicked(id) {
console.log(id);
$.ajax({
type: "POST",
url: "Details.aspx/GetComment",
data: { "id": id },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
console.log(result);
}
});
}
And here is the C# method in Details.aspx.cs - the code behind Details.aspx
[WebMethod()]
public static string GetComment(int id)
{
return "Test";
}
Could anyone offer any insight as to why I might be getting a 404 response?
As most of the people stated, your url might be wrong.
Try to use it like this , maybe it will solve the issue :
<%=ResolveUrl("~/Details.aspx/GetComment") %>
Hope this helps.