How to name a audio file when saving into server with POST - javascript

I've being developing a solution for my webpage with Django and javascript, it's a record button so that the user can send feedback and I can store it into the server.
The plan is putting a text input where the user can introduce its name and a file is created with that name. This is my code by now. Can anyone help me with this?
Python views.py
def voice_request(request):
f = open('./Grabaciones/file.wav', 'wb')
f.write(request.body)
f.close()
return HttpResponse('audio received')
Javascript part
function sendData(data) {
let csrftoken = getCookie('csrftoken');
let response=fetch("/salud/voice_request/", {
method: "post",
body: data,
headers: { "X-CSRFToken": csrftoken },
})
}

Welcome at SO.
You have to offer some text input form to the user in order to enable him to send some context. On the backend site, you would then push the data to the database using a Django model which is basically the toolbox for handling data in Django.
Kindly refer to the docu to get a deep dive into it:
https://docs.djangoproject.com/en/3.0/topics/forms/

Related

How to insert data into my database with php without form?

Please help me, I have a game on my website, but I don't know how to insert that poin into my database because I do not use a form.
I also want to ask, how to enter data without using form into the global variable $_POST? (You can use PHP or javascript for it)
<div class="container">
<h2>
Your point :
<span class="poin">120</span> <!-- It will be inserted into the database -->
</h2>
</div>
Without a form, you can send a POST request to your server by using the fetch API.
Just add the following JavaScript code:
const poin = document.querySelector('.container .point').textContent
;(async () => {
await fetch('host:port', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({ point })
})
})()
And replace 'host:port' to the correct host and port (of your server).
With document.querySelector('.container .point') you are selecting the DOM-element which CSS-selector is '.point'.
fetch accepts the following parameters: url and [options]. The [options] (which is optional) is a object with the following properties: method, headers and body, among others.

How to render an ejs template from express using fetch without submitting form?

