Ajax : append form data to json file without php - javascript

I've been trying for hours to get this thing working.
I'm trying to append the text of Title and the text of Content to a .json file. I've seen a lot of similar problems on here but with php and I'm not allowed to use it (Rule of the teacher).
I tried Fetch API but I found out that it only handles get requests from json files. Yet I only found ajax functions on here where they use $ in front of them.
I just don't know how to include the location of the json file without using php. name file = posts.json.
Example inside json:
Picture json
This is my code JS:
let form = document.getElementById('frm');
form.addEventListener('submit', PostBlog)
function PostBlog(){
let title = document.getElementById("txtTitle");
let content = document.getElementById("txtContent");
let data = {title1: title.value}
//let url = new URL("http://localhost:8080/admin.html");
//let parms = new URLSearchParams({title1: title.value, content1: content.value});
fetch("http://localhost:8080/admin.html",
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
}
).then(receive).then(response => response.text()).then(Succeed).catch(problem)
}
function receive(response) {
if(!(response.ok)){
throw new Error("Didn't Receive " + response.status);
}
return response;
}
function problem(error){
alert("Not Found " + error);
}
function Succeed(data){
alert("Found " + data);
}
HTML important part:
<form id="frm">
<div class="form-group">
<label for="txtTitle">Title</label>
<input type="text" class="form-control" id="txtTitle">
</div>
<div class="form-group">
<label for="txtContent">Content</label>
<textarea class="form-control" id="txtContent" rows="3"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-primary">Reset</button>
</div>
</form>
And finally a picture of the site
Picture of the site

Ajax is a term meaning "Making an HTTP request from JavaScript, running in the browser, without leaving the page".
You can't use it to directly write to data on the server, because browsers aren't allowed to simply write to servers. If that was possible, then the Google homepage would be vandalised 30 times per second.
You need a server-side process to take the HTTP request and write the data to the file (although a database is usually a better bet as that will take care of problems like simultaneous writes). If you don't want to use PHP then you can use any other server-side programming language the server supports. If you don't want to use any of those then you can change your server to one that supports the language you want to use.
I tried Fetch API but I found out that it only handles get requests from json files.
The Fetch API can be used to make more-or-less any kind of request with any kind of payload and any kind of response.
Yet I only found ajax functions on here where they use $ in front of them.
Browsers have two APIs for making Ajax requests. XMLHttpRequest and Fetch. (Fetch is newer).
There is numerous third-party libraries that wrap XMLHttpRequest and/or Fetch to provide alternative APIs. $ is the variable to which jQuery is commonly assigned. Its main Ajax helper function can be found in the ajax property.
The use of a third-party library won't solve the issue that browsers can't write to servers.

Related

How to pass JavaScript variable to Flask?

I want to access the JavaScript variable file in the app.py file but it's giving me a bad request which says "Did not attempt to load JSON data because the request Content-Type was not 'application/json'".
Since I intend to pass only one variable to the Python file, is there not some other shorter method to do so other than using JSON?
#app.route("/", methods=["GET", "POST"])
def index():
if "stop" in request.form:
data = {}
data["file"] = request.json("file")
print(data, file=sys.stderr)
return render_template("index.html")
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="./static/styles/style.css">
<title>Title</title>
</head>
<body>
<form method="post">
<input type="submit" name="start" onclick="startRec" value="start"/>
<input type="submit" name="stop" value="stop"/>
</form>
<script>
const startRec = () => {
var file = {"file" : "whatever"};
$.ajax({
url : "/",
type : "POST",
contentType : "application/json",
data : JSON.stringify(file)
})
.done(function(res){
console.log(res)
});
}
</script>
</body>
</html>
You submit the form and also do your ajax call at same time.
Use a Form or an Ajax function to send data. And not both.
Remove your form, use normal buttons with onclick mapped to your ajax function.
Terminology tips:
Think less in terms of "files" and more in terms of "applications". Your code is stored as text in a file, but when the Python or JS runtime executes the code, it runs as an application in memory, not on disk (where files live).
The client and the server don't share variables. In our case, they share raw data via HTTP requests. A client serializes data (possibly stored in variables) into a raw byte sequence, creates a request with a payload and sends it over the network. The server deserializes the data and creates variable(s) to store the values in the memory reserved for its process. After processing the data, the server sends a response, which can also have a data payload.
This may seem overly pedantic, but having a clear mental picture of the client-server architecture is important to be able to ask the right questions and implement features easily.
Now, there are multiple ways to send data. You can use JSON or form data to format a POST payload, but it looks like you're conflating the two.
if "stop" in request.form: deals with the form, but data["file"] = request.json("file") deals with JSON. When the form is submitted, it POSTs the form data to the route /, and "stop" is indeed in request.form. But the request type isn't JSON, it's form data, hence the error once you attempt to access request.json.
You have two options:
Use form data triggered by the HTML. Put whatever you want the payload to be entirely within the form. No JS will be involved. Here's an example.
Use an asynchronous JS request. Remove the form method="post", attach an event listener to the form submission, call event.preventDefault() inside the handler, then use jQuery to post the data. Here's an example.
Either way, either approach is about as short as it gets. Libraries like htmx exist that create an illusion of simplicity, but there's a learning curve and potential for further misunderstandings when failures arise, so I'd stick to the basics for now--you can get surprisingly far with them.

