AJAX POST successful but does not do anything - javascript

I am building a desktop app using electron. I want to keep the list of all the recent files opened, for this I am using jquery ajax. here is my code
// this function is expected to add a file entry to my json file
this.add_recent_file = function(file_id, file_name, date_opened) {
// Execute the ajax command.
$.ajax({
type: 'POST',
url: './data/recent-files.json',
dataType: 'json',
data: {
id: file_id,
name: file_name,
date: date_opened
},
success: function() {
console.log("Success");
}
});
}
and here is my sample json file:
[
{
"id" : "1",
"name": "File.json",
"date": "24-feb-2018"
}
]
the problem is that console says 'Success' but no changes in json file. Reloading the page didn't change anything.

You can use node.js filesystem to write to the json file. check out the following code.
var fs = require('fs');
var $ = require('jquery');
this.add_recent_file = function (object) {
$.ajax({
type: 'GET',
url: './data/recent-files.json',
dataType: 'json',
success: function (files) {
// append the entry to the array.
files[files.length] = object;
// Get JSON string representation of the array.
var str = JSON.stringify(files);
// Now write it to the json file.
fs.writeFileSync(recent_file_url, str);
},
error: function () {
alert('Error updating json file.');
}
});
}

As stated by #Gerrit Luimstra, you need a backend, If you're using PHP, you might use something like this:
data/update.php
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$dateX = $_POST['date'];
//update database code here

Right now you are using AJAX to POST data to a JSON file and hope that this will update the file. This however is not the case.
What you can do instead is use Electron's file system to write changes to the JSON file.
In this case, your function would become something like:
this.add_recent_file = function(file_id, file_name, date_opened) {
// Create the JSON content
var data = {
id: file_id,
name: file_name,
date: date_opened
};
// If you want to prettify the JSON content
data = JSON.stringify(data, null, 2);
// Write it to the file
fs.writeFileSync('../path/to/recent-files.json', data);
}
This however requires you to use the node filesystem package.

Related

Copy file from local to the server nodejs

I am using nodeJS and I would like to upload a file to the server.
I have pug page where the user fill all the information and choose a file with filechooser. Then I want to send all the information on the page to the server. Therefore, I am using ajax to send a json object and given that file object can not be send through a json object I convert the File object to a json object like this:
function uploadGenome() {
var file = $(':file')[0].files[0];
var fileObject = {
'lastMod': file.lastModified,
'lastModDate': file.lastModifiedDate,
'name': file.name,
'size': file.size,
'type': file.type
};
return fileObject;
}
Then I add everything in a Json object:
var data = {};
data.file = uploadGenome();
data.name = inputs[0].value;
data.description = inputs[1].value;
data.start = inputs[3].value;
data.end = inputs[4].value;
And finally, I send everything with ajax:
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: url,
success: function (data) {
console.log('success');
console.log(JSON.stringify(data));
if (data === 'done')
{
window.location.href = "/";
} else {
alert('Error Creating the Instance');
}
},
error: function () {
console.log('process error');
}
});
On the server side with NodeJS I get everything, but now how could I copy the file that I get in data.file on the server ? I mean create a copy on the project folder which is on a server.

How to write JSON array to file in node.js and request it again client side

I'm trying to create a drag-and-drop table with save and load functionality. I'm using code from REDIPS.drag.
When using the REDIPS save function the table content is returned, client side, to the console and alert like this:
[["d2",2,2,"blue","A1"],["d1",4,5,"blue","A2"],["d3",3,2,"blue","A3"],["d4",1,4,"blue","A4"]].
I've tried a few different ways to POST the data to node and write it to file.
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content},
dataType:'json',
contentType: "application/x-www-form-urlencoded"
});
App.js
var testjson = req.body;
var tablestringify2 = JSON.stringify(testjson);
fs.writeFile('views/test.json', tablestringify2,'utf8', function (err) {
if (err) {
// append failed
} else {
// done
}
})
The data saved to file is:
{"table_content":"[[\"ns1.8b\",3,1,\"\",\"ns1.8b\"],[\"ns3.1\",4,2,\"\",\"ns3.1\"]]"}
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: table_content,
dataType:'json',
});
The data is saved to file as:
{"[":{"\"ns1.8b\",3,0,\"\",\"ns1.8b\"":{"\"ns3.1\",3,2,\"\",\"ns3.1\"":""}}}
When I use a GET, I parse the data which returns;
{ table_content: '[["ns1.8b",3,1,"","ns1.8b"],["ns3.1",5,3,"","ns3.1"]]' }
or
{[:{"ns1.8b",3,0,"","ns1.8b":{"ns3.1",3,2,"","ns3.1":""}}}
Either form cant be loaded back into the table using the REDIPS load function.
Is there any way I could get the data in the following format;
[["ns1.8b",3,0,"","ns1.8b"],["ns3.1",3,2,"","ns3.1"]]
...returned on the client side?
Or would it be possible to save it to file like that?
Perform the stringify at the client side:
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content: JSON.stringify(table_content)},
dataType:'json',
});
At the server side you should be able to access req.body.table_content which will be the (JSON) string representation of the array.

