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

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.

Related

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.

JavaScript post Fetch API

I want to post with the Fetch API and call an action from my controller but the action is not being loaded like when I would do it with submitting a post form.
function postQuery() {
let query = document.getElementById("query").value;
fetch('/actionName', {
method: 'POST',
body: query,
headers:
{
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(response => {
console.log(response);
})
.then(data => {
console.log('Success:', data);
})
}
/actionName is not being loaded, I am supposed to be directed to a different page.
When I would submit a form like that:
<form action="/actionName" method="post">
the public function actionName would be called but with fetch its not working.
When i try to see the $_POST with var_dump($_POST) inside of actionName, I am getting an empty array...I dont understand this
I see two questions here:
Why is the data not accessible to the server
Why is the brower not redirected to /actionName
Answer to #1:
Make sure the content type header matches the data you are sending, if it is raw json, you should use application/json rather then application/x-www-form-urlencoded. If you want to send a form using fetch API, you would need to either serialize to form to a URL encoded format, or use FormData, for example:
var fd = new FormData(document.getElementById('myForm'))
fetch('/actionName', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data;'
},
body: fd
})
Answer to #2:
Submitting HTML Forms will direct the browser to the forms action, so if I submit a form to /actionName, I will end up seeing the HTML that is returned by the server for that route. Using Fetch API to submit a form is a type of AJAX, which means that it is capable of communicating with the server without needing to load a new page.
With that in mind, you have a few options:
Use a regular form so that the desired default behavior happens
Manually redirect the user somewhere after the fetch promise resolves, something like:
fetch(/*..*/).then(data => {
console.log('Success:', data);
window.location.href = '/otherPage'
})
Render the response HTML without redirecting the user, something like:
fetch(/*..*/).then(data => {
console.log('Success:', data);
data.text().then(rawHTML => {
document.body.parentElement.innerHTML = rawHTML
})
})
My personal intuition would be to go with the first option, as it suits your requirements and is the simplest.

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

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/

html in jade/pug page needs a custom request header tag [duplicate]

How can I set a custom field in POST header on submit a form?
It cannot be done - AFAIK.
However you may use for example jquery (although you can do it with plain javascript) to serialize the form and send (using AJAX) while adding your custom header.
Look at the jquery serialize which changes an HTML FORM into form-url-encoded values ready for POST.
UPDATE
My suggestion is to include either
a hidden form element
a query string parameter
Set a cookie value on the page, and then read it back server side.
You won't be able to set a specific header, but the value will be accessible in the headers section and not the content body.
From FormData documention:
XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
With an XMLHttpRequest you can set the custom headers and then do the POST.
In fact a better way to do it to save a cookie on the client side. Then the cookie is automatically sent with every page header for that particular domain.
In node-js, you can set up and use cookies with cookie-parser.
an example:
res.cookie('token', "xyz....", { httpOnly: true });
Now you can access this :
app.get('/',function(req, res){
var token = req.cookies.token
});
Note that httpOnly:true ensures that the cookie is usually not accessible manually or through javascript and only browser can access it.
If you want to send some headers or security tokens with a form post, and not through ajax, in most situation this can be considered a secure way. Although make sure that the data is sent over secure protocol /ssl if you are storing some sensitive user related info which is usually the case.
Here is what I did in pub/jade
extends layout
block content
script(src="/jquery/dist/jquery.js")
script.
function doThePost() {
var jqXHR = $.ajax({
type:'post'
, url:<blabla>
, headers: {
'x-custom1': 'blabla'
, 'x-custom2': 'blabla'
, 'content-type': 'application/json'
}
, data: {
'id': 123456, blabla
}
})
.done(function(data, status, req) { console.log("done", data, status, req); })
.fail(function(req, status, err) { console.log("fail", req, status, err); });
}
h1= title
button(onclick='doThePost()') Click
You could use $.ajax to avoid the natural behaviour of <form method="POST">.
You could, for example, add an event to the submission button and treat the POST request as AJAX.
If you are using JQuery with Form plugin, you can use:
$('#myForm').ajaxSubmit({
headers: {
"foo": "bar"
}
});
Source: https://stackoverflow.com/a/31955515/9469069
To add into every ajax request, I have answered it here:
https://stackoverflow.com/a/58964440/1909708
To add into particular ajax requests, this' how I implemented:
var token_value = $("meta[name='_csrf']").attr("content");
var token_header = $("meta[name='_csrf_header']").attr("content");
$.ajax("some-endpoint.do", {
method: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader(token_header, token_value);
},
data: {form_field: $("#form_field").val()},
success: doSomethingFunction,
dataType: "json"
});
You must add the meta elements in the JSP, e.g.
<html>
<head>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<meta name="_csrf" content="${_csrf.token}"/>
To add to a form submission (synchronous) request, I have answered it here:
https://stackoverflow.com/a/58965526/1909708

