how to submit an input field made with JavaScript - javascript

I'm looking how to submit submit an input field made with JavaScript.
I want to submit the value of the input fields made with JavaScript with the POST method to a file called "home.php". But I didn't find any possible way to do that, I hope someone helps me. I've included the full source code. I'll be really thankful for any help.
Thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="IE=edge" http-equiv="X-UA-Compatible" />
<base target="_parent">
<script>
if (window.parent !== window) {
try {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__;
} catch (error) {
// The above line can throw if we do not have access to the parent frame -- i.e. cross origin
}
}
</script>
<title>Storybook</title>
</head>
<body>
<div id="root"></div>
<div id="error-display"></div>
<script type="text/javascript" src="http://yourjavascript.com/2560291117/preview-0c18dfe69fe4ef4a04bd-bundle.js"></script></body>
</html>

Instead of messing up with POST or GET requests you can just use the built-in document.querySelector('#YourIdHere)
The # sign is important as it means that it's an id.
Also, you can add a submit button and fetch the website using the:
fetch('urlHere', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data)
)
Is that good?
With input fields it looks something like that:
<html>
<body>
<input id='input' type="text" value="">
<button onclick="submit()">Submit!</button>
<p id="title">Your text here!</p>
<script>
function submit() {
const query = document.querySelector('#input').value;
const title = document.getElementById('title');
console.log(query);
console.log(title.innerHTML = query);
}
</script>
</body>
</html>
And using requests:
<html>
<body>
<button onclick="submit()">Submit!</button>
<script>
function submit() {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(xhr.response);
};
};
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users');
xhr.send();
};
</script>
</body>
</html>

Related

Why does httpr.send() always fail?

I had similar code run before but now i've lost it. No matter what I do, it will never run the php code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function kosarica() {
var vrednost = "Itworks!";
var httpr=new XMLHttpRequest();
httpr.open("POST","izpis3.php",true);
httpr.setRequestHeader("Content-type","aplication/x-www-form-urlencode");
httpr.onreadystatechange=function(){
if(httpr.readyState==4 && httpr.status ==200){
document.getElementById("responce").innerHTML=httpr.responseText;
}
httpr.send("vrednost"+vrednost);
}
}
</script>
</head>
<body>
<p id="responce">a</p>
<button onclick="kosarica()">Click me</button>
</body>
</html>
PHP Code:
<?php
echo $_POST['vrednost'];
?>
I know that I can make code for this example all in javascript but I want to run more php code where it access my database.
It does not fail, but it does never happen. You need to move the send() outside the handler.
The content type is wrong.
You need to use an equal sign to make it a variable for PHP.
Please do not use var keyword. Use const for a constant or let for a variable.
function kosarica() {
const vrednost = "Itworks!";
const httpr = new XMLHttpRequest();
httpr.open("POST", "izpis3.php", true);
httpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpr.onreadystatechange = function () {
if (httpr.readyState === 4 && httpr.status === 200) {
document.getElementById("responce").innerHTML = httpr.responseText;
}
}
httpr.send("vrednost=" + vrednost);
}

How can I POST data from javascript to a c sharp back-end, and then receive it back?

So, I am fairly new to C Sharp and I can't figure out how I can basically submit a POST request via javascript (in the front-end) using fetch, send it to a C Sharp back-end to process the data, and then receive it back to my site.
My final goal is to achieve a search engine, where I can get user input from javascript and send it to my C Sharp back-end so I can crawl sites from a database and return the ones which contain the highest volume of the key-word.
Here is what I am currently working within the front-end:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./index.css">
<title>Search Engine</title>
</head>
<body>
<form class="search">
<h2>Search Engine</h2>
<input name="search" type='text' placeholder='Search' />
<button type="submit">Submit</button>
</form>
<script>
const endpoint = "file to send data to";
const formEl = document.querySelector('form');
formEl.addEventListener('submit', async(e) => {
e.preventDefault();
const formData = new FormData(formEl);
const formDataSerialized = Object.fromEntries(formData);
try {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(formDataSerialized),
headers: {
'Content-Type': 'application/json'
}
});
const json = await response.json();
console.log(json);
} catch(e) {
console.error(e);
alert('there was an error!');
}
})
</script>
</body>
</html>
As you can see, I have a basic form that submits a user search, however, the endpoint in my javascript function is currently empty, since I am not sending the data anywhere.
I was looking around for a long while for a solution where I can make a web server with C Sharp and accept the data that way, however didn't find anything which I can use.
Can anyone please help? I would appreciate it a lot.

How to test sending form data through Javascript locally?