login.js file:
const form = document.getElementById('loginForm');
form.addEventListener('submit',async(e)=>{
e.preventDefault();
return await fetch(`localhost:8000/route`, {
method: "get",
headers: {
"Content-Type": "application/json",
},
});
}
app.js file:
app.get('/index',(req,res)=>{
res.render('route.ejs');
})
I only get the rendered html as a response but can't render it.I know that using form submission works.But can anyone plz tell me how to render the page without submitting form?Thank you in Advance.
The reason you get HTML as a response and not rendered because you use an AJAX call when using fetch. It doesn't instruct the browser what to do with that response.
You have few options.
Either when you get the response back you handle it in your callback like so:
return await fetch(`localhost:8000/route`, {
method: "get",
headers: {
"Content-Type": "application/json",
},
}).then(res=> {
let htmlText = await response.text();
document.getElementsByTagName('body')[0].innerHTML(bodyContent);
});
Or in fact if you just want to load a new page from your ejs template, set the window to the new location and browser will automatically render the response. Something like so in your login.js:
document.location.href = "/route_that_returns_html";
Note that since your question is generic you can take one of the above approach. However as your code suggests if you are trying to implement a login then the right way to do it is in following steps:
Let the form submit as usual ( not using ajax/fetch)
On server side using express, execute the login routine to authenticate the user.
If the authentication passes issue a res.redirect() to the authenticated page that renders using ejs or if fails, redirect back to login page with error.
Finally this DigitalOcean Article explains how to use ejs properly and is worth a read.

How to save model instance in Django through JavaScript in HTML

I am Building a BlogApp and I am stuck on a Problem
What i am trying to do
I made a instance named user_location in model. I accessed it in template and I write JavaScript code to access User's Location using JavaScript BUT i want my model instance to save the JavaScript's Output country in the Database.
The Problem
I don't know how to save model instance through JavaScript.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
full_name = models.CharField(max_length=100,default='')
user_location = models.CharField(mac_length=100,default'')
profile.html
<script>
$.ajax({
url: "https://geolocation-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function(location) {
$('#country').html(location.country_name);
}
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>Country: <span id="country"></span></div>
#This is my model instance.
{{ profile.user_location }}
What have i tried
I also tried THIS. BUT it didn't work for me.
I don't know what to do.
Any help would be Appreciated.
Thank You in Advance.
Use Ajax to send your data to the backend and let django do it's thing.
You can use fetch api from javascript to storing the data from javascript in ur model db like fetch(your website route) where u had created your form for post request.
You can create post request on ur route to save ur db.
Example-url = "your website post request route"
params =
method:'post',
headers:
'Content-Type': 'application/json'
body: data
fetch(url, params).then(response=> response.json())
.then(data => console.log(data)
)*/

How can i upload json to the body of a request to rails and also independent images along side the json body?

I want to use rails active storage to save files but I also want to send json and somehow have images sent along to be processed and matched up to the main "form" data.
I have active storage all set up and ready to process images and save them into a separate active storage database that gets joined with the database that I am submitting my json data to. The big disconnect is me figuring out how I can "link" the files that I need to submit and make sure they match up with the json data I am submitting to the other database.
Here is the simple code I am using to submit json data to the rails database. This works perfectly and it submits all the text inputs into the database.
const updateMatchedResults = () => {
return
fetch("http://localhost:3000/collections/"+match.id, {
method: 'POST',
headers: new Headers({
'X-CSRF-TOKEN': csrf,
'Content-Type': 'application/json'
}),
body: JSON.stringify(match)
})
.then(response => console.log(response))
}
I am using vuejs so I have a method that detects when someone has added a file. That looks like this:
uploadFile(e) {
console.dir(e.target.files[0]);
}
When someone uploads or changes a file in the file input, it kicks off this javascript and I can see the file details logged in the console. I know that from here I can submit a request to rails to save the file, but it won't have the proper association as it's not being submitted in a form with the rest of the text data.
I expect to be able to upload the files to the active storage database with the proper association to the json data base I am submitting all the text to.

Angularjs $http Service POST, PUT and GET

I am developing application in AngularJS. But I still not so clear the difference of POST, PUT and GET. Usually I use $http GET when I get data from server when server side does not require any front end data to return data to client side as below.
$http.get(configSettings.baseUrl +"retrive_user.php").success(function (data) {
}).error(function() {
console.log("error");
});
When I am using POST is when I server side require front end data in order to return data to client side as following.
$http({
url: configSettings.baseUrl + "insert_message.php",
method: "POST",
data: {
'username': username,
'messageContent' : messsageContent,
'sender_id': usernameID,
'subscribeChannel' : subscribeChannel,
'attachmentType' : attachmentType,
'event' : 'chat_message'
}
}).success(function(response) {
console.log(response);
}).error(function(response) {
console.log(response);
})
});
Even, I want to delete data or edit data in my MySQL database I am using POST method in angularjs as above and then in my PHP server side, I do like following to get data.
$chat_info = file_get_contents("php://input");
$chat_request = json_decode($chat_info,true);
#$username = $chat_request['username'];
#$messageContent = $chat_request['messageContent'];
#$sender_id = $chat_request['sender_id'];
#$subscribeChannel = $chat_request['subscribeChannel'];
#$attachmentType = $chat_request['attachmentType'];
#$event = $chat_request['event'];
I don't know whether this is a correct practice in RESTful API. I understand the difference between POST and GET. I my server side scripting, I just need to get data from client side in order to Create, Update, Read and Delete data from database. What so special about PUT, DELETE and PATCH in RESTful API?
HTTP verbs are probably one of the most cryptic things about the HTTP protocol.
PUT replace the ENTIRE RESOURCE with the new representation provided or you can say that if user want to add new record, he should use PUT.
On the other hand PATCH => As the name said its a kind of patch to update a piece of record. If user can only wants to update a partial record, say just an email address, he should use PATCH.
As PUT method can update all the record so it need more bandwidth or handle full resources instead on
partial. So PATCH was introduced to reduce the bandwidth.
For example :- lets say I am sending new record to server i.e,
{ "first": "Anand Deep", "last": "Singh" }
So I will use Put because I am adding new record. But here has one problem with Put request that when I will use PUT, I have to send all two parameters that is first and last again. so it is mandatory to send all value again
But Patch only send the data which user want to update and it won't effecting or changing other data.So no need to send all value again.
So PUT for creating new record and PATCH is for updating existing record.
Same for DELETE, its tell to server that this request should delete the record which pass it to server.
For more details click on below image or this URL :-

Categories

Resources