How to set a Header field on POST a form?

How can I set a custom field in POST header on submit a form?
It cannot be done - AFAIK.
However you may use for example jquery (although you can do it with plain javascript) to serialize the form and send (using AJAX) while adding your custom header.
Look at the jquery serialize which changes an HTML FORM into form-url-encoded values ready for POST.
UPDATE
My suggestion is to include either
a hidden form element
a query string parameter
Set a cookie value on the page, and then read it back server side.
You won't be able to set a specific header, but the value will be accessible in the headers section and not the content body.
From FormData documention:
XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.
With an XMLHttpRequest you can set the custom headers and then do the POST.
In fact a better way to do it to save a cookie on the client side. Then the cookie is automatically sent with every page header for that particular domain.
In node-js, you can set up and use cookies with cookie-parser.
an example:
res.cookie('token', "xyz....", { httpOnly: true });
Now you can access this :
app.get('/',function(req, res){
var token = req.cookies.token
});
Note that httpOnly:true ensures that the cookie is usually not accessible manually or through javascript and only browser can access it.
If you want to send some headers or security tokens with a form post, and not through ajax, in most situation this can be considered a secure way. Although make sure that the data is sent over secure protocol /ssl if you are storing some sensitive user related info which is usually the case.
Here is what I did in pub/jade
extends layout
block content
script(src="/jquery/dist/jquery.js")
script.
function doThePost() {
var jqXHR = $.ajax({
type:'post'
, url:<blabla>
, headers: {
'x-custom1': 'blabla'
, 'x-custom2': 'blabla'
, 'content-type': 'application/json'
}
, data: {
'id': 123456, blabla
}
})
.done(function(data, status, req) { console.log("done", data, status, req); })
.fail(function(req, status, err) { console.log("fail", req, status, err); });
}
h1= title
button(onclick='doThePost()') Click
You could use $.ajax to avoid the natural behaviour of <form method="POST">.
You could, for example, add an event to the submission button and treat the POST request as AJAX.
If you are using JQuery with Form plugin, you can use:
$('#myForm').ajaxSubmit({
headers: {
"foo": "bar"
}
});
Source: https://stackoverflow.com/a/31955515/9469069
To add into every ajax request, I have answered it here:
https://stackoverflow.com/a/58964440/1909708
To add into particular ajax requests, this' how I implemented:
var token_value = $("meta[name='_csrf']").attr("content");
var token_header = $("meta[name='_csrf_header']").attr("content");
$.ajax("some-endpoint.do", {
method: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader(token_header, token_value);
},
data: {form_field: $("#form_field").val()},
success: doSomethingFunction,
dataType: "json"
});
You must add the meta elements in the JSP, e.g.
<html>
<head>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<meta name="_csrf" content="${_csrf.token}"/>
To add to a form submission (synchronous) request, I have answered it here:
https://stackoverflow.com/a/58965526/1909708

Categories

Resources