This question already has answers here:
How do I get the different parts of a Flask request's url?
(4 answers)
jQuery posting JSON
(3 answers)
How to get POSTed JSON in Flask?
(13 answers)
Closed 4 years ago.
!! THIS IS NOT A DUPLICATE !!
The question was not how to get an URL in Flask, but how to send data with jQuery to Flask!
I try to send and receive data with python, Flask and jQuery
The problem is that I want the full URL of the website and it is impossible to get it with flask because I make 'POST' requests. So with jQuery, I want to send the current URL.
I don't know how to send data (with jQuery) and receive data (with Flask).
Python/Flask code:
#app.route('/invisible', methods = ['POST'])
def dynamic_refresh():
return jsonify({'somedata': 'data'})
HTML/jQuery code:
<script>
$(document).ready(function() {
window.setInterval(function() {
$.ajax({
type : 'POST',
url : '/invisible',
//I tried to send data from here but it didn't worked
})
.done(function(data) {
console.log(data)
console.log(window.location.href)//the url I want to send
//here I use the data received by the server
})
}, 5000);
});
</script>
Its quite simple, enclose data in JSON array which you want to send through POST request and then retrieve any data from Flask endpoint like this;
var url = $('#url').val().trim(); //get your value from HTML here
var params = {
_url: url,
};
var array = JSON.stringify(params); //enclosed it in json array
$.ajax({
type: "POST",
url: "/invisible",
data: array,
dataType: 'json',
success: function(results){
console.log(results)
}
});
Related
This question already has answers here:
How do I write JSON data to a file?
(16 answers)
Closed 5 years ago.
Trying to understand how to send post requests to my backend (flask).
In my HTML I have 3 checkboxes and a submit button. My submit button returns a javascript array and I'm trying to send that javascript array to an api endpoint 'api/regions' which you can see below.
$(document).ready(function() {
$("#loadData").click(getChecked);
});
function getChecked() {
event.preventDefault();
var checkboxes = $(".form-check input[type=checkbox]:checked");
//toArray: convert checkboxes object to javascript array
var labels = checkboxes.toArray().map(checkbox => checkbox.value);
$.ajax({
url: 'api/regions',
type: "POST",
data: JSON.stringify(labels),
processData: false,
contentType: "application/json; charset=UTF-8",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
In my app.py I have a route for my endpoint api:
#app.route('/api/regions', methods=['POST'])
def regions():
regions = request.json
with open("C:\\test.txt", 'w') as f:
f.write(regions)
if __name__ == "__main__":
app.run(debug=True)
I understand there is no return statement, I'm just trying to write the data I get from
regions = request.json
to a file. "C:\test.txt"
The error I'm getting when trying to do this is 500 which doesn't give me a lot to work with. I'm not sure if what I'm missing is on the front end or back end so hopefully someone could shed some light on where I'm going wrong.
From the flask documentation,
If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.
The key there is that .json is the parsed JSON data, not the original string. If you want to write it to a file, you'll need to convert it back to a string it first, perhaps by using json.dumps():
with open("C:\\test.txt", 'w') as f:
f.write(json.dumps(regions))
This question already has answers here:
Simple Screen Scraping using jQuery
(7 answers)
Closed 5 years ago.
I want to get data from other url which is product info. I want to scrape all of this data for this attribute:
$('[data-b-for-cart]').attr('data-b-for-cart');
And want to export that to csv file.
Not sure hows this should be done any resource would be helpful.
I think I should use the jquery $.get is that right ?
you can try ajax within jquery to scrape. It is not that difficult
$(document).ready(function() {
baseUrl = "http://www.somedomain.com/";
$.ajax({
url: baseUrl,
type: "get",
dataType: "",
success: function(data) {
//do something with data and save as csv file
}
});
});
This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
I'm trying to pass 3 variables that look like this
var location = document.location.pathname;
var search = document.location.search;
var referrer = document.referrer;
Into a PHP file that I can eventually use to send emails, I have never used AJAX before but know that you could use it to achieve this.
Can anyone help me out? Thanks in advance.
A simple Ajax POST method can help you here. Here's an example.
$.ajax({
type: "POST",
url: "ajax.php",
data: {location: location, search: search, referrer: referrer},
success: function(response){
//do something
}
})//ajax end
Now in ajax.php, you can receive the values via $_POST.
PHP Receiving(ajax.php).
var_dump($_POST['location']);
You could do like this:
$.ajax({
type: "POST",
data: {'location': location,
'search': search,
'referrer': referrer
},
url: "Here the path to your php-file",
success: function (data) {
Here you could react on any
}
});
In the php file you receive those data by Post and can handle them.
This question already has answers here:
Jquery Ajax Posting JSON to webservice
(5 answers)
Closed 8 years ago.
How can I send a nested object via POST request?
var name = "test",
path = "?diffCurr%5B%5D=FALSE&diffProv%5B%5D=FALSE",
data = {
datatype:"report",
"value":{
"name":name,
"query":path
}
};
$.ajax({
type:"POST",
url: "resources/savedata.html",
data: data,
success: function(data){
...
},
complete: function(){
...
}
})
When I check in the chrome, in the network tab under "form data", I see this:
datatype:report
value[name]:test
value[query]:?diffCurr%5B%5D=FALSE&diffProv%5B%5D=FALSE
Basically, I was expecting $_POST["value"] to contain an object with name and query.
Basically, I was expecting $_POST["value"] to contain an object with name and query.
It does.
You are just looking at the raw data which is encoded in application/x-www-form-urlencoded with PHP's square bracket syntax for complex objects.
When PHP deserializes it to populate $_POST, it will do so in the form you expect.
One of the easiest way is serializing in a Json string your nested object
$.ajax({
type:"POST",
url: "resources/savedata.html",
data: JSON.stringify(data),
success: function(data){
...
},
complete: function(){
...
}
This question already has an answer here:
jquery ajax form - how to get the redirect url?
(1 answer)
Closed 8 years ago.
Hi I am saving a form using jquery ajax.
$.ajax({
type: "POST",
url: /admin/department/save,
data: $(".formstyles").serialize(),
success: function(data, status,xhr) {
$(contentHolder).html(data);
}});
When this url get a hit it saves the form and redirects to /admin/department/edit/1090
Here, the ajax get is processed and response is received.
I want redirected url from request headers, somehow.
after success you can redirect url
window.location.href = URL;