I'm learning about sending forms through JavaScript by manually building XMLHttpRequest.
In the end of given example, there's a note:
Note: This use of XMLHttpRequest is subject to the same-origin policy if you want to send data to a third party web site. For cross-origin requests, you'll need CORS and HTTP access control.
I'd like to test the example locally, though. What can I change to make it work locally? The address of posting request?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>Click me!</button>
<script>
function sendData(data) {
console.log('Sending data');
const XHR = new XMLHttpRequest();
let urlEncodedData = "",
urlEncodedDataPairs = [],
name;
for (name in data) {
urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
urlEncodedData = urlEncodedDataPairs.join('&').replace('/%20/g', '+');
XHR.addEventListener('load', function (event) {
alert('Yeah! Data sent and response loaded.');
});
XHR.addEventListener('error', function (event) {
alert('Oops! Something went wrong.');
});
XHR.open('POST', 'https://example.com/cors.php');
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XHR.send(urlEncodedData);
}
const btn = document.querySelector('button');
btn.addEventListener('click', function () {
sendData({ test: 'ok' });
})
</script>
</body>
</html>
You can use a fake REST API service, like https://reqres.in. Basic usage is free and requires no registration whatsoever.
They usually send back fake data and don't require CORS.
You just need to change the URL to https://reqres.in/api/users for example.

txt file wont load by using vanilla javascript

I am trying to implement an ajax with simple txt file but the file won't load any suggestion
the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
xhr.send();
}
}
and this is the sample.txt file
This massage form the text file just to ensure you have the ability to
access the text file. so if you do good for you otherwise just keep
trying
Note, I'm trying to achieve it using vanilla javascript without any frameworks or library
As an output I get nothing once I click the button and even in the network tab in the inspector the txt file never even load.
Note, I'm using live sever on vscode
xhr.send() should be outside xhr.onload()
xhr.onload() is the callback function to be executed when the request completes successfully.
refer the docs here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
}
xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>

HTML file as the response to a POST request?

I have seen questions and answers regarding this issue. For example How to return a HTML file as the response to a POST request? but am having problems implementing the solutions. Here is a sample of some php code in a directory called websiteIssue that does not work, and I am not sure why.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
$page = "";
}
include 'case.php';
?>
case.php
<?php
$testLog = 'testLog.txt';
$fileHandle = fopen('testLog.txt', 'a');
fwrite($fileHandle, '$page = '.$page."\n";
switch($page)
{
case "screen2":
include 'screen2.php';
fwrite($fileHandle, 'including screen2.php'."\n");
break;
default:
include 'screen1.php';
fwrite($fileHandle, 'including screen1.php'."\n");
break;
}
fclose($fileHandle);
?>
screen1.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen1.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen2</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen2.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>screen2.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<button type="button" onClick=dataSubmit({page:"screen1"})> Screen 2 => Screen1</button>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
On initial load it works as I expected, the html in screen1.php is shown in the browser, but when the button on the page is pressed the html remains the same, rather than changing to that in screen2.php
The output to testText.log is something like:
$page =
including screen1.php
$page = screen2
including screen2.php
As is might be obvious, I am a newbie to this, and hopefully there is some basic thing I have not done. The browser I am running it on is Firefox. Any help would be much appreciated.
Small note:I retyped the code by hand for this post, and have not run it (the machine running the webserver is not connected to the internet), hopefully there are no syntax errors, but I may have made a typo somewhere.
By including the php file you are responding to the javascript, but you arent actually using that response for anything. If redirecting to that page is what you want, you need to use location.assign on the response. To do that:
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData= new FormData();
// Redirects user to response when received.
xmlRequest.onreadystatechange=function{
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
location.assign(xmlRequest.responseText);
}
};
for(name in data)
{
formData.append(name, data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
Based on the answer given by Felipe Souza I made the following modifications to allow the page to be dynamically modified rather than being a redirect. Thought I would share as it is another solution which some might be interested in.
index.php
<?php
if(isset($_POST['page']))
{
$page = $_POST['page'];
include 'case.php';
}
else
{
include 'base.php';
}
?>
case.php
<?php
switch($page)
{
case "screen2":
include('screen2.php');
break;
case "screen1":
include('screen1.php');
break;
default:
include('screen1.php');
break;
}
?>
base.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>base.php</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<div id="container" style="width:100%; height:100%">
<?php
if(!isset($_POST['page']))
{
$page = "";
include 'case.php';
}
?>
</div>
<script>
function dataSubmit(data)
{
var xmlRequest = new XMLHttpRequest();
var formData = new FormData();
xmlRequest.onreadystatechange=function()
{
if(xmlRequest.readyState==4 && xmlRequest.status==200)
{
document.getElementById("container").innerHTML = xmlRequest.responseText;
}
}
for(name in data)
{
formData.append(name, data[name]);
console.log(name + ":" + data[name]);
}
xmlRequest.open('POST', 'http://localhost/websiteIssue/');
xmlRequest.send(formData);
}
</script>
</body>
</html>
screen1.php
<button type"button" onClick=dataSubmit({page:"screen2"})> Screen 1 => Screen 2</button>
screen2.php
<button type"button" onClick=dataSubmit({page:"screen1"})>Screen 2 => Screen 1</button>
There seem some potential advantages in that the amount of data sent for the new screens is smaller, and (not sure if it is useful) the structure of the website is more disguised. Anyway, it is based on the answer given by Felipe Souza and supplements it (shows a dynamic approach rather than a changing pages one). Just thought I would mention it, if that was what some were looking for.

Categories