Correct path structure to open JSON object using AJAX

I'm trying to create a "mock API" module in JS, so I want to request data from a source (products.json) via a url like myapi.com/get/products. It doesn't have to be a legitimate API.
I have this working using an example JSON object from http://www.jsontest.com - but I'm not sure how to do this with my own external data, products.json
My function:
var displayProductList = (function() {
var productList = {
init: function(uri) {
this.getData(uri);
},
getData: function(uri) {
$.ajax({
context: this,
dataType: 'json',
url: uri,
success: this.runOutput
});
},
runOutput: function(data) {
...
}
}
productList.init('http://echo.jsontest.com/key/value/one/two');
})();
This works OK (I can't run it from JSFiddle as it's not https, but it should work): https://jsfiddle.net/xou1k8y8/1/
So my question is, how would I replace the URL in my code with the path to my directory get/products.json and be able to access the data therein?
For example:
productList.init('localhost/my-project/get/products.json');
Doing the above doesn't work. I've also tried adding /products so I can access the products JSON data below.
My JSON looks like this:
{"products":[
{
"id":"0001",
"title":"The Jungle Book",
"price":"13.60",
"currency":"GBP",
"isbn":"978-0062389503",
"stock":{
"in-stock":"yes",
"stock-quantity":"98"
}
}
};
Your localhost URL is not correct. You need to put // before the hostname in a URL, otherwise it's treated as a directory name.
productList.init('//localhost/my-project/get/products.json');
Note that because of the AJAX same-domain restriction, you can only do this when you loaded the HTML file from http://localhost.
Simply switch the URL for your file path:
getData: function(uri) {
$.ajax({
context: this,
dataType: 'json',
url: 'get/products.json',
success: this.runOutput
});
},
Simple as that c:

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

How to use a JavaScript to load and parse a static JSON file in the server

I'm just starting to use javascript and json.
I need to read data (getInformation function) from a json file when processing an event in a javascript function. So I need it to be synchronic. I don't know if I am missing something in the code, or if I have to create an Request and handle the callback, or if I need to import additional javascript to use json. Because I don't know how to make it work. It doesn't work because at the end the array is empty. Any help is aprreciated.
The json file:
{"Users": [
{"Name": "Jane",
"Points": 67,
"age": 23},
{
"Name": "Sam",
"Points": 65,
"age": 21}
]}
Option 1 - Function called by another function which is processing an event:
var getInformation = function()
{
var path = "./data/users.json";
var informationArray= [];
console.log("Loading ....");
$.getJSON(path, function(data)
{
$.each(data, function(key, val)
{
informationArray.push(key + '-' + val);
});
});
return informationArray;
}
Option 2 - Function called by another function which is processing an event:
var getInformation = function() {
var path = "./data/users.json";
var informationArray= [];
$.ajax({
url: path,
async: false,
dataType: 'json',
success: function(response) {
$.each(response.items,
function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
return informationArray; }
I have seen the following thread and tried what is there but doens't work for me. I would like to know where is the problem in my code or if require any special configuration.
Thread: Is there a version of $getJSON that doesn't use a call back?
When JavaScript is running in a browser it needs to make an AJAX request to the server to access a JSON file. It is possible to write the AJAX request by hand but that is complex and difficult to make work in all browsers. Instead most people use a library like jQuery. You will need to include jQuery in your web page with something like:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
Then in any script tag lower in the html page you should be able to do something like:
$.ajax({
url: "data/users.json",
dataType: "json",
success: function(response) {
$.each(response.Users, function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
see http://api.jquery.com/jQuery.ajax/
To load a JSON file (and not require a callback) you'd use:
var url = 'http://yoursite.com/data/users.json';
var j = [];
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) { j = data;},
async: false
});
alert(j.Users[0].Name);

Categories

Resources