How do you implement XMLHttpRequest in javascript using ant design Upload component to send to google cloud storage?

I am trying to upload to google cloud storage using the XML api. This is an example form that is used to do that. Thanks Brandon Yarbrough
<form action="http://my-bucket.storage.googleapis.com" method="post" enctype="multipart/form-data">
<input type="text" name="key" value="">
<input type="hidden" name="signature" value="sample_token=">
<input name="file" type="file">
<input type="submit" value="Upload">
</form>
I am also using ant design Upload component to do that.
https://ant.design/components/upload/
The documents indicate to use the 'customRequest' prop to have the ability to implement your own XMLHttpRequest. Furthermore it links to some more documentation that describes the object that 'customRequest' receives, which I've destructured below as an argument.
https://github.com/react-component/upload#customrequest
I've attempted to implement.
render() {
const props = {
name: 'file',
action: '//localhost:3000/my-express-endpoint',
data: {
'key': 'value'
},
customRequest({ onProgress, onError, onSuccess, data, filename, file, withCredentials, action, headers }) {
let data = new FormData(); // Using FormData counting on browser support.
data.append('signature', 'sample_token');
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://my-bucket.storage.googleapis.com', true);
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send(data);
}
};
return (
<div className="container">
<Dragger {...props}>
...drop file here
</Dragger>
</div>
)
}
I am unclear how to execute the customRequest. Since I'm overriding does that make the other props name, action, data outside of the customRequest prop invalid and now handled inside the customRequest prop since those were the same? Also since I'm uploading directly to google cloud storage using the XML api does that mean I no longer have to take care of it with my-express-endpoint and handling it with for example multer on server-side?
For starters: The action and data option properties are not applicable when you provide a customRequest. Thus you are correct, you no longer need your express endpoint since your express server is not involved in the transaction.
The more difficult part is handling the file object. When you use an <input type=file ...> in a form (as in your first example) there is a bit of magic going on behind the scenes.
This magic (reading the file, actually) you will have to do yourself when you create the XHR yourself. Recommended reading: The "Dealing with binary data" section two thirds down the page at https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
But there are better ways. I would suggest using a xhr wrapper that does the work for you. Such as https://github.com/axios/axios, which can handle the File object you get in customRequest directly.

How do Java REST calls relate to the front end of a Web Application?

