I'm trying to re-render and display values from my Flask.
The idea is using AJAX to send a post request of my file to Flask, and retrieving values from the database, using return render_template to display the '<div>`
if (request.method == "POST"):
jsdata = request.form['javascript_data']
z= db.execute("SELECT * FROM files WHERE fileName=?", (jsdata,))
z= z.fetchall()
return render_template('index.html', z= z, a=a, b=b, c=c)
*other queries for initial render*
return render_template('index.html', a=a, b=b, c=c)
All my other variables are able to display on load except when the POST request comes in. Any idea to go around this issue?
JS file
function display(filenumber) {
var name = document.getElementById(filenumber);
$.post( "/", {
javascript_data: filenumber
}
);
}
Related
I want to send a file with Scalajs-react and Ajax. The sending part is easy with Ajax.send(requestBody: js.Any) method in the onSubmit method of my form (which I took care to stop the event propagation with preventDefault). To build the request body I use FormData(event.target).
def f(e: ReactFormEvent) = {
Ajax
.post("http://localhost:9000/rpc/v1/test/update-dataset")
.setRequestHeader("X-Requested-With", "XMLHttpRequest")
.send({
new FormData(
e.target
.asInstanceOf[dom.raw.HTMLFormElement]
)
})
.validateStatusIs(200)(Callback.throwException)
.asCallback
}
Form(onSubmit = e => f(e) >> e.preventDefaultCB)(
FormGroup("groupInput")(
FormFile(label = "Input")(),
UncontrolledFormControl(ref = ref, defaultValue = "abc")()
),
Button(`type` = "submit")("Submit")
)
Looks good, but for some reason the request body does not contain anything (ex: ------WebKitFormBoundaryAnYzDUdxWxA8hrJR--) as if FormData did not manage to retrieve the data from the form.
Here is a printout of the two children of e.target where we can see that both inputs have a non-empty value:
__reactFiber$ipxb5pt9wbi,[object Object],__reactProps$ipxb5pt9wbi,[object Object],_wrapperState,[object Object],__reactEvents$ipxb5pt9wbi,[object Set],value,C:\fakepath\artifacts.zip,_valueTracker,[object Object]
__reactFiber$ipxb5pt9wbi,[object Object],__reactProps$ipxb5pt9wbi,[object Object],_wrapperState,[object Object],__reactEvents$ipxb5pt9wbi,[object Set],value,abc,_valueTracker,[object Object]
Note: When I manually append items to the FormData, there are present in the body request.
What am I doing wrong?
Not sure why new FormData(formElement) isn't working, but building manually the FormData works. Ex:
send{
val fd = new FormData()
val elem = dom.document
.getElementById("form-inputf")
.asInstanceOf[HTMLInputElement]
fd.append("file", elem.files(0))
fd
}
If only one file needs to be send, one doesn't even need to use FormData at all. Simply relying on the File API is enough. Ex:
send{
val elem = dom.document
.getElementById("form-inputf")
.asInstanceOf[HTMLInputElement]
elem.files(0)
}
I would like to make a simple contact form for my website. I know how to use ajax to send data, but I don't know how to access it on the Node JS server.
If I were to send my data using this code:
var request=new XMLHttpRequest();
request.open("POST","url");
request.send("{value:'10'}");
How can I access my value in the JSON object I pass to the server?
There are a lot of ways to do this.
For example you could create an endpoint on your server e.g. with express http://expressjs.com/. It might look like this
router.post('/your/url', function(req, res, data) {
var value = req.body.value;
// do cool things with value
res.send('cool');
});
You define a post endpoint which will handle your request. Using the request object you can access the JSON object from the request
I used request_.on("data", function(data_){}); to get my data.
If in my client JS I use request.send("my data");
I can access my data by adding a listener to the request_ object in my Node JS server function.
request_.on("data", function(data_){
console.log(data_);// my data
}
I can then slice up my data any way I want to and use it how I see fit. No need for Express.
Here's my client function that is called when the submit button on my contact form is pressed:
function clickSubmit(event_) {
var xmlhttprequest = new XMLHttpRequest();
xmlhttprequest.open("POST", "contact");
xmlhttprequest.send("email=" + html.email.value + "&name=" + html.name.value + "&message=" + html.message.value);
}
And here's my Node JS server function:
function handleRequest(request_, response_) {
switch(request_.url) {
case "/contact":
request_.on("data", function(data_) {
console.log("data: " + data_);// Outputs the string sent by AJAX.
});
break;
}
}
I am trying to render my riot tags on the server side and this works fine. The tags gets rendered on the server side and gets loaded on the client. Problem arises when I try to define my tags along with the definition of my routes using riot.route. The tags gets compiled to its corresponding Js files but on hitting my route it hits an internal server error and the error logged in the console is riot.route is not a function.
Code for my riot route in the script section of my tag.
<script>
var self = this;
this.data = opts.datastore
this.page = opts.datastore[0]
riot.route(function(id)
{
this.page = this.data.filter(function(r) { return r.id == id })[0] || {}
this.update();
})
this.doUpdate = function update()
{
opts.remarks = this.fname.value;
}
</script>
The data here comes from my server.js file via the datastore option and is a json data.
I have searched in this forum for quiet a bit and here's my problem -
I have a ng-repeat in my html which takes in a list of messages(Json object).
Each message JSON has a sender email address - e.g. abc#gmail.com
Now, I have to get the email address from the message and form another REST API request to fetch their images for e.g. - http://<>:8080/getImage/abc#gmail.com (email address dynamic)
So in my code, I'll have a ng-repeat and a ng-src pointing to the image REST URL
If there's no image in server, it returns a 404 and displays a broken image on the UI. How do I handle it? On the other hand, if I make a http request to determine if there's a success message and on failure return a default image, then the whole thing goes through an endless loop. I'll try to create a fiddle and include it for better explanation.
Use the error block to handle such behavior:
function($http) {
var restUrl = 'getImage/abc';
return {
fetchImage: function(imageId) {
var self = this;
return $http.get(restUrl + '/' + imageId).
success(function(data) {
return self.imageUrl = data;
}).
error(function(data) {
return self.imageUrl = "pathToDefaultImage";
});
},
...
I have a Javascript component that when the DOM is loaded it needs to send a request out to our CDN, which may be in a different domain, to see if there is content for this component. If there is, the component will self-instantiate (its a link to open an embedded video in a modal), if not it will self destruct. My question is mainly about the Grails controller I am using to proxy the AJAX request.
Here is the JS in pseudocode:
checkForVideoAssets: function(videoDataUrl){
Ajax.get(videoDataUrl, function(data){
if(data.responseText==='error'){
//tear down the component
}
else{
//if there is data for the video instantiate the component
}
Here is the Grails controller:
def checkForModalVideoAsset = {
def req = new URL("http://" + params.videoUrl + "/expense/videos/")
def connection = req.openConnection()
if(connection.responseCode != 200){
render 'error'
}
if(connection.responseCode == 200){
render req.getText()
}
}
So, to sum up, the JS grabs an attribute from the DOM that has part of a URL (that we define by convention), sends that URL to the controller, the controller attempts to connect to that URL (at our CDN) and then passes that response back to the AJAX success callback inside the responseText part of the XHR object. This feels less than ideal to me, is it possible to pass the actual response back up to the JS function?
The httpbuilder may be usefull to you
I never tried it but something similar!?
def checkForModalVideoAsset = {
def http = new HTTPBuilder("http://" + params.videoUrl )
http.get(
path : "/expense/videos/",
contentType : TEXT ) { resp, reader ->
response.properties=resp.properties //<-- to easy to work but why not try :)
response << resp
}
}