I am aware of how REST calls work from within a Java Web application. E.g. when a URL is reached its method will be called using HTTP.
For example:
#GET
#Path("people/{id}")
public Response getPersonWithId(#PathParam("id") id) {
//return the person object with that Id
}
What I am unsure of is how this links to the front end?
Is the role of the UI ( i.e. javascript ) just to take a user to the specific URLs so that the back end methods can be called?
E.g. if a user presses a "get details" button, does the button just redirect them to this URL that deails with returning the details, and the back end functionality is then called?
WebService is not actually linked or tied to the front end similar to webapp. Instead, webservice is a service that provides result in the form of JSON/XML, Plain text Format according to request type(get, post, update, delete) and hence, the service can be used by any multiple front end application(not only web application but also smartphone app, desktop app etc.). Also, webservice can be on totally different server.
Let me give you a scenario:
Suppose, you have an front end web site ABC-Website and a backend
webservice on host: www.xyzservice.com/api with following methods:
/product - get request that return all product as list in json format.
/product/id - get request return product detail given id in json
format.
Now, if you simply type in browser www.xyzservice.com/api/product then
all product list will displayed in json format in the browser. That means, You can also read data from webservice directly in browser without front end system and i.e. webservice is not linked/tied to any front end.
Now, you want to use this webservice in your ABC-Website to display all the product list:
You call www.xyzservice.com/api/products and get JSON object that you can use to display in your html page.
<button type="button" onclick="getProducts()">Click Me!</button>
function getProducts(){
$.ajax({
type : "GET",
contentType : "application/json",
url : "http://www.xyzservice.com/api/product",
dataType : 'json',
timeout : 100000,
success : function(data) {
// now you have "data" which is in json format-same data that is displayed on browser.
displayDate(date);
},
error : function(e) {
//do something
},
done : function(e) {
//do something
}
});
}
function displayDate(){
//your codes to parse and display json data in html table in your page.
}
Lets say that your client is a website and you have a Java API.
In the javascript of your website you could do a request to the backend to retrieve the data and then present it to the user. Your javascript (using jQuery as an example) could look like the following:
// here it prints the data retrieved from the backend route (/people/{id}
$.get('http://localhost:3000/people/3',function onDataReceived(data) {
console.log(data);
})
As pointed out, jQuery is not necessary. Here is an example using regular javascript:
this.getRequest('http://localhost:3000/people/3', function onReceived(data) {
});
function getRequest(url, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
in javascript, usually you want to do these request at the background your webpage.
Im gonna try to explain this with an example:
Imagine you have a page that displays a list of cars for sell which can be fetched from the web service provided by java back-end. The back-end have an url that will respond to GET method with a JSON (or XML) object.
What you have is a HTML file where you write a structure for the displayed data and also includes a javascript file that asynchronously calls this webservice, GETs the data, parses the JSON and then it can manipulate it to the form you want to display it on the page.
In different example you can validate forms on the background, or save the forms or do any other stuff that works with the web service API.
For making these asynchronous request you can use different libraries.
Most used is ajax included in jQuery framework or fetch as n standalone library.

Can $http.put write data to JSON file

I apologize for the newbie question but I am getting conflicting answers to this while searching on the net.
I have created an AngularJS app to read from a JSON file using $http.get and display the data as a form with each form element binded with ng-model. Ideally I would like the user to be able to edit the desired field and click save, then have that data updated in the JSON file. I have been told that to do this you will need a 3rd party server like NodeJS, but I am seeing other examples that show it being done in videos. Can someone tell me if this is possible without the 3rd party server and if so what is the best practice for doing this.
Thank you
$http GET (for resource located on client) will not work with the Chrome browser and will give a CORS error (unless you disable Chrome web security by opening Chrome using run .../chrome.exe" --allow-file-access-from-files -disable-web-security). Firefox gives an error saying the JSON in not well formed even though it is. Browsers don't seem to like it.
HTML5 LocalStorage is your best bet for client storage where you wish to perform CRUD operations and have the data survive past page refresh. A good example of this is the [TodoMVC example]
(https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/angularjs)
A very simple example that saves a json file to localstorage and reads the contents of localstorage is shown. The Service contains a getter and a setter method to interact with localstorage.
INDEX.HTML
<body ng-app = "app">
<div ng-controller="MainCtrl">
<form>
<input placeholder="Enter Name.." ng-model="newContact"/>
<button type="submit" class="btn btn-primary btn-lg"
ng-click="addContact(newContact)">Add
</button>
</form>
<div ng-repeat="contact in contacts track by $index">
{{contact.name}}
</div>
</div>
APP.JS
angular.module('app', ['app.services'] )
.controller('MainCtrl', function ($scope, html5LocalStorage) {
//create variable to hold the JSON
var contacts = $scope.contacts = html5LocalStorage.get();
$scope.addContact = function(contact) {
$scope.contacts.push( {"name":contact} ); //Add new value
html5LocalStorage.put($scope.contacts); //save contacts to local storeage
}
});
SERVICES.JS
angular.module('app.services', [] )
.factory('html5LocalStorage', function () {
var STORAGE_ID = 'localStorageWith_nG_KEY'; //the Local storage Key
return {
//Get the localstorage value
get: function ()
{
return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
},
//Set the localstorage Value
put: function (values)
{
localStorage.setItem(STORAGE_ID, JSON.stringify(values));
}
};
});
Otherwise you could use Node and Express and store the JSON file on the server. Use file system module 'fs-extra' to interact with the json file.
You would have to create RESTful API routes for the client to interact with the server using $http and perform CRUD operations.
/put
/get
/delete
/post
I would be interested to see these videos of this being done without the server writing to the file. You cant just "post the .json file" and have it replace the old one, unless you configure your server (apache, nginx, tomcat, node) to do so.

run php query in onchange event

I am newbie here and i having difficulty to construct the mysql query in the javascript. The idea is to run the mysql query when the dropdown value change.
Below are the code:
html code
<select name="cmbStatus" id="cmbStatus" onchange="check()">
<option value="All" selected>All</option>
<option value="New">New</option>
<option value="In Progress">In Progress</option>
<option value="Down">Down</option>
<option value="Complete">Complete</option>
</select>
<label>
<input type="text" name="textfield" id="textfield">
</label
JS code
<script>
function check()
{
document.getElementById("textfield").value = document.getElementById("cmbStatus").value;
}
</script>
PHP code
$query="SELECT * FROM incident_ticket where Status = 'cmbstatus.value' ";
$result=mysql_query($query);
$num=mysql_numrows($result);
Php code runs on the server, while javascript (if not server-side javascript) runs on the client.
This means that you can not run php code directly in a javascript function on javascript events, cause its already ran on the server before the page is even loaded on the client.
What is usually used in cases like this, is called AJAX.
With ajax you send a request to a php script on the server (with the data that you wish to update), and in the php script you run the query.
There are a few different javascript libraries that makes sending requests like this easy, most people would probably recommend using jQuery, in which a simple ajax post request would look something like:
$.ajax({
type: "POST",
url: "thephpscript.php",
data: data,
success: function(){/*onsuccess*/}
});
But this would require you to load the jquery library before doing the request. Which is another question and for which i would recommend reading the jquery docs: http://www.jquery.com
Furthermore:
I would really recommend that you do NOT use the mysql_* functions in PHP either.
The mysql_* api is deprecated and will be removed in future versions of php.
The code you got in your example is also open for sql-injections, which is very bad.
Use mysqli or PDO instead, and either escape the data before using it in query or use prepared statements.
The only way to do that is using AJAX (or similar, but with other data encapsulation methods, like JSON), which is a very broad topic. Too broad to be explained here in detail, but I will give an overview.
Basically AJAX (Asynchronous Javascript And XML) is a way of asynchronously requesting server information by using XML encoding. As the name suggest you will be using Javascript. The Javascript API in most browsers provide in this need with the XMLHttpRequest object (or ActiveXObject in older IE's). So lets create a new object:
ajax = new XMLHttpRequest();
This object provides a few methods and fields, but we will only discuss the most important ones: open(), send(), onreadystatechange, readyState, status and responseXML. To load a webpage (can be anything, but usually this is xml or generated xml from a php page, in your example we are reading nothing, but just requesting to trigger a PHP script) we use the open() method, like this (just an example):
ajax.open("GET", "some_php_file.php");
Now we have built a request we can send it:
ajax.send();
Done! This will most likely trigger your PHP script, but if we want to do it right, we should check for any errors by registering a (anonymous) status change function (the onreadystatechange field). This function will be triggered when the status of the request chances (e.x. from LOADING to DONE)
ajax.onreadystatechange = function()
{
if (ajax.readyState != 4 || ajax.status != 200)
{
// Do some error handling, like displaying a user visible error message or something
// The requested information is available as an XML object in the responseXML field
}
}
readyState = 4 means that the file has been requested (state is DONE) and status is the HTTP response status code for success (200 OK).
You can also use the jQuery library, which simplifies this, but implements essentially the same process.
Hope this helps!
You need to use ajax to execute php code when user change dropdown value on html page.
Use Ajax. you cant directly run MySQL from Javascript. What you can do is, on its on change, using ajax transfer it to a different PHP page, where you can run your SQL script
Use ajax to transfer value to a php file and execute query in that php file on changing the select value
$("#cmbStatus").onchange(function(e) {
jQuery.post("runquery.php", {
selcval:$("#cmbStatus").val()
}, function(data, textStatus){
});
});
in runquery.php execute the php code what you want to perform on change of select value like this
$query="SELECT * FROM incident_ticket where Status = '".$_POST['selcval']."' ";
$result=mysql_query($query);
$num=mysql_numrows($result);
As already mentioned, problem is that PHP script runs on the server while JS runs "real-time" in the browser. You're goal can be acomplished quiet easily though.
The idea is that you'll bind the AJAX call to the onchange event. I recommend using jQuery for that.
JS
$('#cmbStatus').change(function() {
$.post("script.php", { value: this.value });
$('#textfield').val(this.value);
});
script.php
$query="SELECT * FROM incident_ticket where Status = '" . $_POST['value'] . "' ";
$result=mysql_query($query);
$num=mysql_numrows($result);
Replace script.php with the valid url of the script.
I didn't test it so you'll maybe need to change something but I think you'll get the idea.

Categories